Distortions.java 512 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 5
/*
 **
 ** Distortions.java - Calculate lens distortion parameters from the pattern image
 **
6
 ** Copyright (C) 2011-2020 Elphel, Inc.
Andrey Filippov's avatar
Andrey Filippov committed
7 8
 **
 ** -----------------------------------------------------------------------------**
Andrey Filippov's avatar
Andrey Filippov committed
9
 **
10
 **  Distortions.java is free software: you can redistribute it and/or modify
Andrey Filippov's avatar
Andrey Filippov committed
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
 **  it under the terms of the GNU General Public License as published by
 **  the Free Software Foundation, either version 3 of the License, or
 **  (at your option) any later version.
 **
 **  This program is distributed in the hope that it will be useful,
 **  but WITHOUT ANY WARRANTY; without even the implied warranty of
 **  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 **  GNU General Public License for more details.
 **
 **  You should have received a copy of the GNU General Public License
 **  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 ** -----------------------------------------------------------------------------**
 **
 */

26
import java.awt.Point;
Andrey Filippov's avatar
Andrey Filippov committed
27 28
import java.awt.Rectangle;
import java.awt.geom.Point2D;
Andrey Filippov's avatar
Andrey Filippov committed
29
import java.util.ArrayList;
30
import java.util.Arrays;
31
//import java.util.Arrays;
Andrey Filippov's avatar
Andrey Filippov committed
32 33 34 35 36 37 38
//import java.io.StringWriter;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;

import javax.swing.SwingUtilities;

39
import com.elphel.imagej.calibration.DistortionCalibrationData.GridImageParameters;
40
import com.elphel.imagej.calibration.hardware.CamerasInterface;
41 42
import com.elphel.imagej.cameras.EyesisCameraParameters;
import com.elphel.imagej.cameras.EyesisSubCameraParameters;
Andrey Filippov's avatar
Andrey Filippov committed
43
import com.elphel.imagej.common.DoubleGaussianBlur;
44
import com.elphel.imagej.common.PolynomialApproximation;
45
import com.elphel.imagej.common.ShowDoubleFloatArrays;
46
import com.elphel.imagej.common.WindowTools;
Andrey Filippov's avatar
Andrey Filippov committed
47 48
import com.elphel.imagej.jp4.JP46_Reader_camera;

Andrey Filippov's avatar
Andrey Filippov committed
49 50
import Jama.LUDecomposition;
import Jama.Matrix;
Andrey Filippov's avatar
Andrey Filippov committed
51 52 53 54 55 56
import ij.IJ;
import ij.ImagePlus;
import ij.ImageStack;
import ij.Prefs;
//import ij.process.*;
import ij.gui.GenericDialog;
57
import ij.gui.PointRoi;
Andrey Filippov's avatar
Andrey Filippov committed
58 59 60 61 62
import ij.io.FileSaver;
import ij.io.Opener;
import ij.process.FloatProcessor;
import ij.process.ImageProcessor;
import ij.text.TextWindow;
Andrey Filippov's avatar
Andrey Filippov committed
63 64 65 66 67
//import src.java.org.apache.commons.configuration.*;
// to work both in Eclipse and ImageJ:
// 1 - put commons-configuration-1.7.jar under ImageJ plugins directory (I used ImageJ-Elphel)
// 2 - in Eclipse project properties -> Build Path -> Libraries -> Add External jar
public class Distortions {
68
//	final public double hintedMaxRelativeRadius=1.2; // make adjustable?
69
	final public double hintedMaxRelativeRadiusToDiagonal= 1.3; // 0.96; // make adjustable?
70 71
//    int numInputs=27; // with A8...// 24;   // parameters in subcamera+...
//    int numOutputs=16; // with A8...//13;  // parameters in a single camera
Andrey Filippov's avatar
Andrey Filippov committed
72 73 74 75 76
	public PatternParameters patternParameters;
	public LensDistortionParameters lensDistortionParameters;
	public RefineParameters refineParameters= new RefineParameters(); //create with default values
	public FittingStrategy fittingStrategy=null;
    public double [][][][] gridOnSensor =null; // [v][u][px,py][0-value, 1..14 - derivative]
77
    public double [][] interParameterDerivatives=null; //new double[this.numInputs][]; //partial derivative matrix from subcamera-camera-goniometer to single camera (12x21)
Andrey Filippov's avatar
Andrey Filippov committed
78 79 80 81
    public double []   currentVector; // current variable parameter vector
    public double []   Y=null; // array of "y" - for each grid image, each defined grid node - 2 elements
    public int    []   imageStartIndex=null; // elements containing index of the start point of the selected image, first element 0, last - total number of points.
    public double []   weightFunction=null; //  array of weights for pixels (to fade values near borders), corresponding to Y array
82
	public double [][] dTA_dUV = null; // null or double [2][2] to return averaged {{dU/dAz,dU/dTl}{dV/dAz,dV/dTl}}.inverse
83

Andrey Filippov's avatar
Andrey Filippov committed
84
    public double      sumWeights;
Andrey Filippov's avatar
Andrey Filippov committed
85
    public double [][] targetXYZ=null; // array of target {x,y,z} matching each image each grid point
Andrey Filippov's avatar
Andrey Filippov committed
86 87 88 89
    public double [][] jacobian=null; // partial derivatives of fX (above) by parameters to be adjusted (rows)
    public double []   nextVector; // next variable parameter vector
    public double []   currentfX=null; // array of "f(x)" - simulated data for all images, combining pixel-X and pixel-Y (odd/even)
    public double []   nextfX=null; // array of "f(x)" - simulated data for all images, combining pixel-X and pixel-Y (odd/even)
90

Andrey Filippov's avatar
Andrey Filippov committed
91 92 93 94 95 96 97
    public double      currentRMS=-1.0; // calculated RMS for the currentVector->currentfX
    public double      nextRMS=-1.0; // calculated RMS for the nextVector->nextfX
    public double      firstRMS=-1.0; // RMS before current series of LMA started

    public double      currentRMSPure=-1.0; // calculated RMS for the currentVector->currentfX
    public double      nextRMSPure=-1.0; // calculated RMS for the nextVector->nextfX
    public double      firstRMSPure=-1.0; // RMS before current series of LMA started
Andrey Filippov's avatar
Andrey Filippov committed
98

Andrey Filippov's avatar
Andrey Filippov committed
99 100
    public double lambdaStepUp=   8.0; // multiply lambda by this if result is worse
    public double lambdaStepDown= 0.5; // multiply lambda by this if result is better
Andrey Filippov's avatar
Andrey Filippov committed
101
    public double thresholdFinish=0.001; // (copied from series) stop iterations if 2 last steps had less improvement (but not worsening )
Andrey Filippov's avatar
Andrey Filippov committed
102 103
    public int    numIterations=  100; // maximal number of iterations
    public double maxLambda=      100.0;  // max lambda to fail
Andrey Filippov's avatar
Andrey Filippov committed
104

Andrey Filippov's avatar
Andrey Filippov committed
105 106 107 108 109 110 111 112 113 114
    public double lambda=0.001;        // copied from series
    public double [] lastImprovements= {-1.0,-1.0}; // {last improvement, previous improvement}. If both >0 and < thresholdFinish - done
    public int    iterationStepNumber=0;
    public boolean stopEachStep=  true;  // open dialog after each fitting step
    public boolean stopEachSeries=true;  // open dialog when each fitting series finished
    public boolean stopOnFailure= true;  // open dialog when fitting series failed
    public boolean showParams=   false;   // show modified parameters
    public boolean showThisImages=false; // show debug images for the current ("this" state,before correction) state of parameters
    public boolean showNextImages=false; // show debug images for the current (after correction) state of parameters
    public boolean askFilter=     false; // show debug images for the current (after correction) state of parameters
Andrey Filippov's avatar
Andrey Filippov committed
115

Andrey Filippov's avatar
Andrey Filippov committed
116 117 118
 //   public boolean showGridCorr=  true;  // show grid correction
 //   public boolean showIndividual=true;  // show individual image residuals
 //   public double  corrScale=     1.0;   // scale grid correction before applying
Andrey Filippov's avatar
Andrey Filippov committed
119

Andrey Filippov's avatar
Andrey Filippov committed
120 121 122 123
    public int     seriesNumber=0; // just for the dialog
    public boolean saveSeries=false;   // just for the dialog
    public double [][][] pixelCorrection=null; // for each sensor: corr-X, corr-Y, mask, flat-field-Red, flat-field-Green, flat-field-Blue
    public String []  pathNames=null;
124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140

    // Will have to chage for different resolution
//    public int [][]   pixelCorrectionWHD= null; // For each sensor -width, height, decimation
//    public int        defaultPixelCorrectionDecimation=   1;
//   public int        defaultPixelCorrectionWidth=     2592;
//    public int        defaultPixelCorrectionHeight=    1936;

//    @Deprecated
//    public int        pixelCorrectionDecimation=   1;
//    @Deprecated
//    public int        pixelCorrectionWidth=     2592;
//    @Deprecated
//    public int        pixelCorrectionHeight=    1936;




Andrey Filippov's avatar
Andrey Filippov committed
141
    public double     RMSscale=Math.sqrt(2.0); // errors for x and y are calculated separately, so actual error is larger
Andrey Filippov's avatar
Andrey Filippov committed
142

Andrey Filippov's avatar
Andrey Filippov committed
143 144 145 146 147 148 149 150 151
    public boolean  showIndex=true;
    public boolean  showRMS=true;
    public boolean  showPoints=true;
    public boolean  showLensLocation=true;
    public boolean  showEyesisParameters=true;
    public boolean  showIntrinsicParameters=true;
    public boolean  showExtrinsicParameters=true;
    public int      extraDecimals=0;

Andrey Filippov's avatar
Andrey Filippov committed
152
    public boolean   threadedLMA=true; // use threaded/partial method to solve LMA
Andrey Filippov's avatar
Andrey Filippov committed
153 154 155 156 157 158 159
    public LMAArrays lMAArrays=null;
    public LMAArrays  savedLMAArrays=null;
    public long startTime=0;
    public int debugLevel=2;
    public boolean updateStatus=true;
    public int threadsMax=100;
    public AtomicInteger stopRequested=null; // 1 - stop now, 2 - when convenient
Andrey Filippov's avatar
Andrey Filippov committed
160 161

    public String [] status ={"",""};
162
    public double [] lastUsedManualGridHint_UV = {0.5, 0.5};
163 164 165 166 167 168 169 170 171 172 173 174 175 176

    public int getSensorWidth(int subCam) { return fittingStrategy.distortionCalibrationData.eyesisCameraParameters.getSensorWidth(subCam);} // for the future? different sensors
    public int getSensorHeight(int subCam) { return fittingStrategy.distortionCalibrationData.eyesisCameraParameters.getSensorHeight(subCam);}// for the future? different sensors
    public int getDecimateMasks(int subCam) { return fittingStrategy.distortionCalibrationData.eyesisCameraParameters.getDecimateMasks(subCam);}// for the future? different sensors

    public int getSensorWidth() { return fittingStrategy.distortionCalibrationData.eyesisCameraParameters.getSensorWidth();} // for the future? different sensors
    public int getSensorHeight() { return fittingStrategy.distortionCalibrationData.eyesisCameraParameters.getSensorHeight();}// for the future? different sensors
    public int getDecimateMasks() { return fittingStrategy.distortionCalibrationData.eyesisCameraParameters.getDecimateMasks();}// for the future? different sensors

    public int getSensorCorrWidth(int subCam) { return(getSensorWidth(subCam)-1)/getDecimateMasks(subCam)+1;}
    public int getSensorCorrWidth() { return(getSensorWidth()-1)/getDecimateMasks()+1;}

    public void setSensorWidth(int subCam, int v)  {
    	fittingStrategy.distortionCalibrationData.eyesisCameraParameters.setSensorWidth(subCam, v);
Andrey Filippov's avatar
Andrey Filippov committed
177
    }
178 179
    public void setSensorHeight(int subCam, int v) {fittingStrategy.distortionCalibrationData.eyesisCameraParameters.setSensorHeight(subCam, v);}
    public void setDecimateMasks(int subCam, int v){fittingStrategy.distortionCalibrationData.eyesisCameraParameters.setDecimateMasks(subCam, v);}
180 181 182 183
    
    public double [][] getDtaDuv(){
    	return dTA_dUV;
    }
184 185


Andrey Filippov's avatar
Andrey Filippov committed
186 187 188
    public class LMAArrays {
        public double [][] jTByJ=  null; // jacobian multiplied by Jacobian transposed
        public double []   jTByDiff=null; // jacobian multiplied difference vector
Andrey Filippov's avatar
Andrey Filippov committed
189 190
        @Override
		public LMAArrays clone() {
Andrey Filippov's avatar
Andrey Filippov committed
191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210
        	LMAArrays lma=new LMAArrays();
        	lma.jTByJ = this.jTByJ.clone();
        	for (int i=0;i<this.jTByJ.length;i++) lma.jTByJ[i]=this.jTByJ[i].clone();
        	lma.jTByDiff=this.jTByDiff.clone();
        	return lma;
        }
    }
    public Distortions (){}
	public Distortions (
			LensDistortionParameters lensDistortionParameters,
			PatternParameters patternParameters,
			RefineParameters refineParameters,
			AtomicInteger stopRequested
	){
//		this.patternParameters=patternParameters.clone();  // why clone here?
//		this.lensDistortionParameters=lensDistortionParameters.clone();
		this.patternParameters=patternParameters;  // why clone here?
		this.lensDistortionParameters=lensDistortionParameters;
		this.refineParameters=refineParameters;
		this.stopRequested=stopRequested;
211 212 213
		if (this.lensDistortionParameters!=null) {
			interParameterDerivatives=new double[this.lensDistortionParameters.getNumInputs()][];
		}
Andrey Filippov's avatar
Andrey Filippov committed
214

Andrey Filippov's avatar
Andrey Filippov committed
215
	}
216 217
//	public int getNumInputs(){return numInputs;}
//	public int getNumOutputs(){return numOutputs;}
Andrey Filippov's avatar
Andrey Filippov committed
218 219 220
/**
 * Prerequisites:
 * this.patternParameters, this.fittingStrategy are already initialized
Andrey Filippov's avatar
Andrey Filippov committed
221
 *
Andrey Filippov's avatar
Andrey Filippov committed
222 223 224 225 226 227
 */
	/*
	private void initImageSetAndGrids(){  // never used??
// Calculate patter x,y,z==0 and alpha (1.0 - inside, 0.0 - outside) for the grid
// TODO: and save/restore to file to account for non-perfect grid
		patternParameters.calculateGridGeometry();
Andrey Filippov's avatar
Andrey Filippov committed
228
//  Read all grid data files (4-slice TIFF images) and create  pixelsXY and  pixelsUV arrays
Andrey Filippov's avatar
Andrey Filippov committed
229 230 231 232 233 234 235 236 237 238 239 240 241 242 243
		fittingStrategy.distortionCalibrationData.readAllGrids(patternParameters);
		if (this.debugLevel>3) {
			for (int n=0;n<fittingStrategy.distortionCalibrationData.pixelsXY.length;n++) {
				for (int i=0;i<fittingStrategy.distortionCalibrationData.pixelsXY[n].length;i++){
					System.out.println(n+":"+i+"  "+
							fittingStrategy.distortionCalibrationData.pixelsUV[n][i][0]+"/"+
							fittingStrategy.distortionCalibrationData.pixelsUV[n][i][1]+"  "+
							IJ.d2s(fittingStrategy.distortionCalibrationData.pixelsXY[n][i][0], 2)+"/"+
							IJ.d2s(fittingStrategy.distortionCalibrationData.pixelsXY[n][i][1], 2)
					);
				}
			}
		}
	}
	*/
Andrey Filippov's avatar
Andrey Filippov committed
244

245 246 247 248
	public DistortionCalibrationData getDistortionCalibrationData() {
		return (fittingStrategy == null)?null:fittingStrategy.distortionCalibrationData;
	}

Andrey Filippov's avatar
Andrey Filippov committed
249 250 251 252 253 254 255 256 257
	public void resetGridImageMasks(){
		int numImg=fittingStrategy.distortionCalibrationData.getNumImages();
		System.out.println("resetGridImageMasks()");
		for (int imgNum=0;imgNum<numImg;imgNum++){
			fittingStrategy.distortionCalibrationData.gIP[imgNum].resetMask();
		}
	}
	// TODO - make station-dependent? Pass sensor mask and combine it?
	public void calculateGridImageMasks(
258 259
			final boolean proportional,
			final double gridMarginScale,
Andrey Filippov's avatar
Andrey Filippov committed
260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276
			final double minContrast,
			final double shrinkBlurSigma,
			final double shrinkBlurLevel,
			final int threadsMax,
			final boolean updateStatus
			){
		final int numImg=fittingStrategy.distortionCalibrationData.getNumImages();
		final  DistortionCalibrationData.GridImageParameters [] distortionCalibrationData=this.fittingStrategy.distortionCalibrationData.gIP;
		if (updateStatus) IJ.showStatus("Calculating grid image masks...");
		System.out.print("Calculating grid image masks...");
		System.out.print(" minContrast="+minContrast+" shrinkBlurSigma="+shrinkBlurSigma+" shrinkBlurLevel="+shrinkBlurLevel);

   		final AtomicInteger imageNumberAtomic = new AtomicInteger(0);
   		final AtomicInteger imageFinishedAtomic = new AtomicInteger(0);
   		final Thread[] threads = newThreadArray(threadsMax);
   		for (int ithread = 0; ithread < threads.length; ithread++) {
   			threads[ithread] = new Thread() {
Andrey Filippov's avatar
Andrey Filippov committed
277 278
   				@Override
				public void run() {
Andrey Filippov's avatar
Andrey Filippov committed
279
   					for (int imgNum=imageNumberAtomic.getAndIncrement(); imgNum<numImg;imgNum=imageNumberAtomic.getAndIncrement()){
280 281 282
//   						if (imgNum == 488) {
//   							System.out.println("calculateGridImageMasks(), imgNum="+imgNum);
//   						}
Andrey Filippov's avatar
Andrey Filippov committed
283
   						distortionCalibrationData[imgNum].calculateMask(
284 285
   								proportional,
   								gridMarginScale,
Andrey Filippov's avatar
Andrey Filippov committed
286 287 288 289 290
   			        			minContrast,
   			        			shrinkBlurSigma,
   			        			shrinkBlurLevel);
							final int numFinished=imageFinishedAtomic.getAndIncrement();
   							SwingUtilities.invokeLater(new Runnable() {
Andrey Filippov's avatar
Andrey Filippov committed
291 292
   								@Override
								public void run() {
Andrey Filippov's avatar
Andrey Filippov committed
293 294 295 296 297 298 299 300 301 302 303 304 305 306 307
   									if (updateStatus) IJ.showProgress(numFinished,numImg);
   								}
   							});

   					} // for (int numImage=imageNumberAtomic.getAndIncrement(); ...
   				} // public void run() {
   			};
   		}
   		startAndJoin(threads);
		if (updateStatus) IJ.showProgress(0);
		if (updateStatus) IJ.showStatus("Calculating grid image masks... DONE");
		System.out.println("  Done");

	}

Andrey Filippov's avatar
Andrey Filippov committed
308

Andrey Filippov's avatar
Andrey Filippov committed
309 310 311 312
/**
 * once per fitting strategy series:
 *   1) repeat for each image/point patternParameters.getXYZM(int u, int v) and create
 *      this.targetXYZ;
Andrey Filippov's avatar
Andrey Filippov committed
313 314
 *
 *   2)fittingStrategy.buildParameterMap (int numSeries)
Andrey Filippov's avatar
Andrey Filippov committed
315 316
 *   Creates map from the parameter vector index to the {grid image number, parameter number}
 *   When the parameter is shared by several images, the map points to the one which value will be used
Andrey Filippov's avatar
Andrey Filippov committed
317
 *   (they might be different). Timestamp of the masterImages[] is used to determine which image to use.
Andrey Filippov's avatar
Andrey Filippov committed
318 319
 *   Simultaneously creates this.reverseParameterMap that maps each of the image/parameter to the parameter vector
 *   Needs to be run for each new strategy series
Andrey Filippov's avatar
Andrey Filippov committed
320
 *
Andrey Filippov's avatar
Andrey Filippov committed
321 322 323 324 325
 * 	 3)this.currentVector=fittingStrategy.getSeriesVector(); // and save it in the class instance
 *   Calculate vector of the parameters used in LMA algorithm, extracted from the
 *   individual data, using parameter map (calculated once after changing series)
 *
 *    public double []   currentVector; // current variable parameter vector
Andrey Filippov's avatar
Andrey Filippov committed
326
 *
Andrey Filippov's avatar
Andrey Filippov committed
327 328 329 330 331 332 333 334
 */
	final public int filterMulti=            1;
	final public int filterContrast=         2;
	final public int filterSensor=           4;
	final public int filterTargetMask=       8;
	final public int filterTargetAlpha=     16;
	final public int filterTargetErrors=    32;
	final public int filterMaskBadNodes=    64;
Andrey Filippov's avatar
Andrey Filippov committed
335 336 337
	final public int filterDiameter=       128; // use measured grid "diameter" to change image weight
	final public int filterChannelWeights= 256; // different weights for channels (higher weight for bottom sensors)
	final public int filterYtoX=           512; // different weights for channels (higher weight for bottom sensors)
Andrey Filippov's avatar
Andrey Filippov committed
338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355

	final public int filterForAll=             filterMulti+filterContrast+filterSensor+filterTargetMask+filterTargetAlpha+filterTargetErrors+filterMaskBadNodes+
	filterDiameter+filterChannelWeights+filterYtoX;
	final public int filterForSensor=          filterMulti+filterContrast             +filterTargetMask+filterTargetAlpha+filterTargetErrors+filterMaskBadNodes+
	filterDiameter+filterChannelWeights+filterYtoX;
	final public int filterForTargetGeometry=  filterMulti+filterContrast+filterSensor+filterMaskBadNodes+filterDiameter+filterChannelWeights+filterYtoX;
	final public int filterForTargetFlatField= filterMulti+filterContrast+filterSensor+filterMaskBadNodes+filterDiameter+filterChannelWeights+filterYtoX;

	public int selectFilter(int dfltFilter){
		GenericDialog gd = new GenericDialog("Select series to process");
		int filter=    dfltFilter;
		gd.addCheckbox("filterMulti",         (filterForAll & filterMulti)!=0);
		gd.addCheckbox("filterContrast",      (filterForAll & filterContrast)!=0);
		gd.addCheckbox("filterSensor",        (filterForAll & filterSensor)!=0);
		gd.addCheckbox("filterTargetMask",    (filterForAll & filterTargetMask)!=0);
		gd.addCheckbox("filterTargetAlpha",   (filterForAll & filterTargetAlpha)!=0);
		gd.addCheckbox("filterTargetErrors",  (filterForAll & filterTargetErrors)!=0);
		gd.addCheckbox("filterMaskBadNodes",  (filterForAll & filterMaskBadNodes)!=0);
Andrey Filippov's avatar
Andrey Filippov committed
356 357 358 359 360 361
		gd.addCheckbox("filterDiameter",      (filterForAll & filterDiameter)!=0);
		gd.addCheckbox("filterChannelWeights",(filterForAll & filterChannelWeights)!=0);
		gd.addCheckbox("filterYtoX",          (filterForAll & filterYtoX)!=0);



Andrey Filippov's avatar
Andrey Filippov committed
362 363 364 365 366 367 368 369 370 371
		gd.showDialog();
		if (gd.wasCanceled()) return filter;
		filter=0;
		if (gd.getNextBoolean()) filter |= filterMulti;
		if (gd.getNextBoolean()) filter |= filterContrast;
		if (gd.getNextBoolean()) filter |= filterSensor;
		if (gd.getNextBoolean()) filter |= filterTargetMask;
		if (gd.getNextBoolean()) filter |= filterTargetAlpha;
		if (gd.getNextBoolean()) filter |= filterTargetErrors;
		if (gd.getNextBoolean()) filter |= filterMaskBadNodes;
Andrey Filippov's avatar
Andrey Filippov committed
372 373 374
		if (gd.getNextBoolean()) filter |= filterDiameter;
		if (gd.getNextBoolean()) filter |= filterChannelWeights;
		if (gd.getNextBoolean()) filter |= filterYtoX;
Andrey Filippov's avatar
Andrey Filippov committed
375 376 377
		if (this.debugLevel>1) System.out.println("Using filter bitmap: "+filter);
		return filter;
    }
Andrey Filippov's avatar
Andrey Filippov committed
378

Andrey Filippov's avatar
Andrey Filippov committed
379 380 381 382 383 384 385 386 387 388 389 390 391 392 393
	public void initFittingSeries(
			boolean justSelection, // use series to get selection only
			int filter,
			int numSeries) {
		if (initFittingSeries(
			justSelection, // use series to get selection only
			filter,
			numSeries,
			1)){
			initFittingSeries(
					justSelection, // use series to get selection only
					filter,
					numSeries,
					2);
		}
Andrey Filippov's avatar
Andrey Filippov committed
394

Andrey Filippov's avatar
Andrey Filippov committed
395 396 397 398 399 400 401 402 403 404 405 406
	}
	//returns true if some images were disabled and re-calculation is needed
	public boolean initFittingSeries(
			boolean justSelection, // use series to get selection only
			int filter,
			int numSeries,
			int pass) {
		boolean skipMinVal=this.fittingStrategy.distortionCalibrationData.eyesisCameraParameters.minimalValidNodes<0;
		if ((pass>1) && skipMinVal){ System.out.println("initFittingSeries("+justSelection+","+filter+","+numSeries+"), skipMinVal="+skipMinVal); return false;} // debug - skipping new functionality
		System.out.println("initFittingSeries("+justSelection+","+filter+","+numSeries+"), pass="+pass);
		//TODO: ********* Implement comments above ************
		  // calculate total number of x/y pairs in the selected images
407
		if (numSeries <0 ) justSelection=true;
Andrey Filippov's avatar
Andrey Filippov committed
408 409 410 411 412 413
		if ((pass==1) && (numSeries>=0)) fittingStrategy.invalidateSelectedImages(numSeries); // next selectedImages() will select all, including empty
		if (!justSelection) {
			fittingStrategy.buildParameterMap (numSeries); // also sets currentSeriesNumber
		} else{
			fittingStrategy.currentSeriesNumber=numSeries;
		}
Andrey Filippov's avatar
Andrey Filippov committed
414
		int numXYPairs=0;
Andrey Filippov's avatar
Andrey Filippov committed
415 416 417 418 419 420
		int numImg=fittingStrategy.distortionCalibrationData.getNumImages();
		if (this.debugLevel>3)	System.out.println("initFittingSeries("+numSeries+"), numImg="+numImg);
		if ((pass==1) && (numSeries>=0) && !skipMinVal) fittingStrategy.initSelectedValidImages(numSeries); // copy from selected images

		boolean [] selectedImages=fittingStrategy.selectedImages(numSeries); // -1 OK, will select all
		if (this.debugLevel>3)	System.out.println("initFittingSeries("+numSeries+"), selectedImages.length="+selectedImages.length);
421
		int [] dbg_indices = new int[numImg];
Andrey Filippov's avatar
Andrey Filippov committed
422
		for (int imgNum=0;imgNum<numImg;imgNum++) if (selectedImages[imgNum]) {
423
			dbg_indices[imgNum] = numXYPairs;
Andrey Filippov's avatar
Andrey Filippov committed
424 425 426 427 428 429 430 431
			numXYPairs+=fittingStrategy.distortionCalibrationData.gIP[imgNum].pixelsUV.length;
		}
		this.targetXYZ=new double[numXYPairs][3];
		this.Y= new double[numXYPairs*2];
		this.weightFunction=new double[numXYPairs*2];
		this.sumWeights=0.0;
		this.imageStartIndex=new int [numImg+1];
		// added here, was using pixelCorrectionDecimation==1
432 433 434 435
///		this.pixelCorrectionDecimation=fittingStrategy.distortionCalibrationData.eyesisCameraParameters.getDecimateMasks();
///		this.pixelCorrectionWidth=   fittingStrategy.distortionCalibrationData.eyesisCameraParameters.getSensorWidth();
///		this.pixelCorrectionHeight=  fittingStrategy.distortionCalibrationData.eyesisCameraParameters.getSensorHeight();
///		int sensorCorrWidth= (this.pixelCorrectionWidth-1)/this.pixelCorrectionDecimation+1;
Andrey Filippov's avatar
Andrey Filippov committed
436

Andrey Filippov's avatar
Andrey Filippov committed
437 438 439 440 441
		double [] multiWeight=new double [numImg];
		for (int imgNum=0;imgNum<numImg;imgNum++) multiWeight[imgNum]=0.0;
        double minimalGridContrast=fittingStrategy.distortionCalibrationData.eyesisCameraParameters.minimalGridContrast;
        double shrinkBlurSigma=fittingStrategy.distortionCalibrationData.eyesisCameraParameters.shrinkBlurSigma;
        double shrinkBlurLevel=fittingStrategy.distortionCalibrationData.eyesisCameraParameters.shrinkBlurLevel;
442 443
        double gridMarginScale = fittingStrategy.distortionCalibrationData.eyesisCameraParameters.gridMarginScale; // apply -scaled maximal to grid margins (_extra) for masks
        boolean proportional = false;
Andrey Filippov's avatar
Andrey Filippov committed
444
        calculateGridImageMasks(
445 446
        		proportional,
        		gridMarginScale,
Andrey Filippov's avatar
Andrey Filippov committed
447 448 449 450 451 452 453
        		minimalGridContrast, // final double minContrast,
        		shrinkBlurSigma, //final double shrinkBlurSigma,
        		shrinkBlurLevel, //final double shrinkBlurLevel,
    			100, //final int threadsMax,
    			true //final boolean updateStatus
    			);
//        this.imageSetWeight=new double[this.fittingStrategy.distortionCalibrationData.gIS.length];
Andrey Filippov's avatar
Andrey Filippov committed
454

Andrey Filippov's avatar
Andrey Filippov committed
455 456 457
        if ((filter & this.filterChannelWeights)!=0) calculateChannelsWeights(
        		this.fittingStrategy.currentSeriesNumber,
        		fittingStrategy.distortionCalibrationData.eyesisCameraParameters.balanceChannelWeightsMode);
Andrey Filippov's avatar
Andrey Filippov committed
458

Andrey Filippov's avatar
Andrey Filippov committed
459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476
        for (int imgSet=0;imgSet<this.fittingStrategy.distortionCalibrationData.gIS.length;imgSet++){
        	this.fittingStrategy.distortionCalibrationData.gIS[imgSet].setWeight=0.0;
        	int numUsed=0;
        	int stationNumber=0;
        	int numInSet=((this.fittingStrategy.distortionCalibrationData.gIS[imgSet].imageSet!=null)?
        			this.fittingStrategy.distortionCalibrationData.gIS[imgSet].imageSet.length:0);
        	for (int i=0;i<numInSet;i++){
        		if (this.fittingStrategy.distortionCalibrationData.gIS[imgSet].imageSet[i]!=null) {
        			stationNumber=this.fittingStrategy.distortionCalibrationData.gIS[imgSet].imageSet[i].getStationNumber(); // should be the same for all images
        			int imgNum=this.fittingStrategy.distortionCalibrationData.gIS[imgSet].imageSet[i].imgNumber;
        			if ((imgNum>=0) && selectedImages[imgNum]) numUsed++; // counting only selected in this fitting series, not all enabled !
        		}
        	}
        	if (numUsed>0) {
        		double d;
        		switch (fittingStrategy.distortionCalibrationData.eyesisCameraParameters.weightMultiImageMode){
        		case 0: d=1.0; break;
        		case 1: d=Math.pow(numUsed,fittingStrategy.distortionCalibrationData.eyesisCameraParameters.weightMultiExponent);
Andrey Filippov's avatar
Andrey Filippov committed
477
        		break;
Andrey Filippov's avatar
Andrey Filippov committed
478 479 480 481 482
        		case 2: d=(numUsed>1)?(Math.pow(numUsed,fittingStrategy.distortionCalibrationData.eyesisCameraParameters.weightMultiExponent)):0.001; break; // virtually eliminate single-image sets, but prevent errors
        		case 3: d=numUsed*numUsed; break;
        		default: d=1.0;
        		}
        		d*=fittingStrategy.distortionCalibrationData.eyesisCameraParameters.stationWeight[stationNumber];
Andrey Filippov's avatar
Andrey Filippov committed
483
//        		set weight will be calculated as sum of all points weights
Andrey Filippov's avatar
Andrey Filippov committed
484 485 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 512 513 514 515 516 517 518 519
//        		this.fittingStrategy.distortionCalibrationData.gIS[imgSet].setWeight=d;
        		for (int i=0;i<numInSet;i++){
        			if (this.fittingStrategy.distortionCalibrationData.gIS[imgSet].imageSet[i]!=null) {
        				int imgNum=this.fittingStrategy.distortionCalibrationData.gIS[imgSet].imageSet[i].imgNumber;
        				if ((imgNum>=0) && selectedImages[imgNum]) multiWeight[imgNum]= d;
        			}
        		}
        	}
        }
        int patternMaskIndex=3;
        int patternAlphaIndex=7;
        int patternErrorMaskIndex=8;
		int index=0;
		double weightScaleX=1.0,weightScaleY=1.0;
		if (((filter & this.filterYtoX)!=0) && (this.fittingStrategy.distortionCalibrationData.eyesisCameraParameters.weightYtoX!=1.0)) {
			weightScaleX/=Math.sqrt(this.fittingStrategy.distortionCalibrationData.eyesisCameraParameters.weightYtoX);
			weightScaleY*=Math.sqrt(this.fittingStrategy.distortionCalibrationData.eyesisCameraParameters.weightYtoX);
		}
		double weightSumXY=weightScaleX+weightScaleY;
		for (int imgNum=0;imgNum<numImg;imgNum++){
			this.imageStartIndex[imgNum]=index;
			if (selectedImages[imgNum]) {
				int chnNum=this.fittingStrategy.distortionCalibrationData.gIP[imgNum].channel; // number of sub-camera
				int station=this.fittingStrategy.distortionCalibrationData.gIP[imgNum].getStationNumber(); // number of sub-camera
				int setNumber=this.fittingStrategy.distortionCalibrationData.gIP[imgNum].getSetNumber();
				double [] gridWeight=fittingStrategy.distortionCalibrationData.gIP[imgNum].getGridWeight();
				double gridImageWeight=1.0;
				if (((filter & this.filterDiameter)!=0) && (fittingStrategy.distortionCalibrationData.eyesisCameraParameters.weightDiameterExponent>0.0)) {
					gridImageWeight*=Math.pow(setImageDiameter(imgNum),fittingStrategy.distortionCalibrationData.eyesisCameraParameters.weightDiameterExponent);
				}
				if ((filter & this.filterChannelWeights)!=0) {
					gridImageWeight*=this.fittingStrategy.distortionCalibrationData.eyesisCameraParameters.eyesisSubCameras[station][chnNum].getChannelWeightCurrent();
				}
				for (int pointNumber=0;pointNumber<fittingStrategy.distortionCalibrationData.gIP[imgNum].pixelsUV.length;pointNumber++){

					double [] XYZMP=patternParameters.getXYZMPE(
Andrey Filippov's avatar
Andrey Filippov committed
520
							fittingStrategy.distortionCalibrationData.gIP[imgNum].pixelsUV[pointNumber][0],
Andrey Filippov's avatar
Andrey Filippov committed
521 522 523 524 525 526
							fittingStrategy.distortionCalibrationData.gIP[imgNum].pixelsUV[pointNumber][1],
							station,
							chnNum,
							false);
//		 * @return null if out of grid, otherwise X,Y,Z,mask (binary),R (~0.5..1.2),G,B,alpha (0.0..1.0)
/*					double [] XYZM=patternParameters.getXYZM( // will throw if outside or masked out
Andrey Filippov's avatar
Andrey Filippov committed
527
							fittingStrategy.distortionCalibrationData.gIP[imgNum].pixelsUV[pointNumber][0],
Andrey Filippov's avatar
Andrey Filippov committed
528
							fittingStrategy.distortionCalibrationData.gIP[imgNum].pixelsUV[pointNumber][1]);*/
529 530 531 532
					if ((targetXYZ[index]==null) || (XYZMP==null)) {
						System.out.println("Null problem in imgNum="+imgNum+", point "+pointNumber);
						continue;
					}
Andrey Filippov's avatar
Andrey Filippov committed
533 534 535 536 537 538 539 540 541 542 543 544 545
					this.targetXYZ[index][0]=XYZMP[0];
					this.targetXYZ[index][1]=XYZMP[1];
					this.targetXYZ[index][2]=XYZMP[2];
					double weight=1.0;
					if ((filter & this.filterSensor)!=0) {
						weight*=fittingStrategy.distortionCalibrationData.getMask( // returns 1.0 if sensor mask is not available
								chnNum,
								fittingStrategy.distortionCalibrationData.gIP[imgNum].pixelsXY[pointNumber][0],
								fittingStrategy.distortionCalibrationData.gIP[imgNum].pixelsXY[pointNumber][1]);
					}
//					Individual image mask is needed as some parts can be obscured by moving parts - not present on  all images.
//					grid "contrast" may be far from 1.0 but probably should work OK
///					double gridContrast= fittingStrategy.distortionCalibrationData.gIP[imgNum].pixelsXY[pointNumber][2]-minimalGridContrast;//minimalGridContrast\
546 547 548 549 550
					double dbg;
//					if (weight > 0) {
					if ((weight > 0) && (imgNum == 244)) {
						dbg = weight;
					}
Andrey Filippov's avatar
Andrey Filippov committed
551 552 553 554 555
					if ((filter & this.filterContrast)!=0) {
						double gridContrast= gridWeight[pointNumber];
						weight*=gridContrast;
						if (Double.isNaN(gridContrast) && (this.debugLevel>1)) System.out.println("gridContrast=NaN, imgNum="+imgNum);
					}
556 557 558 559 560
//					if (weight > 0) {
					if ((weight > 0) && (imgNum == 244)) {
						dbg = weight;
					}

Andrey Filippov's avatar
Andrey Filippov committed
561 562 563 564
					if ((filter & this.filterTargetMask)!=0) {
						weight*=XYZMP[patternMaskIndex];//DONE: Use grid mask also (fade out outer grid nodes?)
						if (Double.isNaN(XYZMP[patternMaskIndex]) && (this.debugLevel>1)) System.out.println("XYZMP["+patternMaskIndex+"]=NaN, imgNum="+imgNum);
					}
565 566 567 568
//					if (weight > 0) {
					if ((weight > 0) && (imgNum == 244)) {
						dbg = weight;
					}
Andrey Filippov's avatar
Andrey Filippov committed
569 570 571 572
					if ((filter & this.filterTargetAlpha)!=0) {
						weight*=XYZMP[patternAlphaIndex];//DONE: Use grid mask also (fade out outer grid nodes?)
						if (Double.isNaN(XYZMP[patternAlphaIndex]) && (this.debugLevel>1)) System.out.println("XYZMP["+patternAlphaIndex+"]=NaN, imgNum="+imgNum);
					}
573 574 575 576
//					if (weight > 0) {
					if ((weight > 0) && (imgNum == 244)) {
						dbg = weight;
					}
Andrey Filippov's avatar
Andrey Filippov committed
577 578 579 580
					if ((filter & this.filterTargetErrors)!=0) {
						weight*=XYZMP[patternErrorMaskIndex];//DONE: Use grid mask also (fade out outer grid nodes?)
						if (Double.isNaN(XYZMP[patternErrorMaskIndex]) && (this.debugLevel>1)) System.out.println("XYZMP["+patternErrorMaskIndex+"]=NaN, imgNum="+imgNum);
					}
581 582 583 584
//					if (weight > 0) {
					if ((weight > 0) && (imgNum == 244)) {
						dbg = weight;
					}
Andrey Filippov's avatar
Andrey Filippov committed
585 586 587
					if ((filter & this.filterMulti)!=0) {
						weight*=multiWeight[imgNum];
						if (Double.isNaN(multiWeight[imgNum]) && (this.debugLevel>1)) System.out.println("multiWeight["+imgNum+"]=NaN, imgNum="+imgNum);
Andrey Filippov's avatar
Andrey Filippov committed
588
					}
589 590 591 592
//					if (weight > 0) {
					if ((weight > 0) && (imgNum == 244)) {
						dbg = weight;
					}
Andrey Filippov's avatar
Andrey Filippov committed
593 594 595
					if ((filter & this.filterMaskBadNodes)!=0) {
						if (fittingStrategy.distortionCalibrationData.gIP[imgNum].isNodeBad(pointNumber)) weight=0.0;
					}
596 597 598 599
//					if (weight > 0) {
					if ((weight > 0) && (imgNum == 244)) {
						dbg = weight; // got here
					}
Andrey Filippov's avatar
Andrey Filippov committed
600

Andrey Filippov's avatar
Andrey Filippov committed
601 602 603 604 605
					//fittingStrategy.distortionCalibrationData.eyesisCameraParameters.weightMultiExponent)
					if (((filter & this.filterDiameter)!=0) && (fittingStrategy.distortionCalibrationData.eyesisCameraParameters.weightDiameterExponent>0.0)) {
						weight*=gridImageWeight;
						if (Double.isNaN(gridImageWeight) && (this.debugLevel>1)) System.out.println("gridImageWeight=NaN, imgNum="+imgNum);
					}
606 607 608 609
//					if (weight > 0) {
					if ((weight > 0) && (imgNum == 244)) {
						dbg = weight;
					}
Andrey Filippov's avatar
Andrey Filippov committed
610 611 612 613 614
					if (Double.isNaN(weight)) {
						weight=0.0; // find who makes it NaN
						if (Double.isNaN(multiWeight[imgNum])) System.out.println("weight is null, imgNum="+imgNum);
					}

Andrey Filippov's avatar
Andrey Filippov committed
615

Andrey Filippov's avatar
Andrey Filippov committed
616 617 618 619
					this.weightFunction[2*index]=  weight*weightScaleX;
					this.weightFunction[2*index+1]=weight*weightScaleY;
					this.sumWeights+=              weight*weightSumXY;
	        		this.fittingStrategy.distortionCalibrationData.gIS[setNumber].setWeight+=2.0*weight;  // used for variances - proportional to the set weight
620
					if ((this.pixelCorrection==null) || (this.pixelCorrection[chnNum] == null)){
Andrey Filippov's avatar
Andrey Filippov committed
621 622
						this.Y[2*index]=  fittingStrategy.distortionCalibrationData.gIP[imgNum].pixelsXY[pointNumber][0];
						this.Y[2*index+1]=fittingStrategy.distortionCalibrationData.gIP[imgNum].pixelsXY[pointNumber][1];
623 624 625 626 627 628 629 630
						if (Double.isNaN(this.Y[2*index]) || Double.isNaN(this.Y[2*index+1])) {
							System.out.println("Bug 1 in initFittingSeries(): NaN! distortionCalibrationData.gIP["+imgNum+"].pixelsXY["+pointNumber+"][0]="+
						          fittingStrategy.distortionCalibrationData.gIP[imgNum].pixelsXY[pointNumber][0]+
						          ", distortionCalibrationData.gIP["+imgNum+"].pixelsXY["+pointNumber+"][1]="+
						          fittingStrategy.distortionCalibrationData.gIP[imgNum].pixelsXY[pointNumber][1]);
							this.Y[2*index]=      0.0;
							this.Y[2*index + 1]=  0.0;
						}
Andrey Filippov's avatar
Andrey Filippov committed
631
					} else {
Andrey Filippov's avatar
Andrey Filippov committed
632
// TODO: remove and use new code (if tested OK)
Andrey Filippov's avatar
Andrey Filippov committed
633 634 635 636
						double [] pXY={
								fittingStrategy.distortionCalibrationData.gIP[imgNum].pixelsXY[pointNumber][0],
								fittingStrategy.distortionCalibrationData.gIP[imgNum].pixelsXY[pointNumber][1]
						};
Andrey Filippov's avatar
Andrey Filippov committed
637
// TODO: Should it be interpolated? Correction is normally small/smooth, so it may be not important
638 639
						int indexXY=((int) Math.floor(pXY[0]/getDecimateMasks(chnNum))) +
						((int) Math.floor(pXY[1]/getDecimateMasks(chnNum)))*getSensorCorrWidth(chnNum);
Andrey Filippov's avatar
Andrey Filippov committed
640 641 642
						if (this.pixelCorrection[chnNum][0].length<=indexXY){
							System.out.println("initFittingSeries("+numSeries+") bug:");
							System.out.println("this.pixelCorrection["+chnNum+"][0].length="+this.pixelCorrection[chnNum][0].length);
643
							System.out.println("indexXY="+indexXY+" pXY[0]="+pXY[0]+", pXY[1]="+pXY[1]+" sensorCorrWidth="+getSensorCorrWidth(chnNum));
Andrey Filippov's avatar
Andrey Filippov committed
644

Andrey Filippov's avatar
Andrey Filippov committed
645 646 647
						} else {
							this.Y[2*index]=  pXY[0]-this.pixelCorrection[chnNum][0][indexXY]; //java.lang.ArrayIndexOutOfBoundsException: 3204663
							this.Y[2*index+1]=pXY[1]-this.pixelCorrection[chnNum][1][indexXY];
648 649 650 651 652 653 654 655 656 657 658

							if (Double.isNaN(this.Y[2*index]) || Double.isNaN(this.Y[2*index+1])) {
								System.out.println("Bug 2 in initFittingSeries(): NaN! this.pixelCorrection["+chnNum+"][0]["+indexXY+"]="+
										this.pixelCorrection[chnNum][0][indexXY]+
							          ", this.pixelCorrection["+chnNum+"][1]["+indexXY+"]="+
							          this.pixelCorrection[chnNum][1][indexXY]+
							          ", pXY[0]="+pXY[0]+", pXY[1]="+pXY[1]+
							          ", imgNum="+imgNum+", pointNumber="+pointNumber);
								this.Y[2*index]=      0.0;
								this.Y[2*index + 1]=  0.0;
							}
Andrey Filippov's avatar
Andrey Filippov committed
659
						}
Andrey Filippov's avatar
Andrey Filippov committed
660 661
// TODO: remove above and un-comment below	(after testing)
/*
Andrey Filippov's avatar
Andrey Filippov committed
662 663 664 665 666 667 668 669 670 671 672 673 674
						double [] vector=interpolateCorrectionVector(
								chnNum,
								fittingStrategy.distortionCalibrationData.gIP[imgNum].pixelsXY[pointNumber][0],
								fittingStrategy.distortionCalibrationData.gIP[imgNum].pixelsXY[pointNumber][1]);
						this.Y[2*index]=  pXY[0]-vector[0];
						this.Y[2*index+1]=pXY[1]-vector[1];
*/
					}
					index++;
				}
//				numXYPairs+=fittingStrategy.distortionCalibrationData.gIP[imgNum].pixelsUV.length; ??
			}
		}
Andrey Filippov's avatar
Andrey Filippov committed
675
		this.imageStartIndex[numImg]=index; // one after last
Andrey Filippov's avatar
Andrey Filippov committed
676
		if ((pass==1) && (numSeries>=0) && !skipMinVal){
677
    		// count non-zero weight nodes for each image, disable image if this number is less than
Andrey Filippov's avatar
Andrey Filippov committed
678 679 680 681 682 683 684 685 686 687
    		int needReCalc=0;
    		for (int imgNum=0;imgNum<numImg;imgNum++) if (selectedImages[imgNum]) {
    			index=this.imageStartIndex[imgNum];
    			int numValidNodes=0;
    			for (int pointNumber=0;pointNumber<fittingStrategy.distortionCalibrationData.gIP[imgNum].pixelsUV.length;pointNumber++){
    				if (2*(index+pointNumber)>=this.weightFunction.length){
    					System.out.println("BUG@535: this.weightFunction.length="+this.weightFunction.length+" index="+index+
    							" pointNumber="+pointNumber+" imgNum="+imgNum+" pixelsUV.length="+
    							fittingStrategy.distortionCalibrationData.gIP[imgNum].pixelsUV.length+
    							" numXYPairs="+numXYPairs);
Andrey Filippov's avatar
Andrey Filippov committed
688

Andrey Filippov's avatar
Andrey Filippov committed
689 690
    					continue;
    				}
691 692 693
    				if (this.weightFunction[2*(index+pointNumber)]>0.0) {
    					numValidNodes++; //OOB 5064
    				}
Andrey Filippov's avatar
Andrey Filippov committed
694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712
    			}
    			if (numValidNodes<this.fittingStrategy.distortionCalibrationData.eyesisCameraParameters.minimalValidNodes){
    				this.fittingStrategy.invalidateSelectedImage(numSeries,imgNum);
    				needReCalc++;
    				if (this.debugLevel>1){
    					System.out.println("Number of valid nodes in image #"+imgNum+" is "+numValidNodes+" < "+
    							this.fittingStrategy.distortionCalibrationData.eyesisCameraParameters.minimalValidNodes+
    							", this image will be temporarily disabled");
    				}
    			}
    		}
    		if (needReCalc>0) {
    			if (this.debugLevel>1) System.out.println("Number of temporarily disabled images="+needReCalc );
    			return true; // will need a second pass
    		} else {
    			if (this.debugLevel>1) System.out.println("No images disabled, no need for pass #2");
    		}
    	}
		// Normalize set weights
713
		int numSetsUsed=0+0;
Andrey Filippov's avatar
Andrey Filippov committed
714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729
		double totalSetWeight=0.0;
        for (int imgSet=0;imgSet<this.fittingStrategy.distortionCalibrationData.gIS.length;imgSet++){
        	if (this.fittingStrategy.distortionCalibrationData.gIS[imgSet].setWeight>0){
        		numSetsUsed++;
        		totalSetWeight+=this.fittingStrategy.distortionCalibrationData.gIS[imgSet].setWeight;
        	}
        }
        double setWeightScale=numSetsUsed/totalSetWeight;
        if (numSetsUsed>0){
            for (int imgSet=0;imgSet<this.fittingStrategy.distortionCalibrationData.gIS.length;imgSet++){
            	if (this.fittingStrategy.distortionCalibrationData.gIS[imgSet].setWeight>0){
            		numSetsUsed++;
            		this.fittingStrategy.distortionCalibrationData.gIS[imgSet].setWeight*=setWeightScale;
            	}
            }
        }
730
// last? not here! numSetsUsed counted twice (should be = 1, is 2)
Andrey Filippov's avatar
Andrey Filippov committed
731
//		this.imageStartIndex[numImg]=index;
Andrey Filippov's avatar
Andrey Filippov committed
732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749
		if (justSelection) {
			this.currentVector = null;
			this.lambda=0.0;

		} else {
			this.currentVector =fittingStrategy.getSeriesVector(); // here?
			// for now - use common parameters, later maybe restore /add individual
			//    	this.lambda=fittingStrategy.getLambda();
			//    	was commented out???

			this.lambda=fittingStrategy.getLambda();
		   	if ((this.fittingStrategy.varianceModes!=null)
		   			&& (this.fittingStrategy.varianceModes[numSeries]!=this.fittingStrategy.varianceModeDisabled)) fittingStrategy.buildVariancesMaps (numSeries); // return value lost
		}
//    	this.thresholdFinish=fittingStrategy.getStepDone();
    	this.iterationStepNumber=0;
    	// should be calculated after series weights are set
//    public int    []   imageStartIndex=null; // elements containing index of the start point of the selected image, first element 0, last - total number of points.
Andrey Filippov's avatar
Andrey Filippov committed
750
// TODO: add copying  lambdaStepUp,lambdaStepDown?
Andrey Filippov's avatar
Andrey Filippov committed
751 752
    	return false;
	}
Andrey Filippov's avatar
Andrey Filippov committed
753 754


Andrey Filippov's avatar
Andrey Filippov committed
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
	public void calculateChannelsWeights(
			int numSeries,
			double balanceChannelWeightsMode){
		if (balanceChannelWeightsMode==0) return; // keep current weights
		int numImg=fittingStrategy.distortionCalibrationData.getNumImages();
		int numStations=fittingStrategy.distortionCalibrationData.getNumStations();
		int numChannels=fittingStrategy.distortionCalibrationData.getNumChannels();

		if (balanceChannelWeightsMode<0) { //copy specified defaults to current values
			for (int station=0;station<numStations;station++){
				for (int chn=0;chn<numChannels;chn++){
					this.fittingStrategy.distortionCalibrationData.eyesisCameraParameters.eyesisSubCameras[station][chn].setChannelWeightCurrent(
							this.fittingStrategy.distortionCalibrationData.eyesisCameraParameters.eyesisSubCameras[0][chn].getChannelWeightDefault()); // from station 0
				}
			}
		} else {
			double exp=balanceChannelWeightsMode;
			double [][] sumChnWeights=new double [numStations][numChannels];
			double [] avgWeights=new double [numStations];
			int [] numNonzeroChannels=new int [numStations];
			for (int station=0;station<numStations;station++){
				avgWeights[station] =0.0;
				numNonzeroChannels[station] =0;
				for (int chn=0;chn<numChannels;chn++) sumChnWeights[station][chn] =0.0;
			}
			boolean [] selectedImages=fittingStrategy.selectedImages(numSeries); // -1 OK, will select all
			for (int imgNum=0;imgNum<numImg;imgNum++)if (selectedImages[imgNum]) {
					int chn=this.fittingStrategy.distortionCalibrationData.gIP[imgNum].channel; // number of sub-camera
					int station=this.fittingStrategy.distortionCalibrationData.gIP[imgNum].getStationNumber(); // number of sub-camera
					sumChnWeights[station][chn]+=this.fittingStrategy.distortionCalibrationData.gIP[imgNum].getNumContrastNodes(
							this.fittingStrategy.distortionCalibrationData.eyesisCameraParameters.minimalGridContrast);
			}
			for (int station=0;station<numStations;station++){
				for (int chn=0;chn<numChannels;chn++) if (sumChnWeights[station][chn]>0) {
					avgWeights[station]+=sumChnWeights[station][chn];
					numNonzeroChannels[station]++;
				}
				if (numNonzeroChannels[station]>0) avgWeights[station]/=numNonzeroChannels[station];
			}
			for (int station=0;station<numStations;station++){
				for (int chn=0;chn<numChannels;chn++) if (sumChnWeights[station][chn]>0) {
					double weight=(sumChnWeights[station][chn]>0.0)?Math.pow(avgWeights[station]/sumChnWeights[station][chn],exp):0.0;
					this.fittingStrategy.distortionCalibrationData.eyesisCameraParameters.eyesisSubCameras[station][chn].setChannelWeightCurrent(
							weight);
				}
			}
Andrey Filippov's avatar
Andrey Filippov committed
801

Andrey Filippov's avatar
Andrey Filippov committed
802
		}
Andrey Filippov's avatar
Andrey Filippov committed
803

Andrey Filippov's avatar
Andrey Filippov committed
804
	}
Andrey Filippov's avatar
Andrey Filippov committed
805

Andrey Filippov's avatar
Andrey Filippov committed
806 807 808 809 810 811 812 813 814 815 816 817 818 819 820
	public double setImageDiameter(int imgNum){
		int debugThreshold=2;
		int chnNum=this.fittingStrategy.distortionCalibrationData.gIP[imgNum].channel; // number of sub-camera
        double minimalGridContrast=this.fittingStrategy.distortionCalibrationData.eyesisCameraParameters.minimalGridContrast;
		int station=this.fittingStrategy.distortionCalibrationData.gIP[imgNum].getStationNumber(); // number of sub-camera
		EyesisSubCameraParameters esp=this.fittingStrategy.distortionCalibrationData.eyesisCameraParameters.eyesisSubCameras[station][chnNum];
        double r0pix=1000.0*esp.distortionRadius/esp.pixelSize;
        this.fittingStrategy.distortionCalibrationData.gIP[imgNum].setImageDiameter( // need to get image center px,py. Maybe r0 - use to normalize result diameter
    			esp.px0, // double xc,
    			esp.py0, // double yc,
    			r0pix,   // double r0,
    			minimalGridContrast,//  double minContrast
    			(this.debugLevel>debugThreshold)?imgNum:-1);
        return this.fittingStrategy.distortionCalibrationData.gIP[imgNum].getGridDiameter();
	}
Andrey Filippov's avatar
Andrey Filippov committed
821

822
	public void listImageSets(int mode){ // TODO: use series -1 - should work now
Andrey Filippov's avatar
Andrey Filippov committed
823 824 825 826 827
//		boolean [] oldSelection=this.fittingStrategy.selectAllImages(0); // enable all images in series 0
		if (this.fittingStrategy.distortionCalibrationData.gIS!=null){
			if (this.debugLevel>2){
				System.out.println("listImageSets() 1: ");
				for (int is=0;is<this.fittingStrategy.distortionCalibrationData.gIS.length;is++){
828 829 830 831 832
					System.out.println("listImageSets() 1: "+is+
							": tilt="+    this.fittingStrategy.distortionCalibrationData.gIS[is].goniometerTilt+
							" axial="+    this.fittingStrategy.distortionCalibrationData.gIS[is].goniometerAxial+
							" interAxis="+this.fittingStrategy.distortionCalibrationData.gIS[is].interAxisAngle+
							" estimated="+this.fittingStrategy.distortionCalibrationData.gIS[is].orientationEstimated);
Andrey Filippov's avatar
Andrey Filippov committed
833 834 835 836 837 838 839 840 841 842 843
				}
			}
		}

		int filter=this.filterForAll;
		if (this.askFilter) filter=selectFilter(filter);
		initFittingSeries(false,filter,-1); // first step in series
		if (this.fittingStrategy.distortionCalibrationData.gIS!=null){
			if (this.debugLevel>2){
				System.out.println("listImageSets() 2: ");
				for (int is=0;is<this.fittingStrategy.distortionCalibrationData.gIS.length;is++){
844 845 846 847 848
					System.out.println("listImageSets() 2: "+is+
							": tilt="+    this.fittingStrategy.distortionCalibrationData.gIS[is].goniometerTilt+
							" axial="+    this.fittingStrategy.distortionCalibrationData.gIS[is].goniometerAxial+
							" interAxis="+this.fittingStrategy.distortionCalibrationData.gIS[is].interAxisAngle+
							" estimated="+this.fittingStrategy.distortionCalibrationData.gIS[is].orientationEstimated);
Andrey Filippov's avatar
Andrey Filippov committed
849 850 851 852 853 854 855
				}
			}
		}
//	    initFittingSeries(true,this.filterForAll,0); // will set this.currentVector
		this.currentfX=calculateFxAndJacobian(this.currentVector, false); // is it always true here (this.jacobian==null)
		double [] errors=calcErrors(calcYminusFx(this.currentfX));
		int [] numPairs=calcNumPairs();
Andrey Filippov's avatar
Andrey Filippov committed
856

857 858 859
	    int [][] imageSets=this.fittingStrategy.distortionCalibrationData.listImages(
	    		false, // true - only enabled images
	    		null);    // do not filter eo, lwir
860 861 862 863
	    boolean hasLWIR = this.fittingStrategy.distortionCalibrationData.hasSmallSensors();

	    int [] numSetPoints=new int [imageSets.length*(hasLWIR?2:1)];
	    double [] rmsPerSet=new double[imageSets.length*(hasLWIR?2:1)];
864 865 866 867
	    int [][] numImgPoints=new int [imageSets.length][this.fittingStrategy.distortionCalibrationData.getNumSubCameras()];
	    double [][] rmsPerImg=new double[imageSets.length][this.fittingStrategy.distortionCalibrationData.getNumSubCameras()];


868 869 870 871 872 873 874
	    boolean [] hasNaNInSet=new boolean[imageSets.length*(hasLWIR?2:1)];
	    if (hasLWIR) {
	    	for (int setNum=0;setNum<imageSets.length;setNum++){
	    		double [] error2= {0.0,0.0};
	    		int [] numInSet= {0,0};
	    		hasNaNInSet[2*setNum]=false;
	    		hasNaNInSet[2*setNum+1]=false;
875 876 877 878
	    		for (int imgInSet=0;imgInSet<imageSets[setNum].length;imgInSet++) { // upper limit depends (now 4/20)
	    			int imgNum=imageSets[setNum][imgInSet]; // image number
	    			int chn =    fittingStrategy.distortionCalibrationData.gIP[imgNum].getChannel();
	    			int isLwir = fittingStrategy.distortionCalibrationData.isSmallSensor(imgNum)?1:0;
879
	    			int num=numPairs[imgNum];
880 881
	    			rmsPerImg[setNum][chn] = errors[imgNum];
	    			numImgPoints[setNum][chn] = num;
882 883 884 885 886 887
	    			if (Double.isNaN(errors[imgNum])){
	    				hasNaNInSet[2 * setNum + isLwir]=true;
	    			} else {
	    				error2[isLwir]+=errors[imgNum]*errors[imgNum]*num;
	    				numInSet[isLwir]+=num;
	    			}
Andrey Filippov's avatar
Andrey Filippov committed
888
	    		}
889 890 891 892 893 894 895 896 897 898 899 900 901
	    		numSetPoints[2 * setNum + 0]= numInSet[0];
	    		rmsPerSet   [2 * setNum + 0]= Math.sqrt(error2[0]/numInSet[0]);
	    		numSetPoints[2 * setNum + 1]= numInSet[1];
	    		rmsPerSet   [2 * setNum + 1]= Math.sqrt(error2[1]/numInSet[1]);
	    	}

	    } else {
	    	for (int setNum=0;setNum<imageSets.length;setNum++){
	    		double error2=0.0;
	    		int numInSet=0;
	    		hasNaNInSet[setNum]=false;
	    		for (int imgInSet=0;imgInSet<imageSets[setNum].length;imgInSet++) {
	    			int imgNum=imageSets[setNum][imgInSet];
902
	    			int chn =    fittingStrategy.distortionCalibrationData.gIP[imgNum].getChannel();
903
	    			int num=numPairs[imgNum];
904 905
	    			rmsPerImg[setNum][chn] = errors[imgNum];
	    			numImgPoints[setNum][chn] = num;
906 907 908 909 910 911 912 913 914
	    			if (Double.isNaN(errors[imgNum])){
	    				hasNaNInSet[setNum]=true;
	    			} else {
	    				error2+=errors[imgNum]*errors[imgNum]*num;
	    				numInSet+=num;
	    			}
	    		}
	    		numSetPoints[setNum]=numInSet;
	    		rmsPerSet[setNum]=Math.sqrt(error2/numInSet);
Andrey Filippov's avatar
Andrey Filippov committed
915 916
	    	}
	    }
917 918 919 920
	    this.fittingStrategy.distortionCalibrationData.listImageSet(
	    		mode,
	    		numSetPoints,
	    		rmsPerSet,
921 922 923 924
	    		hasNaNInSet,
    			numImgPoints,
    			rmsPerImg
	    		);
Andrey Filippov's avatar
Andrey Filippov committed
925 926
//		this.fittingStrategy.setImageSelection(0, oldSelection); // restore original selection in series 0
	}
Andrey Filippov's avatar
Andrey Filippov committed
927 928


Andrey Filippov's avatar
Andrey Filippov committed
929 930 931 932 933 934 935 936 937 938
	public void updateSensorMasks(){
		int alphaIndex=2;
		if (this.pixelCorrection==null){
			System.out.println("Sensor data is null, can not update sensor masks");
			return;
		}
		if (this.debugLevel>0) System.out.println("Updating sensor masks in sensor data");
		for (int i=0;(i<this.fittingStrategy.distortionCalibrationData.sensorMasks.length) && (i<this.pixelCorrection.length);i++){
			this.pixelCorrection[i][alphaIndex]=this.fittingStrategy.distortionCalibrationData.sensorMasks[i].clone();
		}
Andrey Filippov's avatar
Andrey Filippov committed
939

Andrey Filippov's avatar
Andrey Filippov committed
940 941 942 943 944 945
	}

	public boolean correctPatternFlatField(boolean enableShow){
		if (this.debugLevel>0) System.out.println("=== Performing pattern flat field correction");
		this.patternParameters.updateNumStations(this.fittingStrategy.distortionCalibrationData.eyesisCameraParameters.getNumStations());
		double [][] masks= nonVignettedMasks(
946 947
				this.refineParameters);

948 949 950 951 952 953
		boolean same_size = true;
		for (int nChn=1; nChn < masks.length; nChn++) same_size &= (masks[nChn].length == masks[0].length);


		if (enableShow && this.refineParameters.flatFieldShowSensorMasks) {
			if (same_size) {
954
			ShowDoubleFloatArrays.showArrays( //java.lang.ArrayIndexOutOfBoundsException: 313632
Andrey Filippov's avatar
Andrey Filippov committed
955
				masks,
956 957
				getSensorWidth(0)/ getDecimateMasks(0),
				getSensorHeight(0)/getDecimateMasks(0),
Andrey Filippov's avatar
Andrey Filippov committed
958 959
				true,
		"nonVinetting masks");
960
			} else {
961
				System.out.println ("Can not display different size masks in a stack");
962 963 964 965
			}
		}


Andrey Filippov's avatar
Andrey Filippov committed
966 967 968
		double [][][][] sensorGrids=calculateGridFlatField(
				this.refineParameters.flatFieldSerNumber,
				masks,
969 970 971 972 973 974 975 976
				this.refineParameters);
//				this.refineParameters.flatFieldMinimalContrast,
//				this.refineParameters.flatFieldMinimalAccumulate,
//				this.refineParameters.flatFieldUseInterpolate,
//				this.refineParameters.flatFieldMaskThresholdOcclusion, // suspect occlusion only if grid is missing in the area where sensor mask is above this threshold
//				this.refineParameters.flatFieldShrinkOcclusion,
//				this.refineParameters.flatFieldFadeOcclusion,
//				this.refineParameters.flatFieldIgnoreSensorFlatField);
Andrey Filippov's avatar
Andrey Filippov committed
977 978 979 980
		double [][][] geometry= patternParameters.getGeometry();
		if (enableShow && this.refineParameters.flatFieldShowIndividual){
			for (int station=0;station<sensorGrids.length;station++) if (sensorGrids[station]!=null){
				for (int i=0;i<sensorGrids[station].length;i++) if (sensorGrids[station][i]!=null){
981
					ShowDoubleFloatArrays.showArrays(
Andrey Filippov's avatar
Andrey Filippov committed
982 983 984 985 986 987 988 989
							sensorGrids[station][i],
							geometry[0].length,
							geometry.length,
							true,
							"chn"+i+":"+station+"-pattern");
				}
			}
		}
990 991


Andrey Filippov's avatar
Andrey Filippov committed
992
		double [][][][] patternArray= combineGridFlatField(
993
//				this.refineParameters,
Andrey Filippov's avatar
Andrey Filippov committed
994 995 996 997 998 999 1000 1001 1002 1003 1004
				this.refineParameters.flatFieldReferenceStation,
				sensorGrids,
				this.refineParameters.flatFieldShrinkForMatching,
				this.refineParameters.flatFieldResetMask,
				this.refineParameters.flatFieldMaxRelDiff,
				this.refineParameters.flatFieldShrinkMask,
				this.refineParameters.flatFieldFadeBorder);
		if (enableShow && this.refineParameters.flatFieldShowResult) {
			String [] titles={"Alpha","Red","Green","Blue","Number of images used"};
			for (int station=0;station<patternArray.length;station++) if (patternArray[station]!=null){
				for (int nView=0;nView<patternArray[station].length;nView++) if (patternArray[station][nView]!=null){
1005
					ShowDoubleFloatArrays.showArrays(
Andrey Filippov's avatar
Andrey Filippov committed
1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017
							patternArray[station][nView],
							geometry[0].length,
							geometry.length,
							true,
							"St"+station+"_V"+nView+"_Pattern_Colors "+this.refineParameters.flatFieldMaxRelDiff,
							titles);
				}
			}
		}
		if (this.refineParameters.flatFieldApplyResult) applyGridFlatField(patternArray); // {alpha, red,green,blue, number of images used}[pixel_index]
		return true;
	}
Andrey Filippov's avatar
Andrey Filippov committed
1018

Andrey Filippov's avatar
Andrey Filippov committed
1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039
	public boolean modifyPixelCorrection(
			boolean   enableShow,
			int       threadsMax,
			boolean   updateStatus,
			int debugLevel
	){
		int filter=this.filterForSensor;
		if (this.askFilter) filter=selectFilter(filter);
    	initFittingSeries(true,filter,this.seriesNumber); // first step in series now uses pattern alpha
//    	initFittingSeries(true,this.filterForSensor,this.seriesNumber); // first step in series now uses pattern alpha
    	this.currentfX=calculateFxAndJacobian(this.currentVector, false);
    	//        	this.currentRMS= calcError(calcYminusFx(this.currentfX));
    	if (this.debugLevel>2) {
    		System.out.println("this.currentVector");
    		for (int i=0;i<this.currentVector.length;i++){
    			System.out.println(i+": "+ this.currentVector[i]);
    		}
    	}
		boolean [] selectedImages=fittingStrategy.selectedImages();
		double [][][] sensorXYRGBCorr=  allImagesCorrectionMapped(
				selectedImages,
1040 1041
				enableShow, //  && this.refineParameters.showPerImage,
				this.refineParameters, // .showIndividualNumber,
Andrey Filippov's avatar
Andrey Filippov committed
1042 1043 1044
				threadsMax,
				updateStatus,
				debugLevel);
1045 1046
		String [] titles={"X-corr(pix)","Y-corr(pix)","weight","Red","Green","Blue"};
		for (int numChn=0;numChn<sensorXYRGBCorr.length;numChn++) if (sensorXYRGBCorr[numChn]!=null){
1047 1048
//			boolean small_sensor = fittingStrategy.distortionCalibrationData.isSmallSensor(numChn);
			boolean small_sensor = fittingStrategy.distortionCalibrationData.getSmallSensors()[numChn];
1049
			RefineParameters rp = small_sensor ? refineParameters.refineParametersSmall : refineParameters;
1050
			int decimate=getDecimateMasks(numChn); // Reduce for LWIR? Make form sensor width?
1051 1052
			int sWidth= (getSensorWidth(numChn)-1)/decimate+1;
			if (rp.showUnfilteredCorrection &&  enableShow) { //  && this.refineParameters.showUnfilteredCorrection) {
Andrey Filippov's avatar
Andrey Filippov committed
1053 1054
				showWithRadialTangential(
						titles,
1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081
						"chn_"+numChn+"_visible_correction",
						sensorXYRGBCorr[numChn], // [0] - dx, [1] - dy
						sWidth,
						decimate,
						fittingStrategy.distortionCalibrationData.eyesisCameraParameters.eyesisSubCameras[0][numChn].px0, // using station 0
						fittingStrategy.distortionCalibrationData.eyesisCameraParameters.eyesisSubCameras[0][numChn].py0);
			}
			smoothSensorPolar(
					titles,
					"chn_"+numChn+"_polar_correction",
					sensorXYRGBCorr[numChn], // [0] - dx, [1] - dy
					sWidth,
					decimate,
					fittingStrategy.distortionCalibrationData.eyesisCameraParameters.eyesisSubCameras[0][numChn].px0, // using station 0
					fittingStrategy.distortionCalibrationData.eyesisCameraParameters.eyesisSubCameras[0][numChn].py0,
					rp.center_fract,       // 0.5, // double center_fract, // 0.5 of half-height
					rp.transit_fract,      // 0.2, // double transit_fract, // 0.2 of half-height - transition from center ortho to outer polar
					rp.gaus_ang,           // 0.2, // 1, // 0.2, // double gaus_ang,  // in radians
					rp.gaus_rad,           // 0.05, // 0.1, // double gaus_rad   // in fractions of the full radius
					rp.max_diff_err_geom,  // 0.25, // double max_diff_err_geom,   // before second pass linearly fade R/T and RGB where high-frequency error nears thios value
					rp.max_diff_err_photo, // 0.25, // double max_diff_err_photo
					rp.showExtrapolationCorrection &&  enableShow); // boolean showDebugImages);

			if (rp.showThisCorrection &&  enableShow) { //  && this.refineParameters.showUnfilteredCorrection) {
				showWithRadialTangential(
						titles,
						"after-chn_"+numChn+"_after_polar",
Andrey Filippov's avatar
Andrey Filippov committed
1082 1083 1084 1085 1086 1087 1088
						sensorXYRGBCorr[numChn], // [0] - dx, [1] - dy
						sWidth,
						decimate,
						fittingStrategy.distortionCalibrationData.eyesisCameraParameters.eyesisSubCameras[0][numChn].px0, // using station 0
						fittingStrategy.distortionCalibrationData.eyesisCameraParameters.eyesisSubCameras[0][numChn].py0);
			}
		}
1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119
		//eyesisSubCameras
		//extrapolate
		// TODO: different extrapolation for FF - not circular where shades are in effect (top/bottom)
		//    	if (!this.refineParameters.sensorExtrapolateDiff) { // add current correction BEFORE extrapolating/blurring
		addOldXYCorrectionToCurrent(
				//    				true, // if (!this.refineParameters.sensorExtrapolateDiff)
				this.refineParameters, // .correctionScale,
				sensorXYRGBCorr
				);
		/*
		allSensorsExtrapolationMapped(
				0, //final int stationNumber, // has to be selected
				sensorXYRGBCorr, //final double [][][] gridPCorr,
				this.refineParameters,
				threadsMax,
				updateStatus,
				enableShow && this.refineParameters.showExtrapolationCorrection, //final boolean showDebugImages,
				debugLevel
				);
		 */
 //   	if (this.refineParameters.smoothCorrection) {
		/*
    	boolean [] whichBlur={true,true,false,true,true,true}; // all but weight
    	IJ.showStatus("Bluring sensor corrections...");
    	for (int numChn=0;numChn<sensorXYRGBCorr.length;numChn++) if (sensorXYRGBCorr[numChn]!=null){
    		boolean small_sensor = fittingStrategy.distortionCalibrationData.isSmallSensor(numChn);
    		RefineParameters rp = small_sensor ? refineParameters.refineParametersSmall : refineParameters;
    		if (rp.smoothCorrection) {
    			int decimate=getDecimateMasks(numChn);
    			int sWidth= (getSensorWidth(numChn)-1)/decimate+1;
    			int sHeight=(getSensorHeight(numChn)-1)/decimate+1;
Andrey Filippov's avatar
Andrey Filippov committed
1120 1121 1122 1123 1124 1125
    			DoubleGaussianBlur gb=new DoubleGaussianBlur();
    			for (int m=0;m<whichBlur.length;m++) if (whichBlur[m]){
    				gb.blurDouble(
    						sensorXYRGBCorr[numChn][m],
    						sWidth,
    						sHeight,
1126 1127
    						rp.smoothSigma/decimate,
    						rp.smoothSigma/decimate,
Andrey Filippov's avatar
Andrey Filippov committed
1128 1129 1130 1131 1132
    						0.01);
    			}
    			IJ.showProgress(numChn+1, sensorXYRGBCorr.length);
    		}
    	}
1133 1134 1135 1136 1137 1138
    	IJ.showProgress(1.0);
 //   	}
		 */
//    	if (enableShow && this.refineParameters.showThisCorrection ) {
		/*
    	if (enableShow) {
Andrey Filippov's avatar
Andrey Filippov committed
1139
    		for (int numChn=0;numChn<sensorXYRGBCorr.length;numChn++) if (sensorXYRGBCorr[numChn]!=null){
1140 1141 1142 1143 1144
    			boolean small_sensor = fittingStrategy.distortionCalibrationData.isSmallSensor(numChn);
    			RefineParameters rp = small_sensor ? refineParameters.refineParametersSmall : refineParameters;
    			if (rp.showThisCorrection) {
    				int decimate=getDecimateMasks(numChn);
    				int sWidth= (getSensorWidth(numChn)-1)/decimate+1;
1145
    				//    		   ShowDoubleFloatArrays.showArrays(sensorXYRGBCorr[numChn], sWidth, sHeight,  true, "chn_"+numChn+"_filtered", titles);
1146 1147 1148 1149 1150 1151 1152 1153 1154
    				showWithRadialTangential(
    						titles,
    						"chn_"+numChn+"_filtered",
    						sensorXYRGBCorr[numChn], // [0] - dx, [1] - dy
    						sWidth,
    						decimate,
    						fittingStrategy.distortionCalibrationData.eyesisCameraParameters.eyesisSubCameras[0][numChn].px0, // using station 0
    						fittingStrategy.distortionCalibrationData.eyesisCameraParameters.eyesisSubCameras[0][numChn].py0);
    			}
Andrey Filippov's avatar
Andrey Filippov committed
1155 1156
    		}
    	}
1157 1158 1159
    	*/
		/*
//    	if (this.refineParameters.sensorExtrapolateDiff) { // add current correction AFTER extrapolationg/bluring
Andrey Filippov's avatar
Andrey Filippov committed
1160
    		addOldXYCorrectionToCurrent(
1161 1162
    				false, // if (this.refineParameters.sensorExtrapolateDiff) { // add current correction AFTER extrapolationg/bluring
    				this.refineParameters, // .correctionScale,
Andrey Filippov's avatar
Andrey Filippov committed
1163
    				sensorXYRGBCorr
Andrey Filippov's avatar
Andrey Filippov committed
1164
    		);
1165 1166
//    	}
	    */
Andrey Filippov's avatar
Andrey Filippov committed
1167
//   	if (!selectCorrectionScale()) return false;
1168

Andrey Filippov's avatar
Andrey Filippov committed
1169 1170 1171
		IJ.showStatus("Applying corrections:"+((!this.refineParameters.applyCorrection && !this.refineParameters.applyFlatField)?
				"none ":((this.refineParameters.applyCorrection?"geometry ":"")+(this.refineParameters.applyFlatField?"flat field":""))));
    	boolean result=applySensorCorrection(
1172
    			this.refineParameters,
Andrey Filippov's avatar
Andrey Filippov committed
1173
    			sensorXYRGBCorr, //sensorXYCorr, // modified to accept both 7(old) and 6(new) entries
Andrey Filippov's avatar
Andrey Filippov committed
1174 1175 1176
    			fittingStrategy.distortionCalibrationData);
    	if (enableShow && this.refineParameters.showCumulativeCorrection) {
    		for (int numChn=0;numChn<sensorXYRGBCorr.length;numChn++) if (sensorXYRGBCorr[numChn]!=null){
1177 1178
				int decimate=getDecimateMasks(numChn);
				int sWidth= (getSensorWidth(numChn)-1)/decimate+1;
1179
//    		   ShowDoubleFloatArrays.showArrays(sensorXYRGBCorr[numChn], sWidth, sHeight,  true, "Cumulative_chn_"+numChn+"_corrections", titles);
Andrey Filippov's avatar
Andrey Filippov committed
1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196
				showWithRadialTangential(
						titles,
						"Cumulative_chn_"+numChn+"_corrections",
						sensorXYRGBCorr[numChn], // [0] - dx, [1] - dy
						sWidth,
						decimate,
						fittingStrategy.distortionCalibrationData.eyesisCameraParameters.eyesisSubCameras[0][numChn].px0, // using station 0
						fittingStrategy.distortionCalibrationData.eyesisCameraParameters.eyesisSubCameras[0][numChn].py0);
    		}
    	}
    	if (result) {
			updateCameraParametersFromCalculated(false); // update camera parameters from enabled only images (may overwrite some of the above)

    	}
		IJ.showStatus("");
    	return result;
    }
Andrey Filippov's avatar
Andrey Filippov committed
1197

Andrey Filippov's avatar
Andrey Filippov committed
1198 1199 1200 1201 1202
	public void showWithRadialTangential(
			String [] preTitles,
			String title,
			double [][] preData, // [0] - dx, [1] - dy
			int width,
1203
			int decimate,
Andrey Filippov's avatar
Andrey Filippov committed
1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226
			double x0,
			double y0){
		int indexDx=0;
		int indexDy=1;
		int indexDr=0;
		int indexDt=1;
		int indexDa=2;
		String [] extraTitles={"R-corr(pix)","T-corr{pix)","A-corr(pix)"};
		int newImages=extraTitles.length;
		int length=preData[0].length;
		int height=length/width;
		double [][] data= new double [preData.length+newImages] [length];
		String [] titles= new String [preTitles.length+newImages];
		for (int i=0;i<preData.length;i++){
			data[i+newImages]=preData[i];
			titles[i+newImages]=preTitles[i];
		}
		for (int i=0;i<newImages;i++){
			titles[i]=extraTitles[i];
			data[i]=new double[length];
		}
		Point2D Z=new Point2D.Double(0.0,0.0);
		for (int i=0;i<length;i++){
1227
			Point2D R=new Point2D.Double((decimate*(i%width))-x0,(decimate*(i/width))-y0);
Andrey Filippov's avatar
Andrey Filippov committed
1228 1229 1230 1231 1232 1233 1234 1235
			double r=R.distance(Z);
			Point2D uR=new Point2D.Double(1.0,0.0);
			if (r>0) uR.setLocation(R.getX()/r,R.getY()/r);
			Point2D dXY=new Point2D.Double(preData[indexDx][i],preData[indexDy][i]);
			data[indexDr][i]= dXY.getX()*uR.getX()+dXY.getY()*uR.getY();
			data[indexDt][i]=-dXY.getX()*uR.getY()+dXY.getY()*uR.getX();
			data[indexDa][i]=dXY.distance(Z);
		}
1236
	   ShowDoubleFloatArrays.showArrays(data, width, height,  true, title, titles);
Andrey Filippov's avatar
Andrey Filippov committed
1237
	}
Andrey Filippov's avatar
Andrey Filippov committed
1238

Andrey Filippov's avatar
Andrey Filippov committed
1239

1240 1241 1242



1243
	public static double [][] DXYtoDRT(
1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 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 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 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 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544
			double [][] dataXY, // [0] - dx, [1] - dy
			int width,
			int decimate,
			double x0,
			double y0){
		int length=dataXY[0].length;
//		int height=length/width;
		double [][] dataRT = new double[2][length];
		Point2D Z=new Point2D.Double(0.0,0.0);
		for (int i=0;i<length;i++){
			Point2D R=new Point2D.Double((decimate*(i%width))-x0,(decimate*(i/width))-y0);
			double r=R.distance(Z);
			Point2D uR=new Point2D.Double(1.0,0.0);
			if (r>0) uR.setLocation(R.getX()/r,R.getY()/r);
			Point2D dXY=new Point2D.Double(dataXY[0][i],dataXY[1][i]);
			dataRT[0][i]= dXY.getX()*uR.getX()+dXY.getY()*uR.getY();
			dataRT[1][i]=-dXY.getX()*uR.getY()+dXY.getY()*uR.getX();
		}
		return dataRT;
	}

	public double [][] DRTtoDXY(
			double [][] dataRT, // [0] - dx, [1] - dy
			int width,
			int decimate,
			double x0,
			double y0){

		int length=dataRT[0].length;
//		int height=length/width;
		double [][] dataXY = new double[2][length];
		Point2D Z=new Point2D.Double(0.0,0.0);
		for (int i=0;i<length;i++){
			Point2D R=new Point2D.Double((decimate*(i%width))-x0,(decimate*(i/width))-y0);
			double r=R.distance(Z);
			Point2D uR=new Point2D.Double(1.0,0.0);
			if (r>0) uR.setLocation(R.getX()/r,R.getY()/r); // cos, sin
			Point2D dRT=new Point2D.Double(dataRT[0][i],dataRT[1][i]);
			dataXY[0][i]= dRT.getX()*uR.getX()-dRT.getY()*uR.getY();
			dataXY[1][i]= dRT.getX()*uR.getY()+dRT.getY()*uR.getX();
		}
		return dataXY;
	}




	public double [][] correctionToRadial(
			double [][] preData, // variable number of layers, [0] - weight dRT or RGB
			int width,
			int decimate,
			double x0,
			double y0,
			int inner_rad_d, // margins (minimal from all sides)
			int lines_overlap, // add linesto the bottom (corresponding to the angle)
			int indexWeight) {
		int length=preData[0].length;
		int height=length/width;
		int [] ints = radialInts(
				length,
				width,
				decimate,
				x0,
				y0,
				inner_rad_d); // margins (minimal from all sides)
//		int inner_rad_d =    ints[0];
		int polar_height0 = ints[0];
		int polar_width =   ints[1];

		int polar_height =  polar_height0 + lines_overlap;


		double [][] polar = new double[preData.length][polar_width * polar_height];
		for (int i = 0; i < polar.length; i++) if (i != indexWeight){
 			for (int j = 0; j < polar[i].length; j++) {
 				polar[i][j] = Double.NaN;
 			}
 		}
 		double k = 2* Math.PI / polar_height0;
 		for (int iangle = 0; iangle < polar_height; iangle++) {
 			double angle = k * iangle;
 			double s = Math.sin(angle);
 			double c = Math.cos(angle);
 			for (int ir = 0; ir < polar_width; ir++) {
 				double r = decimate*(ir + inner_rad_d);
 				// calculate x,y - no interpolation here
 				int ix = (int) Math.round((x0 + r * c)/decimate);
 				int iy = (int) Math.round((y0 + r * s)/decimate);
 				if ((ix >= 0) && (iy >= 0) && (ix < width) && (iy < height)) {
 					int indx = ix+ iy* width;
 					int indx_polar = ir + iangle* polar_width;
 					for (int l = 0; l < polar.length; l++) {
 						polar[l][indx_polar] = preData[l][indx];
 					}
 				}
 			}
 		}
 		return polar;
	}

	public void correctionToOrtho(
			double [][] data_ortho, // variable number of layers, will be modifier from the overlapping radial)
			double [][] data_polar, // same layers as ortho, will be used as a source
			int width,
			int decimate,
			double x0,
			double y0,
			int inner_rad_d, // margins (minimal from all sides)
			int lines_overlap, // add lines to the bottom (corresponding to the angle)
			int transit_rad) {
		int length=data_ortho[0].length;
		int height=length/width;

		int [] ints = radialInts(
				length,
				width,
				decimate,
				x0,
				y0,
				inner_rad_d); // margins (minimal from all sides)

		double [] transition = new double[transit_rad];
		for (int i = 0; i < transit_rad; i++) {
			transition[i] = 0.5*(1.0-Math.cos(Math.PI * (i +0.5)/transit_rad));
		}
		int polar_height0 = ints[0];
		int polar_width =   ints[1];
// 		double k = 2 * Math.PI / polar_height0;
 		int iangle0 = lines_overlap / 2; // polar was created with overlap (pver2PI) for angular blurring, use middle portion

 		for (int iy = 0; iy < height; iy++) {
 			double rs = iy * decimate - y0;
 			for (int ix = 0; ix < width; ix++) {
 				int indx = ix+ iy* width;
 	 			double rc = ix * decimate - x0;
 	 			double r = Math.sqrt(rc*rc + rs*rs);
 	 			double angle = Math.atan2(rs, rc);
 				if (angle < 0.0) angle += 2* Math.PI;
 				int iangle = (int) Math.round(polar_height0 * angle/ (2 * Math.PI));
 				if (iangle < iangle0) {
 					iangle += polar_height0;
 				}
 				int ir = (int) Math.round(r/decimate - inner_rad_d);
 				if ((ir >=0) && (ir < polar_width)) {
 					int indx_polar = ir + iangle* polar_width;
 					if (ir >= transit_rad){
 						for (int l = 0; l < data_ortho.length; l++) {
 							data_ortho[l][indx] = data_polar[l][indx_polar];
 						}
 					} else {
 						for (int l = 0; l < data_ortho.length; l++) {
 							data_ortho[l][indx] = transition[ir]*data_polar[l][indx_polar] + (1.0-transition[ir])*data_ortho[l][indx];
 						}
 					}
 				}
 			}
 		}
	}


	public void correctionToOrtho0XXX(
			double [][] data_ortho, // variable number of layers, will be modifier from the overlapping radial)
			double [][] data_polar, // same layers as ortho, will be used as a source
			int width,
			int decimate,
			double x0,
			double y0,
			int inner_rad_d, // margins (minimal from all sides)
			int lines_overlap){ // add lines to the bottom (corresponding to the angle)
		int length=data_ortho[0].length;
		int height=length/width;

		int [] ints = radialInts(
				length,
				width,
				decimate,
				x0,
				y0,
				inner_rad_d); // margins (minimal from all sides)

		int polar_height0 = ints[0];
		int polar_width =   ints[1];
 		double k = 2 * Math.PI / polar_height0;
 		int iangle0 = lines_overlap / 2; // polar was created with overlap (pver2PI) for angular blurring, use middle portion

 		for (int iangle = iangle0; iangle < (iangle0 + polar_height0); iangle++) {
 			double angle = k * iangle;
 			double s = Math.sin(angle);
 			double c = Math.cos(angle);
 			for (int ir = 0; ir < polar_width; ir++) {
 				double r = decimate*(ir + inner_rad_d);
 				// calculate x,y - no interpolation here
 				int ix = (int) Math.round((x0 + r * c)/decimate);
 				int iy = (int) Math.round((y0 + r * s)/decimate);
 				if ((ix >= 0) && (iy >= 0) && (ix < width) && (iy < height)) {
 					int indx = ix+ iy* width;
 					int indx_polar = ir + iangle* polar_width;
 					for (int l = 0; l < data_ortho.length; l++) {
 						data_ortho[l][indx] = data_polar[l][indx_polar];
 					}
 				}
 			}
 		}
	}

	public int [] radialInts( // helper to correctionToRadial() and correctionToOrtho()
			int length,
			int width,
			int decimate,
			double x0,
			double y0,
			int inner_rad_d) { // margins (minimal from all sides)
		int height=length/width;

		//find longest distance from the center to the corners
		Point2D C=new Point2D.Double(x0, y0);
		Point2D [] corners = {
				new Point2D.Double(-decimate,     -decimate),
				new Point2D.Double(decimate*(width+1),-decimate),
				new Point2D.Double(decimate*(width+1), decimate*(height+1)),
				new Point2D.Double(-decimate,      decimate*(height+1)),
		};
		double radius = 0.0;
		for (Point2D p :corners) {
			radius = Math.max(radius, C.distance(p));
		}
//		double x0d = x0/decimate;
//		double y0d = y0/decimate;
//		double min_rad_d_h = Math.min(x0d, width- 1-x0d);
//		double min_rad_d_v = Math.min(y0d, height-1-y0d);

		int imax_rad_d = (int) Math.ceil(radius/decimate);

//		int inner_rad_d = (int) Math.floor(Math.min(min_rad_d_h,min_rad_d_v)) -1 - margins;
		int polar_height0 = (int) Math.ceil(2*Math.PI*radius/decimate);
		int polar_width =  imax_rad_d - inner_rad_d + 1;
		int [] rslt = {polar_height0, polar_width};
		return rslt;
	}

	public void smoothSensorPolar(
			String [] preTitles,
			String title,
			double [][] preData, // [0] - dx, [1] - dy
			int width,
			int decimate,
			double x0,
			double y0,
			double center_fract, // 0.5 of half-height
			double transit_fract, // 0.2 of half-height - transition from center ortho to outer polar
			double gaus_ang_rel,  // in radians 0.2
			double gaus_rad_rel,  // in fractions of the full radius 0.1
			double max_diff_err_geom,   // before second pass linearly fade R/T and RGB where high-frequency error nears thios value
			double max_diff_err_photo,
			boolean showDebugImages
			) {
		int indexDx=    0;
		int indexDy=    1;
		int indexWeight=2;
		int indexR=     3;
		int indexG=     4;
		int indexB=     5;
		int length=preData[0].length;
		int height=length/width;
		double sensor_radius_d = Math.sqrt(width*width+height*height)/2;
		double gaus_ang =   gaus_ang_rel * sensor_radius_d;
		double gaus_rad =   gaus_rad_rel *  sensor_radius_d;
		int lines_overlap = (int) Math.round(4 * gaus_ang);
		int inner_rad_d = (int) Math.round(height/2 * center_fract);
		int transit_rad = (int) Math.round(height/2 * transit_fract);

		int [] ints = radialInts(
				length,
				width,
				decimate,
				x0,
				y0,
				inner_rad_d); // margins (minimal from all sides)
		int polar_height0 = ints[0];
		int polar_width =   ints[1];
		int polar_height =  polar_height0 + lines_overlap;
		int polar_length = polar_width * polar_height;

// convert dXY to dRT
		double [][] data_xy = {preData[indexDx].clone(), preData[indexDy].clone()}; // clone to later blur (actually src is not needed)
 		double [][] data_rt = DXYtoDRT(
				data_xy, // [0] - dx, [1] - dy
				width,
				decimate,
				x0,
				y0);
		double [][] data_ortho= {
				preData[indexWeight],
				data_rt[0],
				data_rt[1],
				preData[indexR],
				preData[indexG],
				preData[indexB]};

		String [] dbg_titles= {"Weight","dR", "dT","Red", "Green", "Blue"};
		if (showDebugImages) {
1545
			ShowDoubleFloatArrays.showArrays(data_ortho, width, height,  true, "ortho-"+title, dbg_titles);
1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557
		}
		double [][] data_polar = correctionToRadial(
				data_ortho, // variable number of layers, [0] - weight dRT or RGB
				width,
				decimate,
				x0,
				y0,
				inner_rad_d,    // distorted inner radis
				lines_overlap, // add lines to the bottom (corresponding to the angle)
				0); // indexWeight);

		if (showDebugImages) {
1558
			ShowDoubleFloatArrays.showArrays(data_polar, polar_width, polar_height,  true, "polar-"+title, dbg_titles);
1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581
		}
		double [][] data_polar_blur = new double[data_polar.length][];
		data_polar_blur[0] = data_polar[0].clone();
		for (int i = 1; i < data_polar_blur.length; i++) {
			data_polar_blur[i] = data_polar[i].clone();
			for (int j = 0; j < polar_length; j++ ) {
				data_polar_blur[i][j]*=data_polar[0][j]; // weight (was *= data_polar_blur[0][j] restore?
				if (Double.isNaN(data_polar_blur[i][j])) data_polar_blur[i][j]= 0.0;
			}
			(new DoubleGaussianBlur() ).blurDouble(data_polar_blur[i], polar_width, polar_height, gaus_rad, gaus_ang, 0.01);
		}
		(new DoubleGaussianBlur() ).blurDouble(data_polar_blur[0], polar_width, polar_height, gaus_rad, gaus_ang, 0.01);
		for (int i = 1; i < data_polar_blur.length; i++) {
			for (int j = 0; j < polar_length; j++ ) {
				if (data_polar_blur[0][j] == 0.0) {
					data_polar_blur[i][j] = Double.NaN;
				} else {
					data_polar_blur[i][j] /= data_polar_blur[0][j]; // weight
				}
			}

		}
		if (showDebugImages) {
1582
			ShowDoubleFloatArrays.showArrays(data_polar_blur, polar_width, polar_height,  true, "polar-bl-"+title, dbg_titles);
1583 1584 1585 1586 1587 1588 1589 1590
		}
		double [][] data_polar_diff = new double[data_polar.length][data_polar[0].length];
		for (int i = 0; i < data_polar_diff.length; i++) {
			for (int j = 0; j < polar_length; j++ ) {
				data_polar_diff[i][j] = data_polar[i][j] - data_polar_blur[i][j];
			}
		}
		if (showDebugImages) {
1591
			ShowDoubleFloatArrays.showArrays(data_polar_diff, polar_width, polar_height,  true, "polar-diff-"+title, dbg_titles);
1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626
		}

		double [][] errors_gr = new double[5][data_polar[0].length];
		for (int j = 0; j < polar_length; j++) {
			for (int i = 1; i < 3; i++) {
				errors_gr[0][j] += data_polar_diff[i][j]*data_polar_diff[i][j];
			}
			errors_gr[0][j] = Math.sqrt(errors_gr[0][j]);

			for (int i = 3; i < 6; i++) {
				errors_gr[1][j] += data_polar_diff[i][j]*data_polar_diff[i][j];
			}
			errors_gr[1][j] = Math.sqrt(errors_gr[1][j]);
		}
		errors_gr[2] = data_polar[0].clone(); // weight

		// reduce weight where high frequency difference was high, re-run blur
		double [] weight_geom =  data_polar[0].clone();
		double [] weight_photo = data_polar[0].clone();
		for (int i = 0; i <polar_length; i++) {
			if (Double.isNaN(errors_gr[0][i]) || (errors_gr[0][i] > max_diff_err_geom)) {
				weight_geom[i] = 0.0;
			} else {
				weight_geom[i] *= (max_diff_err_geom - errors_gr[0][i]) / max_diff_err_geom;
			}
			if (Double.isNaN(errors_gr[1][i]) || (errors_gr[1][i] > max_diff_err_photo)) {
				weight_photo[i] = 0.0;
			} else {
				weight_photo[i] *= (max_diff_err_photo - errors_gr[1][i])/max_diff_err_photo;
			}
		}
		errors_gr[3] = weight_geom.clone(); // weight
		errors_gr[4] = weight_photo.clone(); // weight
		if (showDebugImages) {
			String [] titles_err = {"geom","photo","weight", "weight_geom","weight_photo"};
1627
			ShowDoubleFloatArrays.showArrays(errors_gr, polar_width, polar_height,  true, "polar-err-"+title, titles_err);
1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670
		}

		// geometry
		for (int i = 1; i < 3; i++) { // geom
			data_polar_blur[i] = data_polar[i].clone();
			for (int j = 0; j < polar_length; j++ ) {
				data_polar_blur[i][j] *= weight_geom[j]; // weight
				if (Double.isNaN(data_polar_blur[i][j])) data_polar_blur[i][j]= 0.0;
			}
			(new DoubleGaussianBlur() ).blurDouble(data_polar_blur[i], polar_width, polar_height, gaus_rad, gaus_ang, 0.01);
		}
		(new DoubleGaussianBlur() ).blurDouble(weight_geom, polar_width, polar_height, gaus_rad, gaus_ang, 0.01);
		for (int i = 1; i < 3; i++) { // geom
			for (int j = 0; j < polar_length; j++ ) {
				if (weight_geom[j] == 0.0) {
					data_polar_blur[i][j] = Double.NaN;
				} else {
					data_polar_blur[i][j] /= weight_geom[j]; // weight
				}
			}
		}

		// photo
		for (int i = 3; i < 6; i++) { // photo
			data_polar_blur[i] = data_polar[i].clone();
			for (int j = 0; j < polar_length; j++ ) {
				data_polar_blur[i][j] *= weight_photo[j]; // weight
				if (Double.isNaN(data_polar_blur[i][j])) data_polar_blur[i][j]= 0.0;
			}
			(new DoubleGaussianBlur() ).blurDouble(data_polar_blur[i], polar_width, polar_height, gaus_rad, gaus_ang, 0.01);
		}
		(new DoubleGaussianBlur() ).blurDouble(weight_photo, polar_width, polar_height, gaus_rad, gaus_ang, 0.01);
		for (int i = 3; i < 6; i++) { // photo
			for (int j = 0; j < polar_length; j++ ) {
				if (weight_photo[j] == 0.0) {
					data_polar_blur[i][j] = Double.NaN;
				} else {
					data_polar_blur[i][j] /= weight_photo[j]; // weight
				}
			}
		}
		data_polar_blur[0] = weight_geom.clone();
		if (showDebugImages) {
1671
			ShowDoubleFloatArrays.showArrays(data_polar_blur, polar_width, polar_height,  true, "polar-bl2-"+title, dbg_titles);
1672 1673 1674 1675 1676 1677 1678 1679
		}
		data_polar_diff = new double[data_polar.length][polar_length];
		for (int i = 0; i < data_polar_diff.length; i++) {
			for (int j = 0; j < polar_length; j++ ) {
				data_polar_diff[i][j] = data_polar[i][j] - data_polar_blur[i][j];
			}
		}
		if (showDebugImages) {
1680 1681
			ShowDoubleFloatArrays.showArrays(data_polar_diff, polar_width, polar_height,  true, "polar-diff2-"+title, dbg_titles);
			ShowDoubleFloatArrays.showArrays(data_ortho, width, height,  true, "ortho-back-pre-"+title, dbg_titles);
1682 1683 1684 1685 1686 1687 1688 1689 1690 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
		}

		// put back to ortho (so far no transition, no ortho blur)
		// Blur dXY, not dRT!

		for (int l = 0; l < 2; l++) {
			(new DoubleGaussianBlur() ).blurDouble(data_xy[l], width, height, gaus_rad, gaus_rad, 0.01);
		}
		data_rt = DXYtoDRT(
				data_xy, // [0] - dx, [1] - dy
				width,
				decimate,
				x0,
				y0);
		for (int l = 0; l < 2; l++) {
			data_ortho[l+1] = data_rt[l];
		}


		double [][] polar_back = {
				data_polar[0], // weight
				data_polar_blur[1],
				data_polar_blur[2],
				data_polar_blur[3],
				data_polar_blur[4],
				data_polar_blur[5]};


		(new DoubleGaussianBlur() ).blurDouble(data_ortho[0], width, height, gaus_rad, gaus_rad, 0.01); // is it needed - blur alpha?

		for (int l = 3; l < data_ortho.length; l++) { // only R,G,B
			(new DoubleGaussianBlur() ).blurDouble(data_ortho[l], width, height, gaus_rad, gaus_rad, 0.01);
		}

//		if (showDebugImages) {
1717
//			ShowDoubleFloatArrays.showArrays(polar_back, polar_width, polar_height,  true, "polar-back-"+title, dbg_titles);
1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730
//		}

		correctionToOrtho(
				data_ortho, // variable number of layers, will be modifier from the overlapping radial)
				polar_back, // same layers as ortho, will be used as a source
				width,
				decimate,
				x0,
				y0,
				inner_rad_d, // margins (minimal from all sides)
				lines_overlap, // add lines to the bottom (corresponding to the angle)
				transit_rad); // smooth transition between ortho and polar width
		if (showDebugImages) {
1731
			ShowDoubleFloatArrays.showArrays(data_ortho, width, height,  true, "ortho-back"+title, dbg_titles);
1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750
		}

		double [][] data_rt_back = {data_ortho[1], data_ortho[2]};
		double [][] data_xy_back = DRTtoDXY(
				data_rt_back, // [0] - dx, [1] - dy
				width,
				decimate,
				x0,
				y0);

		preData[indexWeight] = data_ortho[0];
		preData[indexDx] =     data_xy_back[0]; // data_ortho[1];
		preData[indexDy] =     data_xy_back[1]; // data_ortho[2];
		preData[indexR] =      data_ortho[3];
		preData[indexG] =      data_ortho[4];
		preData[indexB] =      data_ortho[5];

	}

Andrey Filippov's avatar
Andrey Filippov committed
1751
	public void addOldXYCorrectionToCurrent(
1752 1753
//			boolean invert,
    		RefineParameters refineParameters,
Andrey Filippov's avatar
Andrey Filippov committed
1754 1755
    		double [][][] sensorXYCorr
			){
1756
		if (this.pixelCorrection==null) return; // no modifications are needed
Andrey Filippov's avatar
Andrey Filippov committed
1757
		for (int i=0;i<sensorXYCorr.length;i++) if ((sensorXYCorr[i]!=null) && (this.pixelCorrection[i]!=null)) {
1758 1759 1760
//			boolean small_sensor = fittingStrategy.distortionCalibrationData.isSmallSensor(i);
			boolean small_sensor = fittingStrategy.distortionCalibrationData.getSmallSensors()[i];
			
1761 1762 1763 1764 1765 1766 1767
			RefineParameters rp = small_sensor ? refineParameters.refineParametersSmall : refineParameters;
//			if (rp.sensorExtrapolateDiff ^ invert) { // add current correction AFTER extrapolationg/bluring
				double scale = rp.correctionScale;
				for (int j=0;j<sensorXYCorr[i][0].length;j++){
					sensorXYCorr[i][0][j]=this.pixelCorrection[i][0][j]+scale*sensorXYCorr[i][0][j];
					sensorXYCorr[i][1][j]=this.pixelCorrection[i][1][j]+scale*sensorXYCorr[i][1][j];
				}
Andrey Filippov's avatar
Andrey Filippov committed
1768
			}
1769
//		}
Andrey Filippov's avatar
Andrey Filippov committed
1770
	}
Andrey Filippov's avatar
Andrey Filippov committed
1771 1772 1773



Andrey Filippov's avatar
Andrey Filippov committed
1774 1775 1776 1777 1778 1779 1780 1781
	public void patternErrors(
			final int       threadsMax,
			final boolean   updateStatus,
			final int debugLevel
			){
		GenericDialog gd=new GenericDialog("Setup pattern errors map");
		gd.addNumericField("Series number", this.seriesNumber, 0,2,"");
		gd.addCheckbox    ("Show map", true);
Andrey Filippov's avatar
Andrey Filippov committed
1782

Andrey Filippov's avatar
Andrey Filippov committed
1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797
		gd.addNumericField("Minimal RMS", .07, 3,6,"pix");
		gd.addNumericField("Maximal RMS", 0.12, 3,6,"pix");
		gd.addNumericField("Expand EMS mask", 1, 0,2,"nodes");
		gd.addCheckbox    ("Update pattern weights", false);
		gd.addCheckbox    ("Reset error-based target map", false);
		gd.showDialog();
		if (gd.wasCanceled()) return;
		this.seriesNumber =      (int) gd.getNextNumber();
		boolean showMap=               gd.getNextBoolean();
 		double minRMS =                gd.getNextNumber();
 		double maxRMS =                gd.getNextNumber();
		int expandMask =         (int) gd.getNextNumber();

		boolean updateMap=              gd.getNextBoolean();
		boolean resetMap=              gd.getNextBoolean();
Andrey Filippov's avatar
Andrey Filippov committed
1798

Andrey Filippov's avatar
Andrey Filippov committed
1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819
		if (resetMap){
			this.patternParameters.resetPatternErrorMask();
			return;
		} else {
			double [] worstImageNumber=calculatePatterErrorRMS(
					this.seriesNumber,
					threadsMax,
					updateStatus,
					debugLevel);
			this.patternParameters.savePatternErrorMask();
			double [] savedMask=this.patternParameters.getSavedPatternErrorMask();
			this.patternParameters.calculatePatternErrorMask(maxRMS,minRMS);
			for (int i=0;i<expandMask;i++)this.patternParameters.expandPatternErrorMask();
			if (showMap){
				String [] titles={"mask","rms","worst image number","savedMask"};
				double [][] debugData={
						this.patternParameters.getPatternErrorMask(),
						this.patternParameters.getPatternErrors(),
						worstImageNumber,
						savedMask};
				 Rectangle gridDimensions=patternParameters.getUVDimensions();
1820
				ShowDoubleFloatArrays.showArrays(
Andrey Filippov's avatar
Andrey Filippov committed
1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834
						debugData,
						gridDimensions.width,
						gridDimensions.height,
						true,
						"TM_"+maxRMS+":"+minRMS,
						titles);
			}
			if (!updateMap) {
				System.out.println("Restoring mask to the previous state");
				this.patternParameters.restorePatternErrorMask();
			}
		}
	}

Andrey Filippov's avatar
Andrey Filippov committed
1835 1836


Andrey Filippov's avatar
Andrey Filippov committed
1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853
	public double []  calculatePatterErrorRMS( // returns worst image number array
			final int       series,
			final int       threadsMax,
			final boolean   updateStatus,
			final int debugLevel

	){
    	if (fittingStrategy==null) {
    		String msg="Fitting strategy does not exist, exiting";
    		IJ.showMessage("Error",msg);
    		throw new IllegalArgumentException (msg);
    	}
    	if (fittingStrategy.distortionCalibrationData.eyesisCameraParameters==null){
    		String msg="Eyesis camera parameters (and sensor dimensions) are not defined";
    		IJ.showMessage("Error",msg);
    		throw new IllegalArgumentException (msg);
    	}
Andrey Filippov's avatar
Andrey Filippov committed
1854
    	//	fittingStrategy.distortionCalibrationData.readAllGrids();
Andrey Filippov's avatar
Andrey Filippov committed
1855 1856 1857
//    	if (! selectGridEnhanceParameters()) return false;
//    	if (series<0) return null; // false; // make "all " later?
    	this.seriesNumber=series;
Andrey Filippov's avatar
Andrey Filippov committed
1858

Andrey Filippov's avatar
Andrey Filippov committed
1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884
    	initFittingSeries(true,this.filterForTargetGeometry,this.seriesNumber); // first step in series now uses pattern alpha
    	this.currentfX=calculateFxAndJacobian(this.currentVector, false);
    	//        	this.currentRMS= calcError(calcYminusFx(this.currentfX));
    	if (this.debugLevel>2) {
    		System.out.println("this.currentVector");
    		for (int i=0;i<this.currentVector.length;i++){
    			System.out.println(i+": "+ this.currentVector[i]);
    		}
    	}
		final boolean [] selectedImages=fittingStrategy.selectedImages();
		final Rectangle gridDimensions=patternParameters.getUVDimensions();
		final int width=  gridDimensions.width;
		final int height= gridDimensions.height;
//		final int U0=     gridDimensions.x;
//		final int V0=     gridDimensions.y;
		final double [][] gridErrors=new double [4][width*height]; // added debug features - worst image number
		for (int n=0;n<gridErrors.length;n++) for (int i=0;i<gridErrors[n].length;i++) gridErrors[n][i]=0.0;
		int numSelected=0;
		for (int imgNum=0;imgNum<selectedImages.length;imgNum++) if (selectedImages[imgNum]) numSelected++;
		final int finalSelected=numSelected;
		if (updateStatus) IJ.showStatus("Calculating pattern grid errors...");
   		final AtomicInteger imageNumberAtomic = new AtomicInteger(0);
   		final AtomicInteger imageFinishedAtomic = new AtomicInteger(0);
   		final Thread[] threads = newThreadArray(threadsMax);
   		for (int ithread = 0; ithread < threads.length; ithread++) {
   			threads[ithread] = new Thread() {
Andrey Filippov's avatar
Andrey Filippov committed
1885 1886
   				@Override
				public void run() {
Andrey Filippov's avatar
Andrey Filippov committed
1887 1888 1889 1890 1891 1892 1893 1894 1895 1896
   					double [][] partialGridErrors=new double [4][width*height];
   					for (int n=0;n<partialGridErrors.length;n++) for (int i=0;i<partialGridErrors[n].length;i++) partialGridErrors[n][i]=0.0;
   					for (int imgNum=imageNumberAtomic.getAndIncrement(); imgNum<selectedImages.length;imgNum=imageNumberAtomic.getAndIncrement()){
   						if (selectedImages[imgNum]){
   							accumulatePatternErrors(
   									partialGridErrors,
   									imgNum,
   									gridDimensions);
   							final int numFinished=imageFinishedAtomic.getAndIncrement();
   							SwingUtilities.invokeLater(new Runnable() {
Andrey Filippov's avatar
Andrey Filippov committed
1897 1898
   								@Override
								public void run() {
Andrey Filippov's avatar
Andrey Filippov committed
1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910
   									if (updateStatus) IJ.showProgress(numFinished,finalSelected);
   								}
   							});
   						} //if (selectedImages[numImage]){
   					} // for (int numImage=imageNumberAtomic.getAndIncrement(); ...
   					combinePatternErrors(partialGridErrors,gridErrors);
   				} // public void run() {
   			};
   		}
   		startAndJoin(threads);
   		for (int i=0;i<gridErrors[0].length;i++){
   			gridErrors[0][i]=(gridErrors[0][i]>0.0)?Math.sqrt(gridErrors[0][i]/gridErrors[1][i]):Double.NaN;
Andrey Filippov's avatar
Andrey Filippov committed
1911

Andrey Filippov's avatar
Andrey Filippov committed
1912 1913 1914 1915
   		}
   		patternParameters.setPatternErrors(gridErrors[0]);
   		return gridErrors[2]; // worst image number for target grid nodes
	}
Andrey Filippov's avatar
Andrey Filippov committed
1916

Andrey Filippov's avatar
Andrey Filippov committed
1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940
	public void accumulatePatternErrors(
			double [][] errorMap,
			int imgNum,
			Rectangle gridDimensions){
		int width=  gridDimensions.width;
//		int height= gridDimensions.height;
		int U0=     gridDimensions.x; // location of the grid center (U==0,V==0)
		int V0=     gridDimensions.y;
		double [] diff=calcYminusFx(this.currentfX, 2*this.imageStartIndex[imgNum],2*this.imageStartIndex[imgNum+1]);
		int [][] imgUV=	  this.fittingStrategy.distortionCalibrationData.gIP[imgNum].pixelsUV;
		for (int i=0;i<imgUV.length;i++){
			int index=width*(imgUV[i][1]+V0) + (imgUV[i][0]+U0);
			double w=this.weightFunction[2*(this.imageStartIndex[imgNum]+i)];
			double dX=diff[2*i];
			double dY=diff[2*i+1];
			double e2w=w*(dX*dX+dY*dY);
			errorMap[0][index]+=e2w;
			errorMap[1][index]+=w;
			if (e2w>errorMap[3][index]){
				errorMap[3][index]=e2w;    // worst error for this node
				errorMap[2][index]=imgNum; // worst (for that particular grig node) image number
			}
		}
	}
Andrey Filippov's avatar
Andrey Filippov committed
1941

Andrey Filippov's avatar
Andrey Filippov committed
1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952
	public synchronized void combinePatternErrors(
			double [][] partialErrorMap,
			double [][] fullErrorMap ){
//		for (int n=0;n<fullErrorMap.length;n++) for (int i=0;i<fullErrorMap[n].length;i++) fullErrorMap[n][i]+=partialErrorMap[n][i];
		for (int i=0;i<fullErrorMap[0].length;i++){
			fullErrorMap[0][i]+=partialErrorMap[0][i];
			fullErrorMap[1][i]+=partialErrorMap[1][i];
			if (fullErrorMap[3][i]<partialErrorMap[3][i]){
				fullErrorMap[2][i]=partialErrorMap[2][i];
				fullErrorMap[3][i]=partialErrorMap[3][i];
			}
Andrey Filippov's avatar
Andrey Filippov committed
1953

Andrey Filippov's avatar
Andrey Filippov committed
1954 1955 1956 1957
		}

	}

Andrey Filippov's avatar
Andrey Filippov committed
1958 1959 1960



Andrey Filippov's avatar
Andrey Filippov committed
1961 1962
	/**
	 * Calculate each sensor correction increment for geometry and photometry contributed by all images selected in a series
Andrey Filippov's avatar
Andrey Filippov committed
1963
	 * @param selectedImages process only selected images
Andrey Filippov's avatar
Andrey Filippov committed
1964 1965 1966 1967
	 * @param showIndividual show per-image intermediate results
	 * @param threadsMax maximal number of concurrent threads
	 * @param updateStatus update IJ status/progress
	 * @param debugLevel debug level
Andrey Filippov's avatar
Andrey Filippov committed
1968
	 * @return [sensor]{dpX,dpY,alpha,R,G,B}[pixelIndex] . dpX, dpY - correction to previous, RGB - total FF, not increment!
Andrey Filippov's avatar
Andrey Filippov committed
1969 1970 1971
	 */

	public double [][][]  allImagesCorrectionMapped(
1972 1973 1974 1975 1976
			final boolean []       selectedImages,
			final boolean          si,               // showIndividual,
			final RefineParameters refineParameters, // final int showIndividualNumber,
			final int              threadsMax,
			final boolean          updateStatus,
Andrey Filippov's avatar
Andrey Filippov committed
1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994
			final int debugLevel
			){
		int numChannels=  fittingStrategy.distortionCalibrationData.getNumChannels(); // number of used channels
		final double [][][] gridPCorr=new double [numChannels][][];
		for (int chnNum=0;chnNum<gridPCorr.length;chnNum++) gridPCorr[chnNum]=null;
		int numSelected=0;
		for (int imgNum=0;imgNum<selectedImages.length;imgNum++) if (selectedImages[imgNum]) numSelected++;
		final int finalSelected=numSelected;
		if (updateStatus) IJ.showStatus("Calculating sensor corrections...");
   		final AtomicInteger imageNumberAtomic = new AtomicInteger(0);
   		final AtomicInteger imageFinishedAtomic = new AtomicInteger(0);
   		final Thread[] threads = newThreadArray(threadsMax);
   		final AtomicInteger stopRequested=this.stopRequested;
		final AtomicBoolean interruptedAtomic=new AtomicBoolean();
		final int alphaIndex=2;

   		for (int ithread = 0; ithread < threads.length; ithread++) {
   			threads[ithread] = new Thread() {
Andrey Filippov's avatar
Andrey Filippov committed
1995 1996
   				@Override
				public void run() {
Andrey Filippov's avatar
Andrey Filippov committed
1997 1998 1999
   					for (int imgNum=imageNumberAtomic.getAndIncrement(); (imgNum<selectedImages.length) && !interruptedAtomic.get();imgNum=imageNumberAtomic.getAndIncrement()){
   						if (selectedImages[imgNum]){
   							int chnNum=fittingStrategy.distortionCalibrationData.gIP[imgNum].channel; // number of sub-camera
2000 2001
   	   						//boolean small_sensor = fittingStrategy.distortionCalibrationData.isSmallSensor(chnNum);
   	   						boolean small_sensor = fittingStrategy.distortionCalibrationData.getSmallSensors()[chnNum];
2002 2003 2004
   	   						RefineParameters rp = small_sensor ? refineParameters.refineParametersSmall : refineParameters;
   	   						boolean   showIndividual = si && rp.showPerImage;
   	   						int showIndividualNumber = rp.showIndividualNumber;
Andrey Filippov's avatar
Andrey Filippov committed
2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016
   							double [][] singleCorr=
   								singleImageCorrectionMapped(
   									imgNum, // image number
   									showIndividual && ((showIndividualNumber<0) || (showIndividualNumber==chnNum)),
   									debugLevel);
   							combineImageCorrection(
   									chnNum,
   									gridPCorr,
   									singleCorr
   							);
   							final int numFinished=imageFinishedAtomic.getAndIncrement();
   							SwingUtilities.invokeLater(new Runnable() {
Andrey Filippov's avatar
Andrey Filippov committed
2017 2018
   								@Override
								public void run() {
Andrey Filippov's avatar
Andrey Filippov committed
2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038
   									if (updateStatus) IJ.showProgress(numFinished,finalSelected);
   								}
   							});
   	   						if (stopRequested.get()==1){ // ASAP
   	   							interruptedAtomic.set(true);
   	   						}
   						} //if (selectedImages[numImage]){
   					} // for (int numImage=imageNumberAtomic.getAndIncrement(); ...
   				} // public void run() {
   			};
   		}
   		startAndJoin(threads);
   		// divide by weight;
   		for (int nChn=0;nChn<gridPCorr.length;nChn++) if (gridPCorr[nChn]!=null){
   			for (int i=0;i<gridPCorr[nChn].length;i++) {
   				if (i!=alphaIndex){
   					for (int j=0; j<gridPCorr[nChn][i].length;j++){
   						if (gridPCorr[nChn][alphaIndex][j]>0) gridPCorr[nChn][i][j]/=gridPCorr[nChn][alphaIndex][j];
   					}
   				}
Andrey Filippov's avatar
Andrey Filippov committed
2039
   			}
Andrey Filippov's avatar
Andrey Filippov committed
2040
   		}
Andrey Filippov's avatar
Andrey Filippov committed
2041

Andrey Filippov's avatar
Andrey Filippov committed
2042
		if (updateStatus) IJ.showProgress(0);
Andrey Filippov's avatar
Andrey Filippov committed
2043

Andrey Filippov's avatar
Andrey Filippov committed
2044 2045 2046 2047 2048 2049
   		if (interruptedAtomic.get()) {
   			System.out.println("allImagesCorrection() aborted by user request");
   			return null;
   		}
   		return gridPCorr;
	}
2050
	@Deprecated
Andrey Filippov's avatar
Andrey Filippov committed
2051 2052 2053
	public void allSensorsExtrapolationMapped(
			final int stationNumber, // has to be selected
			final double [][][] gridPCorr,
2054
			final RefineParameters refineParameters, //
Andrey Filippov's avatar
Andrey Filippov committed
2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074
			final int       threadsMax,
			final boolean   updateStatus,
			final boolean showDebugImages,
			final int debugLevel
			){
		if (updateStatus) IJ.showStatus("Extrapolating sensor corrections...");
   		final AtomicInteger sensorNumberAtomic = new AtomicInteger(0);
   		final AtomicInteger sensorFinishedAtomic = new AtomicInteger(0);
   		final Thread[] threads = newThreadArray(threadsMax);
   		final AtomicInteger stopRequested=this.stopRequested;
		final AtomicBoolean interruptedAtomic=new AtomicBoolean();
		final EyesisSubCameraParameters [] eyesisSubCameras = this.fittingStrategy.distortionCalibrationData.eyesisCameraParameters.eyesisSubCameras[stationNumber];
		final double [][] sensorMasks=this.fittingStrategy.distortionCalibrationData.sensorMasks;

		final int alphaIndex=2;

		final boolean extraShowDebug=showDebugImages&& (debugLevel>2);

   		for (int ithread = 0; ithread < threads.length; ithread++) {
   			threads[ithread] = new Thread() {
Andrey Filippov's avatar
Andrey Filippov committed
2075 2076
   				@Override
				public void run() {
Andrey Filippov's avatar
Andrey Filippov committed
2077 2078 2079 2080 2081 2082 2083 2084
   					DoubleGaussianBlur gb=null;
   					double [][] debugMasks1=null;
   					double [][] debugMasks2=null;
   					String [] debugMaskTitles={"original","blured"};
   					if (extraShowDebug){
   						debugMasks1=new double[2][];
   						debugMasks2=new double[2][];
   					}
2085 2086
//   					if (shrinkBlurComboSigma>0.0) gb=new DoubleGaussianBlur();
   					gb=new DoubleGaussianBlur();
Andrey Filippov's avatar
Andrey Filippov committed
2087
   					for (int sensorNum=sensorNumberAtomic.getAndIncrement(); (sensorNum<gridPCorr.length) && !interruptedAtomic.get();sensorNum=sensorNumberAtomic.getAndIncrement()){
2088 2089
//   						boolean small_sensor = fittingStrategy.distortionCalibrationData.isSmallSensor(sensorNum);
   						boolean small_sensor = fittingStrategy.distortionCalibrationData.getSmallSensors()[sensorNum];
2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117
   						RefineParameters rp = small_sensor ? refineParameters.refineParametersSmall : refineParameters;
   						if (rp.extrapolate) {
   							int sensorWidth=   fittingStrategy.distortionCalibrationData.eyesisCameraParameters.getSensorWidth(sensorNum);
   							int sensorHeight=  fittingStrategy.distortionCalibrationData.eyesisCameraParameters.getSensorHeight(sensorNum);
   							int decimation=fittingStrategy.distortionCalibrationData.eyesisCameraParameters.getDecimateMasks(sensorNum);
   							int width= (sensorWidth-1)/decimation+1; // decimated width (648)
   							int height= (sensorHeight-1)/decimation+1; // decimated width (648)

   							if (gridPCorr[sensorNum]!=null){
   								final double [] centerPXY={
   										eyesisSubCameras[sensorNum].px0,
   										eyesisSubCameras[sensorNum].py0
   								};
   								if (rp.sensorShrinkBlurComboSigma>0.0){
   									double sigma=rp.sensorShrinkBlurComboSigma/decimation;
   									int margin=(int) (2*sigma);
   									int width1=width+2*margin;
   									int height1=height+2*margin;
   									if (extraShowDebug) debugMasks2[0]=gridPCorr[sensorNum][alphaIndex].clone();
   									double [] mask= addMarginsThreshold(
   											gridPCorr[sensorNum][alphaIndex], // double [] data,
   											0.0, // double threshold,
   											width,
   											height,
   											margin);
   									if (extraShowDebug) debugMasks1[0]=mask.clone();
   									gb.blurDouble(
   											mask,
Andrey Filippov's avatar
Andrey Filippov committed
2118 2119
   											width1,
   											height1,
2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132
   											sigma,
   											sigma,
   											0.01);

   									double k=1.0/(1.0-rp.sensorShrinkBlurComboLevel);
   									for (int i=0;i<mask.length;i++) {
   										mask[i]=k*(mask[i]-rp.sensorShrinkBlurComboLevel);
   										mask[i]=(mask[i]>0.0)?(mask[i]*mask[i]):0.0;
   									}
   									if (extraShowDebug) debugMasks1[1]=mask.clone();
   									gridPCorr[sensorNum][alphaIndex]=removeMargins(
   											mask, //double [] data,
   											width, // w/o margins
Andrey Filippov's avatar
Andrey Filippov committed
2133
   											height,
2134 2135 2136
   											margin); //mask; // replace with 0.0 .. 1.0 mask
   									if (extraShowDebug) debugMasks2[1]=gridPCorr[sensorNum][alphaIndex].clone();
   									if (extraShowDebug) {
2137
   										ShowDoubleFloatArrays.showArrays(
2138 2139 2140 2141 2142 2143
   												debugMasks1,
   												width1,
   												height1,
   												true,
   												"M1-"+sensorNum,
   												debugMaskTitles);
2144
   										ShowDoubleFloatArrays.showArrays(
2145 2146 2147 2148 2149 2150 2151
   												debugMasks2,
   												width,
   												height,
   												true,
   												"M2-"+sensorNum,
   												debugMaskTitles);
   									}
Andrey Filippov's avatar
Andrey Filippov committed
2152 2153

   								}
2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182
   								singleSensorExtrapolationMapped(
   										sensorNum,
   										gridPCorr[sensorNum],
   										sensorMasks[sensorNum],
   										width,
   										decimation,
   										rp.sensorAlphaThreshold,
   										rp.sensorStep,
   										centerPXY,
   										rp.sensorInterpolationSigma,
   										rp.sensorTangentialRadius,
   										rp.sensorScanDistance,
   										rp.sensorResultDistance,
   										rp.sensorInterpolationDegree,
   										(rp.sensorShrinkBlurComboSigma > 0.0),
   										showDebugImages,
   										debugLevel);
   								final int numFinished=sensorFinishedAtomic.getAndIncrement();
   								SwingUtilities.invokeLater(new Runnable() {
   									@Override
   									public void run() {
   										if (updateStatus) IJ.showProgress(numFinished,gridPCorr.length);
   									}
   								});
   								if (stopRequested.get()==1){ // ASAP
   									interruptedAtomic.set(true);
   								}
   							}
   						} //if (rp.extrapolate); // if (selectedImages[numImage]){
Andrey Filippov's avatar
Andrey Filippov committed
2183 2184 2185 2186 2187 2188 2189 2190
   					} // for (int numImage=imageNumberAtomic.getAndIncrement(); ...
   				} // public void run() {
   			};
   		}
   		startAndJoin(threads);
		if (updateStatus) IJ.showProgress(0);
   		return;
	}
2191 2192
 @Deprecated
 	public double [] addMargins(
Andrey Filippov's avatar
Andrey Filippov committed
2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212
			double [] data,
			double marginData,
			int width,
			int height,
			int margin){
		int width1= width+ 2*margin;
		int height1=height+2*margin;
		int length1=width1*height1;
		double [] result = new double [length1];
		for (int i=0;i<length1;i++) result[i] = marginData;
		int indexDest=margin*(width1+1);
		int indexSrc=0;
		for (int y=0;y<height;y++){
			for (int x=0;x<width;x++){
				result[indexDest++]=data[indexSrc++];
			}
			indexDest+=2*margin;
		}
		return result;
	}
2213
    @Deprecated
Andrey Filippov's avatar
Andrey Filippov committed
2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234
	public double [] addMarginsThreshold(
			double [] data,
			double threshold,
			int width,
			int height,
			int margin){
		int width1= width+ 2*margin;
		int height1=height+2*margin;
		int length1=width1*height1;
		double [] result = new double [length1];
		for (int i=0;i<length1;i++) result[i] = -1.0;
		int indexDest=margin*(width1+1);
		int indexSrc=0;
		for (int y=0;y<height;y++){
			for (int x=0;x<width;x++){
				result[indexDest++]=(data[indexSrc++]>threshold)?1.0:-1.0;
			}
			indexDest+=2*margin;
		}
		return result;
	}
2235
    @Deprecated
Andrey Filippov's avatar
Andrey Filippov committed
2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254
	public double [] removeMargins(
			double [] data,
			int width, // w/o margins
			int height,
			int margin){
		int width1= width+ 2*margin;
//		int height1=height+2*margin;
		int length=width*height;
		double [] result = new double [length];
		int indexSrc=margin*(width1+1);
		int indexDest=0;
		for (int y=0;y<height;y++){
			for (int x=0;x<width;x++){
				result[indexDest++]=data[indexSrc++];
			}
			indexSrc+=2*margin;
		}
		return result;
	}
2255
    @Deprecated
Andrey Filippov's avatar
Andrey Filippov committed
2256 2257 2258 2259 2260 2261 2262 2263 2264 2265
	public void singleSensorExtrapolationMapped(
			int sensoNum,
			double [][] gridPCorr,
			double [] sensorMask,
			int width,
			int decimation,
			double alphaThreshold,
			double step,
			double [] centerPXY,
			double interpolationSigma, // sensor pixels
Andrey Filippov's avatar
Andrey Filippov committed
2266
			double tangentialRadius,
Andrey Filippov's avatar
Andrey Filippov committed
2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328
			int    scanDistance,       // sensor pixels
			int resultDistance,
			int interpolationDegree,
			boolean useAlpha, // false - sensor mask
			boolean showDebugImages,
			int debugLevel
			){
		int dxIndex=0;
		int alphaIndex=2;
		int rIndex=3;
		int height=gridPCorr[0].length/width;
		double gaussianK=-0.5/(interpolationSigma*interpolationSigma);
		double tangR0=tangentialRadius*Math.sqrt(width*height)*decimation/2; // sigma in tangential direction is interpolationSigma*(1+r/tangR0), in radial - interpolationSigma
		PolynomialApproximation polynomialApproximation =new PolynomialApproximation(0);// no debug
		int length=gridPCorr[0].length;
		DirInc dirInc= new DirInc(width,height);
		int [] iMap = new int[length];
		for (int i=0;i<length;i++) iMap[i]= (gridPCorr[alphaIndex][i]>=alphaThreshold)?1:0;
		List <Integer>waveList=new ArrayList<Integer>(1000);
		for (int index0=0;index0<length;index0++) if (iMap[index0]==0){
			for (int iDir=0;iDir<8;iDir+=2){
				int index=dirInc.newIndex(index0,iDir);
				if ((index>=0) && (iMap[index]==1)){
					iMap[index0]=2;
					waveList.add(new Integer(index0));
					break;
				}
			}
		}
// decimate the wave list
		List <Integer> seedList=new ArrayList<Integer>(1000);
		int oldIndex=0; // find better start?
		int s2= (int) Math.floor(step*step);
		while (waveList.size()>0){
			int oldX=oldIndex%width;
			int oldY=oldIndex/width;
			int bestD2=height*height+width*width;
			int nBest=-1;
			for (int n=0;n<waveList.size();n++){
				int index=waveList.get(n);
				int dx=index%width-oldX;
				int dy=index/width-oldY;
				int d2=dx*dx+dy*dy;
				if (d2<bestD2){
					bestD2=d2;
					nBest=n;
				}
			}
			oldIndex=waveList.remove(nBest);
			seedList.add(new Integer(oldIndex));
			oldX=oldIndex%width;
			oldY=oldIndex/width;
			// remove all closer than step
			for (int n=0;n<waveList.size();n++){ // size will change
				int index=waveList.get(n);
				int dx=index%width-oldX;
				int dy=index/width-oldY;
				int d2=dx*dx+dy*dy;
				if (d2<s2){
					waveList.remove(n);
				}
			}
Andrey Filippov's avatar
Andrey Filippov committed
2329

Andrey Filippov's avatar
Andrey Filippov committed
2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353
		} //while (waveList.size()>0)
		// debug show waves?
		Rectangle full=new Rectangle (0,0,width,height);
		double [][] extrapolated=new double [gridPCorr.length][length];
		for (int n=0;n<extrapolated.length;n++) for (int i=0;i<extrapolated[n].length;i++) extrapolated[n][i]=0.0;
		int halfScanSize=scanDistance/decimation+1;
		int halfInterpolteSize=resultDistance/decimation+1;
		for (int n=0; n<seedList.size();n++) {
			int index0=seedList.get(n);
			int x0=index0%width;
			int y0=index0/width;
			double [] dCxy0={
					x0*decimation-centerPXY[0],
					y0*decimation-centerPXY[1]
			};
			double r0=Math.sqrt(dCxy0[0]*dCxy0[0]+dCxy0[1]*dCxy0[1]);
			final Rectangle scan =full.intersection(new Rectangle (x0-halfScanSize,y0-halfScanSize,2*halfScanSize+1,2*halfScanSize+1));
			waveList.clear();
			for (int y=scan.y;y<(scan.y+scan.height);y++) for (int x=scan.x;x<(scan.x+scan.width);x++) {
				int index=y*width+x;
				if (iMap[index]==1)	waveList.add(new Integer(index));
			}
			double [][][] data = new double [5][waveList.size()][3]; // x,y,w
			double sumWeights=0.0;
Andrey Filippov's avatar
Andrey Filippov committed
2354
			double rScaleTangSigma=1.0/(1.0+r0/tangR0); //
Andrey Filippov's avatar
Andrey Filippov committed
2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372
			for (int i=0;i<data[0].length;i++){
				int index=waveList.get(i);
				int x=index%width;
				int y=index/width;
				double [] dCxy={
						x*decimation-centerPXY[0],
						y*decimation-centerPXY[1]
				};
				double [] ddCxy={
						dCxy[0]-dCxy0[0],
						dCxy[1]-dCxy0[1]
				};
				double rc=Math.sqrt(dCxy[0]*dCxy[0]+dCxy[1]*dCxy[1]); // distance from lens center (in sensor pixels)
				double rDiff=rc-r0;
				double [] uRadVect={(rc>0.0)?(dCxy[0]/rc):0.0, (rc>0.0)?(dCxy[1]/rc):0.0};

				double distRad= ddCxy[0]*uRadVect[0]+ddCxy[1]*uRadVect[1]; // radial distance form the center (seed point)
				double distTan=-ddCxy[0]*uRadVect[1]+ddCxy[1]*uRadVect[0]; // tangential distance form the center (seed point)
Andrey Filippov's avatar
Andrey Filippov committed
2373 2374
				distTan*=rScaleTangSigma; // // for the center (seed point). was  distTan/=(1.0+rc/tangR0);
				double w=Math.exp(gaussianK*(distRad*distRad+distTan*distTan))*gridPCorr[alphaIndex][index];
Andrey Filippov's avatar
Andrey Filippov committed
2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416
				sumWeights+=w;

				double dRad= gridPCorr[dxIndex+0][index]*uRadVect[0]+gridPCorr[dxIndex+1][index]*uRadVect[1]; // radial component
				double dTan=-gridPCorr[dxIndex+0][index]*uRadVect[1]+gridPCorr[dxIndex+1][index]*uRadVect[0]; // tangential component
				data[0][i][1]=dRad;
				data[1][i][1]=dTan;

				data[2][i][1]=gridPCorr[rIndex+0][index]; // R
				data[3][i][1]=gridPCorr[rIndex+1][index]; // G
				data[4][i][1]=gridPCorr[rIndex+2][index]; // B
				for (int j=0;j<data.length;j++){
					data[j][i][0]=rDiff;
					data[j][i][2]=w;
				}
			}
			sumWeights*=rScaleTangSigma; // normalize for expanded in one dimension gaussian
			double [][] poly=new double [data.length][];
			for (int j=0;j<poly.length;j++) {
				poly[j]=polynomialApproximation.polynomialApproximation1d(data[j],interpolationDegree);
			}
			if (poly[0]==null) { // all will be either null, or not - [0] testing is enough
				System.out.println("singleSensorExtrapolationMapped() BUG - poly[0]==null");
//				stageReprojPXY[index0]=null;
				continue;
			}
			final Rectangle rInterpolate =full.intersection(new Rectangle (x0-halfInterpolteSize,y0-halfInterpolteSize,2*halfInterpolteSize+1,2*halfInterpolteSize+1));
			for (int y=rInterpolate.y;y<(rInterpolate.y+rInterpolate.height);y++) for (int x=rInterpolate.x;x<(rInterpolate.x+rInterpolate.width);x++) {
				int index=y*width+x;
				double [] dCxy={
						x*decimation-centerPXY[0],
						y*decimation-centerPXY[1]
				};
				double [] ddCxy={
						dCxy[0]-dCxy0[0],
						dCxy[1]-dCxy0[1]
				};
				double rc=Math.sqrt(dCxy[0]*dCxy[0]+dCxy[1]*dCxy[1]); // distance from lens center (in sensor pixels)
				double rDiff=rc-r0;
				double [] uRadVect={(rc>0.0)?(dCxy[0]/rc):0.0, (rc>0.0)?(dCxy[1]/rc):0.0};

				double distRad= ddCxy[0]*uRadVect[0]+ddCxy[1]*uRadVect[1]; // radial distance form the center (seed point)
				double distTan=-ddCxy[0]*uRadVect[1]+ddCxy[1]*uRadVect[0]; // tangential distance form the center (seed point)
Andrey Filippov's avatar
Andrey Filippov committed
2417
				distTan*=rScaleTangSigma;
Andrey Filippov's avatar
Andrey Filippov committed
2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466
				double w=Math.exp(gaussianK*(distRad*distRad+distTan*distTan)); //*gridPCorr[alphaIndex][index];
				w*=sumWeights; // more points were used in coefficients calculation, more trust to that extrapolation
				// extrapolate each value using polynomial coefficients
				double [] results= new double [poly.length];
				for (int nPar=0;nPar<results.length;nPar++){
					double rN=1.0;
					results[nPar]=0.0;
					for (int dgr=0;dgr<poly[nPar].length;dgr++){
						results[nPar]+=poly[nPar][dgr]*rN;
						rN*=rDiff;
					}
				}
				// restore dX, dY from radial/tangential
				double [] diffPXY={
						results[0]*uRadVect[0]-results[1]*uRadVect[1],
						results[0]*uRadVect[1]+results[1]*uRadVect[0]};
                //accumulate
				extrapolated[dxIndex+0][index]+=diffPXY[0]*w;
				extrapolated[dxIndex+1][index]+=diffPXY[1]*w;
				extrapolated[rIndex+0][index]+=results[2]*w;
				extrapolated[rIndex+1][index]+=results[3]*w;
				extrapolated[rIndex+2][index]+=results[4]*w;
				extrapolated[alphaIndex][index]+=w;
			}
		} // for (int n=0; n<seedList.size();n++) {
		// divide by weight
		for (int index=0;index<length;index++) if (extrapolated[alphaIndex][index]>0.0){
			for (int i=0;i<extrapolated.length;i++) if (i!=alphaIndex){
				extrapolated[i][index]/=extrapolated[alphaIndex][index];
			}
		}
		// debug show here extrapolated
		if (showDebugImages){
			String [] debugTiles={"dX","dY","alpha","R","G","B","mask"};
			double [] debugMask=new double[length];
			for (int i=0;i<length;i++) debugMask[i]=iMap[i];
			for (int n=0; n<seedList.size();n++) {
				int index=seedList.get(n);
				debugMask[index]+=3.0;
			}
			//iMap[index0]
			double [][] debugData={
					extrapolated[0],
					extrapolated[1],
					extrapolated[2],
					extrapolated[3],
					extrapolated[4],
					extrapolated[5],
					debugMask};
2467
			ShowDoubleFloatArrays.showArrays(
Andrey Filippov's avatar
Andrey Filippov committed
2468 2469 2470 2471 2472 2473 2474 2475 2476 2477
					debugData,
					width,
					height,
					true,
					"EX-"+sensoNum,
					debugTiles);

		}
		// mix interpolated with original data
// double [] sensorMask,
Andrey Filippov's avatar
Andrey Filippov committed
2478
//gridPCorr
Andrey Filippov's avatar
Andrey Filippov committed
2479 2480 2481 2482 2483 2484 2485
		for (int index=0;index<length;index++) if (extrapolated[alphaIndex][index]>0.0){
			for (int i=0;i<extrapolated.length;i++) if (i!=alphaIndex){
				double w=useAlpha?(gridPCorr[alphaIndex][index]):((gridPCorr[alphaIndex][index]>0.0)?sensorMask[index]:0.0);
				gridPCorr[i][index]=gridPCorr[i][index]*w+extrapolated[i][index]*(1.0-w);
			}
		}
	}
2486
    // used 2020
Andrey Filippov's avatar
Andrey Filippov committed
2487 2488 2489 2490 2491 2492 2493 2494 2495 2496
	public synchronized void combineImageCorrection(
			int chnNum,
			double [][][] gridPCorr,
			double [][] singleCorr
	){
		int alphaIndex=2;

		if (gridPCorr[chnNum]==null){
			gridPCorr[chnNum]=new double [singleCorr.length][singleCorr[0].length];
			for (int i=0;i<singleCorr.length;i++) for (int j=0; j<singleCorr[i].length;j++){
Andrey Filippov's avatar
Andrey Filippov committed
2497
				gridPCorr[chnNum][i][j]=0.0;
Andrey Filippov's avatar
Andrey Filippov committed
2498 2499 2500 2501 2502 2503 2504 2505
			}
		}
		for (int i=0;i<singleCorr.length;i++) {
			if (i==alphaIndex){
				for (int j=0; j<singleCorr[i].length;j++) gridPCorr[chnNum][i][j]+=singleCorr[i][j];
			} else {
				for (int j=0; j<singleCorr[i].length;j++) gridPCorr[chnNum][i][j]+=singleCorr[i][j]*singleCorr[alphaIndex][j];
			}
Andrey Filippov's avatar
Andrey Filippov committed
2506
		}
Andrey Filippov's avatar
Andrey Filippov committed
2507 2508 2509
	}

	/**
Andrey Filippov's avatar
Andrey Filippov committed
2510
	 * Calculate sensor correction increment for geometry and photometry contributed by a single image
Andrey Filippov's avatar
Andrey Filippov committed
2511
	 * @param imgNum  number of image
Andrey Filippov's avatar
Andrey Filippov committed
2512
	 * @param maxSensorMask maximal value of the sensor mask for this sensor to start extrapolating
Andrey Filippov's avatar
Andrey Filippov committed
2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529
	 * @param minContrast minimal measured grid contrast to seed extrapolating  - to prevent expansion in the areas where this particular sensor has bad data
	 * @param minTargetAlpha - minimal alpha of the target node
	 * @param useTargetAlpha   false - only use contrast of the detected grid, true - multiply contrast by grid alpha
	 * @param showIntermediate - show intermediate data as images
	 * @param debugLevel debug level
	 * @return scan-line pixels additional correction arrays {dpX,dpY,alpha,R,G,B}[pixelIndex]
	 */
	public double [][]  singleImageCorrectionMapped(
			int imgNum, // image number
			boolean showIntermediate,
			int debugLevel
			){
		CorrectionInNodes correctionInNodes=extractNodeCorrections(
				imgNum, // image number
				showIntermediate,
				debugLevel);
		if (showIntermediate) correctionInNodes.show("finNode-"+imgNum);
2530 2531 2532 2533
		int chnNum=fittingStrategy.distortionCalibrationData.gIP[imgNum].channel;
		int sensorWidth=   fittingStrategy.distortionCalibrationData.eyesisCameraParameters.getSensorWidth(chnNum);
		int sensorHeight=  fittingStrategy.distortionCalibrationData.eyesisCameraParameters.getSensorHeight(chnNum);
		int decimation=fittingStrategy.distortionCalibrationData.eyesisCameraParameters.getDecimateMasks(chnNum);
Andrey Filippov's avatar
Andrey Filippov committed
2534 2535 2536 2537 2538 2539 2540
		double [][] additionalCorrection=correctionInNodes.mapToPixels(
				decimation,
				sensorWidth,
				sensorHeight,
				debugLevel);
		if (showIntermediate){
			String [] dbgTitles={"dPX","dPY","alpha","R","G","B"};
2541
			ShowDoubleFloatArrays.showArrays(
Andrey Filippov's avatar
Andrey Filippov committed
2542 2543 2544 2545 2546 2547 2548
					additionalCorrection,
					sensorWidth/decimation,
					sensorHeight/decimation,
					true,
					"AC-"+imgNum,
					dbgTitles);
		}
Andrey Filippov's avatar
Andrey Filippov committed
2549

Andrey Filippov's avatar
Andrey Filippov committed
2550 2551 2552
		return additionalCorrection;
	}

Andrey Filippov's avatar
Andrey Filippov committed
2553

Andrey Filippov's avatar
Andrey Filippov committed
2554 2555 2556 2557 2558 2559
	/**
	 * @param imgNum  number of image
	 * @param showIntermediate - show intermediate images
	 * @param debugLevel debug level
	 * @return CorrectionInNodes data correction, image and grid data for some target grid nodes
	 */
Andrey Filippov's avatar
Andrey Filippov committed
2560

Andrey Filippov's avatar
Andrey Filippov committed
2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572
	public CorrectionInNodes extractNodeCorrections(
			int imgNum, // image number
			boolean showIntermediate,
			int debugLevel
			){
//		int debugThreshold=2;
    	int imgRGBIndex=   3;
		int chnNum=fittingStrategy.distortionCalibrationData.gIP[imgNum].channel; // number of sub-camera
		int station=fittingStrategy.distortionCalibrationData.gIP[imgNum].getStationNumber(); // number of sub-camera
		LensDistortionParameters lensDistortionParameters= setupLensDistortionParameters(
				imgNum,
				debugLevel);     // Axial - may be Double.NaN
Andrey Filippov's avatar
Andrey Filippov committed
2573

Andrey Filippov's avatar
Andrey Filippov committed
2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596
		int [][] imgUV=	  fittingStrategy.distortionCalibrationData.gIP[imgNum].pixelsUV;
		double [][] imgXY=fittingStrategy.distortionCalibrationData.gIP[imgNum].pixelsXY; // for each image, each grid node - a set of of {px,py,contrast,vignR,vignG,vignB} vign* is in the 0..1.0 range
		if ((imgUV==null) || (imgUV.length==0)) {
			System.out.println("expandMeasuredGrid("+imgNum+",..) empty image");
			return null;
		}
		int minU=imgUV[0][0];
		int minV=imgUV[0][1];
		int maxU=minU;
		int maxV=minV;
		for (int i=1;i<imgUV.length;i++){
			if (minU>imgUV[i][0]) minU=imgUV[i][0];
			if (minV>imgUV[i][1]) minV=imgUV[i][1];
			if (maxU<imgUV[i][0]) maxU=imgUV[i][0];
			if (maxV<imgUV[i][1]) maxV=imgUV[i][1];
		}
		int extraMargins=1;
		int [] uv0= {minU-extraMargins,minV-extraMargins}; // target U,V at the stageXYA[0]
		int width= maxU-minU+1+2*extraMargins;
		int height=maxV-minV+1+2*extraMargins;
		double [][] stagePXY= new double [width*height][]; //reprojected {px,py}
		double [][] stageDiffPXY=   new double [width*height][]; // difference between corrected measured and reprojected (to add to correction)
		double [][] stageDiffRGB=   new double [width*height][]; // difference (measured RGB)/(grid RGB) and current correction RGB (pixel sensitivity RGB)
Andrey Filippov's avatar
Andrey Filippov committed
2597
		double [] stageMask=        new double [width*height];   // weight
Andrey Filippov's avatar
Andrey Filippov committed
2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635
		for (int i=0;i<stagePXY.length;i++) {
			stagePXY[i]=null;
			stageDiffPXY[i]  =null;
			stageDiffRGB[i] = null;
		}
//		int vignRIndex=3; //  in measured data
		int corrRIndex=3; // in correction vector
//		int gridRIndex=3; // in reprojected vector
		double [] diff=calcYminusFx(this.currentfX, 2*this.imageStartIndex[imgNum],2*this.imageStartIndex[imgNum+1]);
		double [][] photometrics=patternParameters.getPhotometricBySensor(station,chnNum); // head/bottom grid intensity/alpha
		int targetGridWidth=getGridWidth();
		double [][] debugRGB=null;
		if (showIntermediate){
			debugRGB = new double [12][width*height];
			for (int n=0;n<debugRGB.length;n++) for (int i=0;i<debugRGB[n].length;i++) debugRGB[n][i]=0.0;
		}
		for (int i=0;i<imgUV.length;i++){
			int index=width*(imgUV[i][1]-uv0[1]) + (imgUV[i][0]-uv0[0]);
			int targetGridIndex=targetGridWidth*(imgUV[i][1]+patternParameters.V0) +(imgUV[i][0]+patternParameters.U0); // index in photometrics[][]
			int doublePairIndex=2*(this.imageStartIndex[imgNum]+i); // number of a pair in a full vector
			stageMask[index]=this.weightFunction[doublePairIndex];
			stagePXY[index]=null;
			double [] debugCorrVector=null;
			if (showIntermediate) {
				debugCorrVector=interpolateCorrectionVector ( //  vector of {corrX, corrY, alpha, flatfield_red, flatfield_green, flatfield_blue}
						chnNum,
						imgXY[i][0], //double px, measured
						imgXY[i][1]); //double py, measured);
			}
			double [] reprojectedNode= reprojectGridNode( //{pX,pY,grid mask (binary), grid R, grid G, grid B, alpha}
					lensDistortionParameters,
					imgNum,
					imgUV[i][0], //int u, // grid signed u,v
					imgUV[i][1]); //int v
			if (reprojectedNode==null) {
				continue; // out of grid - should not happen here (now - also: target point behind the camera sensor)?
			}
//			double [] reprojPXY={reprojectedNode[0],reprojectedNode[1]};
Andrey Filippov's avatar
Andrey Filippov committed
2636
			double [] nodePXY={this.Y[doublePairIndex],this.Y[doublePairIndex+1]};
Andrey Filippov's avatar
Andrey Filippov committed
2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649
			stagePXY[index]=nodePXY;// measured pixels Px,Py with correction applied  // reprojPXY;
//			double [] diffPXY= {imgXY[i][0]-corrVector[0]-reprojectedNode[0],imgXY[i][1]-debugCorrVector[1]-reprojectedNode[1]};
			double [] diffPXY= {diff[2*i],diff[2*i+1]};
			stageDiffPXY[index]=diffPXY;
			//{px,py,contrast,vignR,vignG,vignB}
			double [] diffRGB={0.0,0.0,0.0};
			for (int c=0;c<diffRGB.length;c++){
				double gridPhotometrics=photometrics[c][targetGridIndex];
//				if (gridPhotometrics>0.0) diffRGB[c]=imgXY[i][imgRGBIndex+c]/gridPhotometrics-debugCorrVector[corrRIndex+c];
				if (gridPhotometrics>0.0) diffRGB[c]=imgXY[i][imgRGBIndex+c]/gridPhotometrics; // don't use old correction at all!
			}
			stageDiffRGB[index]=diffRGB;
			stageMask[index]=this.weightFunction[2*(this.imageStartIndex[imgNum]+i)];
Andrey Filippov's avatar
Andrey Filippov committed
2650

Andrey Filippov's avatar
Andrey Filippov committed
2651 2652 2653 2654 2655 2656
			if (showIntermediate) for (int c=0;c<3;c++){
				debugRGB[4*c+0][index]=photometrics[c][targetGridIndex];
				debugRGB[4*c+1][index]=imgXY[i][imgRGBIndex+c];
				debugRGB[4*c+2][index]=debugCorrVector[corrRIndex+c];
				debugRGB[4*c+3][index]=imgXY[i][imgRGBIndex+c]/photometrics[c][targetGridIndex];
			}
Andrey Filippov's avatar
Andrey Filippov committed
2657

Andrey Filippov's avatar
Andrey Filippov committed
2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678
		}
		if (showIntermediate){
			double [][] debugData = new double [8][width*height];
			String [] dbgTitles={"rep-X","rep-Y","dX","dY","R","G","B","Weight"};//
			for (int i=0;i<debugData[0].length;i++){
				if (stagePXY[i]==null){
					for (int j=0;j<debugData.length;j++) {
						debugData[j][i]=Double.NaN; // 0.0?
					}
				} else {
					debugData[0][i]=stagePXY[i][0];
					debugData[1][i]=stagePXY[i][1];
					debugData[2][i]=  stageDiffPXY[i][0];
					debugData[3][i]=  stageDiffPXY[i][1];
					debugData[4][i]=  stageDiffRGB[i][0];
					debugData[5][i]=  stageDiffRGB[i][1];
					debugData[6][i]=  stageDiffRGB[i][2];
					debugData[7][i]=     stageMask[i];
				}

			}
2679
			ShowDoubleFloatArrays.showArrays(
Andrey Filippov's avatar
Andrey Filippov committed
2680 2681 2682 2683 2684 2685 2686
					debugData,
					width,
					height,
					true,
					"PRE_EXP-"+imgNum+"-"+chnNum,
					dbgTitles);
			String [] dbgTitles1={"R-tar","R-grid","R-corr","R-FF","G-tar","G-grid","G-corr","G-FF","B-tar","B-grid","B-corr","B-FF",};//
2687
			ShowDoubleFloatArrays.showArrays(
Andrey Filippov's avatar
Andrey Filippov committed
2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708
					debugRGB,
					width,
					height,
					true,
					"CORR-RGB-"+imgNum+"-"+chnNum,
					dbgTitles1);

		}
		CorrectionInNodes correctionInNodes=new CorrectionInNodes(
				imgNum,
				uv0[0],
				uv0[1],
				width,
				height,
				stagePXY,
				stageDiffPXY,
				stageDiffRGB,
				stageMask
				);
		return correctionInNodes;
	}
Andrey Filippov's avatar
Andrey Filippov committed
2709

Andrey Filippov's avatar
Andrey Filippov committed
2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736
	class CorrectionInNodes{
		public int numImg;
		public Rectangle uv0;
		public double [][] reprojPXY; //= new double [width*height][]; //reprojected {px,py}
		public double [][] diffPXY; //=   new double [width*height][]; // difference between corrected measured and reprojected (to add to correction)
		public double [][] diffRGB; //=   new double [width*height][]; // difference (measured RGB)/(grid RGB) and current correction RGB (pixel sensitivity RGB)
		public double []   mask;
//		public int stageMasksSensor=0, stageMasksTarget=1, stageMasksContrast=2;
		public CorrectionInNodes (
				int numImg,
				int u0,
				int v0,
				int width,
				int height,
				double [][] reprojPXY, //= new double [width*height][]; //reprojected {px,py}
				double [][] diffPXY, //=   new double [width*height][]; // difference between corrected measured and reprojected (to add to correction)
				double [][] diffRGB, //=   new double [width*height][]; // difference (measured RGB)/(grid RGB) and current correction RGB (pixel sensitivity RGB)
				double [] mask //=     new double [width*height][]; // {sensor mask, target mask, measured contrast}
		){
			this.numImg=numImg;
			this.uv0=new Rectangle(u0,v0,width,height);
			this.reprojPXY=reprojPXY; //= new double [width*height][]; //reprojected {px,py}
			this.diffPXY=diffPXY; //=   new double [width*height][]; // difference between corrected measured and reprojected (to add to correction)
			this.diffRGB=diffRGB; //=   new double [width*height][]; // difference (measured RGB)/(grid RGB) and current correction RGB (pixel sensitivity RGB)
			this.mask=mask; //=     new double [width*height][]; // {sensor mask, target mask, measured contrast}
		}

Andrey Filippov's avatar
Andrey Filippov committed
2737

Andrey Filippov's avatar
Andrey Filippov committed
2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758
		public void show(
				String title
				){
				double [][] debugData = new double [8][this.uv0.width*this.uv0.height];
				String [] dbgTitles={"rep-X","rep-Y","dX","dY","R","G","B","Weight"};
				for (int i=0;i<debugData[0].length;i++){
					if (this.reprojPXY[i]==null){
						for (int j=0;j<debugData.length;j++) {
							debugData[j][i]=Double.NaN; // 0.0?
						}
					} else {
						debugData[0][i]=this.reprojPXY[i][0];
						debugData[1][i]=this.reprojPXY[i][1];
						debugData[2][i]=  this.diffPXY[i][0];
						debugData[3][i]=  this.diffPXY[i][1];
						debugData[4][i]=  this.diffRGB[i][0];
						debugData[5][i]=  this.diffRGB[i][1];
						debugData[6][i]=  this.diffRGB[i][2];
						debugData[7][i]=     this.mask[i];
					}
				}
2759
				ShowDoubleFloatArrays.showArrays(
Andrey Filippov's avatar
Andrey Filippov committed
2760 2761 2762 2763 2764 2765 2766 2767 2768 2769
						debugData,
						this.uv0.width,
						this.uv0.height,
						true,
						title,
						dbgTitles);
		}
		/**
		 * Convert correction for grid nodes (detected and extrapolated) into decimated pixel array
		 * result should be added to the current (prior) correction. Use alpha as weight when accumulating for multiple images
Andrey Filippov's avatar
Andrey Filippov committed
2770
		 * @param decimation decimate correction pixels from sensor pixels
Andrey Filippov's avatar
Andrey Filippov committed
2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812
		 * @param sensorWidth sensor width in pixels (2592)
		 * @param sensorHeight sensor height in pixels (1936)
		 * @param debugLevel debug level (verbose if >3)
		 * @return scan-line pixels correction arrays {dpX,dpY,alpha,R,G,B}[pixelIndex]
		 */
		public double [][] mapToPixels(
				int decimation,
				int sensorWidth,
				int sensorHeight,
				int debugLevel){
			int debugThreshold=2;
			int sWidth= (sensorWidth-1)/decimation+1; // decimated width (648)
			int sHeight=(sensorHeight-1)/decimation+1; // decimated height (484)

			int [] uvInc={0,1,this.uv0.width,this.uv0.width+1}; // four corners as vu index
			int [][] cycles={ // counter-clockwise corners bounding the area  (only orthogonal sides?)
					{1,0,2},
					{2,3,1},
					{0,2,3},
					{3,1,0}};

			double [][] thisPCorr=  new double [6][sWidth*sHeight]; // calculate for a single (this) image, accumulate in the end
			int    []   thisCounted=new    int    [sWidth*sHeight]; // some pixels accumulated twice - divide in the end
			for (int n=0;n<thisPCorr.length;n++) for (int i=0;i<thisPCorr[0].length;i++) thisPCorr[n][i]=0.0;
			for (int i=0;i<thisCounted.length;i++) thisCounted[i]=0;

			// now use imgData array to fill thisPCorr by linear interpolation
			for (int v=0;v<(this.uv0.height-1); v++) for (int u=0; u<(this.uv0.width-1);u++){
				int vu=u+this.uv0.width*v;
                double [][] cornerXY =new double[4][];
                for (int i=0;i<uvInc.length;i++){
                	int vu1=vu+uvInc[i];
                	cornerXY[i]=null;
                	if (this.reprojPXY[vu1]!=null){
                		double w=this.mask[vu1];
                		if (w>0.0) {
                			cornerXY[i]=new double[2];
                			cornerXY[i][0]=this.reprojPXY[vu1][0];
                			cornerXY[i][1]=this.reprojPXY[vu1][1];
                		}
                	}
                }
Andrey Filippov's avatar
Andrey Filippov committed
2813
                boolean [] cycleFits=new boolean[cycles.length];
Andrey Filippov's avatar
Andrey Filippov committed
2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859
                boolean anyFits=false;
                for (int i=0;i<cycles.length;i++){
                	cycleFits[i]=true;
                	for (int j=0;j<cycles[i].length;j++) if (cornerXY[cycles[i][j]]==null) {
                		cycleFits[i]=false;
                		break;
                	}
                	anyFits |=cycleFits[i];
                }
                if (!anyFits) continue; // not a single cycle
				if (debugLevel>debugThreshold) {
					String debugString="cycleFits ";
					for (int i =0;i<cycleFits.length; i++) debugString+=" "+cycleFits[i];
					System.out.println(debugString);
				}
                if (cycleFits[0]&&cycleFits[1]){ // remove overlaps
                	cycleFits[2]=false;
                	cycleFits[3]=false;
                }
                boolean minMaxUndefined=true;
				double minX=0,maxX=0,minY=0,maxY=0;
				// find bounding rectangle;
				for (int nCycle=0;nCycle<cycles.length;nCycle++) if (cycleFits[nCycle]){
					int [] cycle=cycles[nCycle];
					for (int corner=0; corner<cycle.length;corner++){
						if (minMaxUndefined || (minX>cornerXY[cycle[corner]][0])) minX=cornerXY[cycle[corner]][0];
						if (minMaxUndefined || (maxX<cornerXY[cycle[corner]][0])) maxX=cornerXY[cycle[corner]][0];
						if (minMaxUndefined || (minY>cornerXY[cycle[corner]][1])) minY=cornerXY[cycle[corner]][1];
						if (minMaxUndefined || (maxY<cornerXY[cycle[corner]][1])) maxY=cornerXY[cycle[corner]][1];
						minMaxUndefined=false;
					}
				}
				int iMinX=(int) Math.floor(minX/decimation);
				int iMinY=(int) Math.floor(minY/decimation);
				int iMaxX=(int) Math.ceil(maxX/decimation);
				int iMaxY=(int) Math.ceil(maxY/decimation);
				// not sure if these checks are needed, got out of bounds wheriDy was =484=sHeight
				if (iMinX<0) iMinX=0;
				if (iMaxX>=sWidth) iMaxX=sWidth-1;
				if (iMinY<0) iMinY=0;
				if (iMaxY>=sHeight) iMaxY=sHeight-1;
				double [] originXY=new double [2];
				double [] endXY=new double [2];
				boolean debugHadPixels=false;
//TODO: scan X,Y in this rectangle, for points in defined squares/triangles find if the point is inside (accurate not to loose any).
				for (int idY=iMinY; idY<=iMaxY;idY++){
Andrey Filippov's avatar
Andrey Filippov committed
2860

Andrey Filippov's avatar
Andrey Filippov committed
2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888
					double pY=idY*decimation; // in sensor pixels
					for (int idX=iMinX; idX<=iMaxX;idX++){
						double pX=idX*decimation; // in sensor pixels
						// scan allowed triangles, usually 2
						for (int nCycle=0;nCycle<cycles.length;nCycle++) if (cycleFits[nCycle]){
							int [] cycle=cycles[nCycle];
							// is this point inside?
							boolean inside=true;
							for (int nEdge=0;nEdge<cycle.length;nEdge++){
								int nextNEdge=(nEdge==(cycle.length-1))?0:(nEdge+1);

								originXY[0]=this.reprojPXY[vu+uvInc[cycle[nEdge]]][0];     // imgData[2][vu+uvInc[cycle[nEdge]]];
								originXY[1]=this.reprojPXY[vu+uvInc[cycle[nEdge]]][1];     // imgData[3][vu+uvInc[cycle[nEdge]]];
								endXY[0]=   this.reprojPXY[vu+uvInc[cycle[nextNEdge]]][0]; // imgData[2][vu+uvInc[cycle[nextNEdge]]];
								endXY[1]=   this.reprojPXY[vu+uvInc[cycle[nextNEdge]]][1]; // imgData[3][vu+uvInc[cycle[nextNEdge]]];
								if (((pX-originXY[0])*(endXY[1]-originXY[1]) - (pY-originXY[1])*(endXY[0]-originXY[0]))<0.0){
									inside=false;
									break;
								}
							}
							if (!inside) continue; // point is outside of the interpolation area, try next triangle (if any)
							if (debugLevel>debugThreshold) {
								System.out.println("idX="+idX+" idY="+idY+" nCycle="+nCycle);
								String debugString1="cycle:";
								for (int i =0;i<cycle.length; i++) debugString1+=" "+cycle[i];
								System.out.println(debugString1);
							}

Andrey Filippov's avatar
Andrey Filippov committed
2889
							/* interpolate:
Andrey Filippov's avatar
Andrey Filippov committed
2890 2891 2892
							1. taking cycles[0] as origin and two (non co-linear) edge vectors - V1:from 0 to 1 and V2 from 1 to 2
							    find a1 and a2  so that vector V  (from 0  to pXY) = a1*V1+ a2*V2
							2. if F0 is the value of the interpolated function at cycles[0], F1 and F2 - at cycles[1] and cycles2
Andrey Filippov's avatar
Andrey Filippov committed
2893
							   then F=F0+(F1-F0)*a1 +(F2-F1)*a2
Andrey Filippov's avatar
Andrey Filippov committed
2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987
							 */
							double [] XY0={this.reprojPXY[vu+uvInc[cycle[0]]][0],this.reprojPXY[vu+uvInc[cycle[0]]][1]};
							double [] XY1={this.reprojPXY[vu+uvInc[cycle[1]]][0],this.reprojPXY[vu+uvInc[cycle[1]]][1]};
							double [] XY2={this.reprojPXY[vu+uvInc[cycle[2]]][0],this.reprojPXY[vu+uvInc[cycle[2]]][1]};
							double [] V= {pX-XY0[0],pY-XY0[1]};
							double [][] M={
									{XY1[0]-XY0[0],XY2[0]-XY1[0]},
									{XY1[1]-XY0[1],XY2[1]-XY1[1]}};
							double det=M[0][0]*M[1][1]-M[1][0]*M[0][1];
							double [][] MInverse={
									{ M[1][1]/det,-M[0][1]/det},
									{-M[1][0]/det, M[0][0]/det}};
							double [] a12={
									MInverse[0][0]*V[0]+MInverse[0][1]*V[1],
									MInverse[1][0]*V[0]+MInverse[1][1]*V[1]};
							int pCorrIndex=idY*sWidth+idX;
// some points may be accumulated multiple times - thisPCorr[3] will take care of this
							if (debugLevel>debugThreshold) {
								System.out.println("XY0="+IJ.d2s(XY0[0],3)+":"+IJ.d2s(XY0[1],3));
								System.out.println("XY1="+IJ.d2s(XY1[0],3)+":"+IJ.d2s(XY1[1],3));
								System.out.println("XY2="+IJ.d2s(XY2[0],3)+":"+IJ.d2s(XY2[1],3));
								System.out.println("M00="+IJ.d2s(M[0][0],3)+" M01="+IJ.d2s(M[0][1],3));
								System.out.println("M10="+IJ.d2s(M[1][0],3)+" M11="+IJ.d2s(M[1][1],3));
								System.out.println("MInverse00="+IJ.d2s(MInverse[0][0],5)+" MInverse01="+IJ.d2s(MInverse[0][1],5));
								System.out.println("MInverse10="+IJ.d2s(MInverse[1][0],5)+" MInverse11="+IJ.d2s(MInverse[1][1],5));
								System.out.println("a12="+IJ.d2s(a12[0],3)+":"+IJ.d2s(a12[1],3));
								System.out.println("this.diffPXY[vu+uvInc[cycle[0]]][0]="+IJ.d2s(this.diffPXY[vu+uvInc[cycle[0]]][0],3)+
										"this.diffPXY[vu+uvInc[cycle[0]]][1]="+IJ.d2s(this.diffPXY[vu+uvInc[cycle[0]]][1],3));
								System.out.println("this.diffPXY[vu+uvInc[cycle[1]]][0]="+IJ.d2s(this.diffPXY[vu+uvInc[cycle[1]]][0],3)+
										"this.diffPXY[vu+uvInc[cycle[1]]][1]="+IJ.d2s(this.diffPXY[vu+uvInc[cycle[1]]][1],3));
								System.out.println("this.diffPXY[vu+uvInc[cycle[2]]][0]="+IJ.d2s(this.diffPXY[vu+uvInc[cycle[2]]][0],3)+
										"this.diffPXY[vu+uvInc[cycle[2]]][1]="+IJ.d2s(this.diffPXY[vu+uvInc[cycle[2]]][1],3));
							}

							double [] corr={
									 this.diffPXY[vu+uvInc[cycle[0]]][0]+ // dPx
									(this.diffPXY[vu+uvInc[cycle[1]]][0]-this.diffPXY[vu+uvInc[cycle[0]]][0])*a12[0]+
									(this.diffPXY[vu+uvInc[cycle[2]]][0]-this.diffPXY[vu+uvInc[cycle[1]]][0])*a12[1],

									 this.diffPXY[vu+uvInc[cycle[0]]][1]+ // dPy
									(this.diffPXY[vu+uvInc[cycle[1]]][1]-this.diffPXY[vu+uvInc[cycle[0]]][1])*a12[0]+
									(this.diffPXY[vu+uvInc[cycle[2]]][1]-this.diffPXY[vu+uvInc[cycle[1]]][1])*a12[1],

									 this.mask[vu+uvInc[cycle[0]]]+ // alpha
									(this.mask[vu+uvInc[cycle[1]]]-this.mask[vu+uvInc[cycle[0]]])*a12[0]+
									(this.mask[vu+uvInc[cycle[2]]]-this.mask[vu+uvInc[cycle[1]]])*a12[1],

									 this.diffRGB[vu+uvInc[cycle[0]]][0]+ // Red measured/pattern
									(this.diffRGB[vu+uvInc[cycle[1]]][0]-this.diffRGB[vu+uvInc[cycle[0]]][0])*a12[0]+
									(this.diffRGB[vu+uvInc[cycle[2]]][0]-this.diffRGB[vu+uvInc[cycle[1]]][0])*a12[1],

									 this.diffRGB[vu+uvInc[cycle[0]]][1]+ // Red measured/pattern
									(this.diffRGB[vu+uvInc[cycle[1]]][1]-this.diffRGB[vu+uvInc[cycle[0]]][1])*a12[0]+
									(this.diffRGB[vu+uvInc[cycle[2]]][1]-this.diffRGB[vu+uvInc[cycle[1]]][1])*a12[1],

									 this.diffRGB[vu+uvInc[cycle[0]]][2]+ // Red measured/pattern
									(this.diffRGB[vu+uvInc[cycle[1]]][2]-this.diffRGB[vu+uvInc[cycle[0]]][2])*a12[0]+
									(this.diffRGB[vu+uvInc[cycle[2]]][2]-this.diffRGB[vu+uvInc[cycle[1]]][2])*a12[1]};
							if (debugLevel>debugThreshold) {
								System.out.println("corr="+IJ.d2s(corr[0],3)+" "+IJ.d2s(corr[1],3)+" "+IJ.d2s(corr[2],3));
							}
 if (pCorrIndex>thisPCorr[0].length) {
//	 System.out.println("imgNum=" + imgNum+": "+	fittingStrategy.distortionCalibrationData.gIP[imgNum].path);
	 System.out.println("thisPCorr[0].length="+thisPCorr[0].length+" pCorrIndex="+pCorrIndex+" sWidth="+sWidth+" idY="+idY+" idX="+idX);
 }
                            for (int i=0;i<corr.length;i++) {
                            	thisPCorr[i][pCorrIndex]+= corr[i]; // OOB: -8, -1433
                            }
							thisCounted[pCorrIndex]++;

							if (debugLevel>debugThreshold) {
								debugHadPixels=true;
							}
						}
					} // idX
					// use same order in calculations, make sure no gaps
				} // idY
				if ((debugLevel>debugThreshold) && (debugHadPixels)){
//					if (!debugExit) {
						System.out.println(
								" minX="+IJ.d2s(minX,1)+
								" maxX="+IJ.d2s(maxX,1));
						System.out.println(
								" minY="+IJ.d2s(minY,1)+
								" maxY="+IJ.d2s(maxY,1));
						System.out.println(
								" iMinX="+iMinX+
								" iMaxX="+iMaxX);
						System.out.println(
								" iMinY="+iMinY+
								" iMaxY="+iMaxY);
//					}
//					if (!debugExit) debugCntr--;
//					if (debugCntr==0) debugExit=true; // exit after first non-empty tile
Andrey Filippov's avatar
Andrey Filippov committed
2988

Andrey Filippov's avatar
Andrey Filippov committed
2989 2990 2991 2992 2993 2994 2995 2996
				}
			} //for (int v=0;v<(this.uv0.height-1); v++) for (int u=0; u<(this.uv0.width-1);u++){
            for (int i=0;i<thisCounted.length;i++) if (thisCounted[i]>1) {
            	for (int j=0;j<thisPCorr[i].length;j++)	thisPCorr[j][i]/= thisCounted[i];
            }
            return thisPCorr;
		}
	}
Andrey Filippov's avatar
Andrey Filippov committed
2997

Andrey Filippov's avatar
Andrey Filippov committed
2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028
	class DirInc{
		private int top=   1 | 2 | 4 | 8 | 16;
		private int bottom=1 |             16 | 32 | 64 | 128;
		private int left=  1 | 2 |                   64 | 128;
		private int right=         4 | 8 | 16 | 32 | 64;
		private int [] inc=null;
		private int [] validDirs=null;
		private double [][] unityVector=null;
		public int dirs=8;
		public DirInc(int width, int height){
//			int [] dirs8={1,1+width,width,-1+width,-1,-1-width,-width,1-width};
			int [][] incXY8={{1,0},{1,1},{0,1},{-1,1},{-1,0},{-1,-1},{0,-1},{1,-1}};
			this.inc=new int [incXY8.length];
			this.unityVector=new double [incXY8.length][2];
			for (int i=0;i<incXY8.length;i++){
				this.inc[i]=incXY8[i][0]+width*incXY8[i][1];
				double len=Math.sqrt(incXY8[i][0]*incXY8[i][0]+incXY8[i][1]*incXY8[i][1]);
				this.unityVector[i][0]=incXY8[i][0]/len;
				this.unityVector[i][1]=incXY8[i][1]/len;
			}
//			this.inc=dirs8;
			this.validDirs=new int [width*height];
			for (int i=0;i<this.validDirs.length;i++) this.validDirs[i]=0xff;
			for (int i=0;i<width;i++){
				this.validDirs[                 i]&=top;
				this.validDirs[(height-1)*width+i]&=bottom;
			}
			for (int i=0;i<height;i++){
				this.validDirs[i*width]&=left;
				this.validDirs[i*width + width-1]&=right;
			}
Andrey Filippov's avatar
Andrey Filippov committed
3029

Andrey Filippov's avatar
Andrey Filippov committed
3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046
		}
		public int newIndex(int oldIndex, int dir){
			if ((validDirs[oldIndex] & (1<<dir))==0) return -1; // invalid dir for this location (border)
			return oldIndex+this.inc[dir];
		}
		public double [] unity(int dir) {
			return this.unityVector[(dir+this.unityVector.length)%this.unityVector.length];
		}
	}

	public class PixXYUV{
		double [][]xy=null;
		int [][]uv=null;
		double [] alpha=null;
		double [][]dxy=null;
		public PixXYUV(){}
		public PixXYUV(int len){
Andrey Filippov's avatar
Andrey Filippov committed
3047 3048 3049 3050
			this.uv=new int [len][2];
			this.xy=new double [len][2];
			this.alpha=new double [len];
			this.dxy=new double [len][2];
Andrey Filippov's avatar
Andrey Filippov committed
3051 3052
		}
	}
Andrey Filippov's avatar
Andrey Filippov committed
3053 3054 3055 3056




Andrey Filippov's avatar
Andrey Filippov committed
3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071
	/**
	 * Interpolate (bi-linear) X/Y corrections and flat-field data for the sensor
	 * @param chnNum - sensor (channel) number
	 * @param px     - pixel X coordinate (non-decimated)
	 * @param py     - pixel Y coordinate (non-decimated)
	 * @return       - vector of {corrX, corrY, alpha, flatfield_red, flatfield_green, flatfield_blue}
	 */
	public double [] interpolateCorrectionVector (
			int chnNum,
			double px,
			double py){
		if (this.pixelCorrection==null){
			double [] vector={0.0,0.0,1.0,1.0,1.0,1.0};
			return vector;
		}
3072 3073 3074
//		this.pixelCorrectionDecimation=fittingStrategy.distortionCalibrationData.eyesisCameraParameters.decimateMasks;
//		this.pixelCorrectionWidth=   fittingStrategy.distortionCalibrationData.eyesisCameraParameters.sensorWidth;
//		this.pixelCorrectionHeight=  fittingStrategy.distortionCalibrationData.eyesisCameraParameters.sensorHeight;
Andrey Filippov's avatar
Andrey Filippov committed
3075

3076
		int sensorCorrWidth= getSensorCorrWidth(chnNum);
Andrey Filippov's avatar
Andrey Filippov committed
3077
		int sensorCorrHeight=this.pixelCorrection[chnNum][0].length/sensorCorrWidth;
3078 3079 3080

		int [] ix={(int) Math.floor(px/getDecimateMasks(chnNum)), (int) Math.floor(px/getDecimateMasks(chnNum))+1};
		int [] iy={(int) Math.floor(py/getDecimateMasks(chnNum)),(int) Math.floor(py/getDecimateMasks(chnNum))+1};
Andrey Filippov's avatar
Andrey Filippov committed
3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096
		for (int i=0;i<2;i++){
			if (ix[i]<0) ix[i]=0;
			else if (ix[i]>=sensorCorrWidth) ix[i]=sensorCorrWidth-1;
			if (iy[i]<0) iy[i]=0;
			else if (iy[i]>=sensorCorrHeight) iy[i]=sensorCorrHeight-1;
		}
		int index00=ix[0] + iy[0]*sensorCorrWidth;
		int indexX0=ix[1] + iy[0]*sensorCorrWidth;
		int index0Y=ix[0] + iy[1]*sensorCorrWidth;
		int indexXY=ix[1] + iy[1]*sensorCorrWidth;

		double corrDX=0,corrDY=0;
		if ((px>ix[0])&& (px<ix[1])) corrDX=px-ix[0];
		if ((py>iy[0])&& (py<iy[1])) corrDY=py-iy[0];
		double [] vector=new double [this.pixelCorrection[chnNum].length];
		for (int n=0;n<vector.length;n++){
Andrey Filippov's avatar
Andrey Filippov committed
3097
			// bilinear interpolation
Andrey Filippov's avatar
Andrey Filippov committed
3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113
			vector[n]=
				(1-corrDX)* (1-corrDY)* this.pixelCorrection[chnNum][n][index00]+
				corrDX * (1-corrDY)* this.pixelCorrection[chnNum][n][indexX0]+
				(1-corrDX)*    corrDY * this.pixelCorrection[chnNum][n][index0Y]+
				corrDX *    corrDY * this.pixelCorrection[chnNum][n][indexXY];
		}
		return vector;
	}
	/**
	 * Bilinear interpolate sensor mask array
	 * @param mask decimated mask data
	 * @param px     - pixel X coordinate (non-decimated)
	 * @param py     - pixel Y coordinate (non-decimated)
	 * @return interpolated mask data at specified fractional pixel
	 */
	public double interpolateMask (
3114
			int       chnNum,
Andrey Filippov's avatar
Andrey Filippov committed
3115 3116 3117
			double [] mask,
			double px,
			double py){
3118 3119 3120
///		this.pixelCorrectionDecimation=fittingStrategy.distortionCalibrationData.eyesisCameraParameters.decimateMasks;
///		this.pixelCorrectionWidth=   fittingStrategy.distortionCalibrationData.eyesisCameraParameters.sensorWidth;
///		this.pixelCorrectionHeight=  fittingStrategy.distortionCalibrationData.eyesisCameraParameters.sensorHeight;
Andrey Filippov's avatar
Andrey Filippov committed
3121

3122
		int sensorCorrWidth= getSensorCorrWidth(chnNum); // (this.pixelCorrectionWidth-1)/this.pixelCorrectionDecimation+1;
Andrey Filippov's avatar
Andrey Filippov committed
3123
		int sensorCorrHeight=mask.length/sensorCorrWidth;
3124 3125
		int [] ix={(int) Math.floor(px/getDecimateMasks(chnNum)), (int) Math.floor(px/getDecimateMasks(chnNum))+1};
		int [] iy={(int) Math.floor(py/getDecimateMasks(chnNum)), (int) Math.floor(py/getDecimateMasks(chnNum))+1};
Andrey Filippov's avatar
Andrey Filippov committed
3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146
		for (int i=0;i<2;i++){
			if (ix[i]<0) ix[i]=0;
			else if (ix[i]>=sensorCorrWidth) ix[i]=sensorCorrWidth-1;
			if (iy[i]<0) iy[i]=0;
			else if (iy[i]>=sensorCorrHeight) iy[i]=sensorCorrHeight-1;
		}
		int index00=ix[0] + iy[0]*sensorCorrWidth;
		int indexX0=ix[1] + iy[0]*sensorCorrWidth;
		int index0Y=ix[0] + iy[1]*sensorCorrWidth;
		int indexXY=ix[1] + iy[1]*sensorCorrWidth;

		double corrDX=0,corrDY=0;
		if ((px>ix[0])&& (px<ix[1])) corrDX=px-ix[0];
		if ((py>iy[0])&& (py<iy[1])) corrDY=py-iy[0];
		double result=
				(1-corrDX)* (1-corrDY)* mask[index00]+
				corrDX * (1-corrDY)* mask[indexX0]+
				(1-corrDX)*    corrDY * mask[index0Y]+
				corrDX *    corrDY * mask[indexXY];
		return result;
	}
Andrey Filippov's avatar
Andrey Filippov committed
3147 3148


Andrey Filippov's avatar
Andrey Filippov committed
3149
/**
Andrey Filippov's avatar
Andrey Filippov committed
3150
 *   after fitting finished and accepted - 	fittingStrategy.saveSeriesVector(double [] vector)
Andrey Filippov's avatar
Andrey Filippov committed
3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188
 */
	public void saveFittingSeries() {
		fittingStrategy.saveSeriesVector(this.currentVector);
	}
	/*
	 * For each image in the series:

    	public double [] fittingStrategy.getImageParametersVector(int numImg, double [] parameterVector);
    	 * Calculates current values of all parameters for the particular sensor - some ("fixed")
    	 * are taken from the data stored for this individual image, others - from the parameter
    	 * vector (used in fitting)
    	 * @param numImg number of image
    	 * @param vector parameters vector
    	 * @return vector used for the current image (parameters influencing the acquired grid
    	 * on the sensor (common parameters and those of the sensor's subchannel)

   public void calcInterParamers(
    		double [] parVect,
    		boolean [] mask, // calculate only selected derivatives (all parVect values are still
    		boolean calculateDerivatives // calculate this.interParameterDerivatives -derivatives array (false - just this.values)
    		){
     * Calculate/set  this.lensDistortionParameters and this.interParameterDerivatives
     * @param parVect 21-element vector for eyesis sub-camera, including common and individual parameters
     * @param mask -mask - which partial derivatives are needed to be calculated (others will be null)
     * @param calculateDerivatives calculate array of partial derivatives, if false - just the values


For each point in the image
      public double [][] lensDistortionParameters.reorderPartialDerivatives (double [][] srcDerivatives){
      double [][] lensDistortionParameters.calcPartialDerivatives(
        		double xp, // target point horizontal, positive - right,  mm
        		double yp, // target point vertical,   positive - down,  mm
        		double zp, // target point horizontal, positive - away from camera,  mm
        		boolean calculateAll){ // calculate derivatives, false - values only

    public double [][] interParameterDerivatives=null; //partial derivative matrix from subcamera-camera-goniometer to single camera (12x21)
    public double []   currentVector; // current variable parameter vector
    public double []   Y=null; // array of "y" - for each grid image, each defined grid node - 2 elements
Andrey Filippov's avatar
Andrey Filippov committed
3189
    public double [][] targetXYZ=null; // array of target {x,y,z} matching each image each grid point
Andrey Filippov's avatar
Andrey Filippov committed
3190 3191 3192
    public double []   fX=null; // array of "f(x)" - simulated data for all images, combining pixel-X and pixel-Y (odd/even)
    public double [][] jacobian=null; // partial derivatives of fX (above) by parameters to be adjusted (rows)
	 */
Andrey Filippov's avatar
Andrey Filippov committed
3193

Andrey Filippov's avatar
Andrey Filippov committed
3194 3195 3196 3197 3198
	public ImagePlus simulatePatternOnSensor(
			int stationNumber,
			int subCam,
			double goniometerTilt,
			double goniometerAxial,
3199
			double goniometerInterAxis,
Andrey Filippov's avatar
Andrey Filippov committed
3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210
			SimulationPattern.SimulParameters simulParametersDefault,
			int threadsMax,
			boolean updateStatus,
			int mspDebugLevel,
			int global_debug_level, // DEBUG_LEVEL
			int debug_level // debug level used inside loops
	){
		MatchSimulatedPattern matchSimulatedPattern = new MatchSimulatedPattern(64); // new instance, all reset, FFTSize=64 will not be used
		matchSimulatedPattern.debugLevel = mspDebugLevel;
		//		MatchSimulatedPattern.DistortionParameters distortionParameters = modifyDistortionParameters();
		//		SimulationPattern.SimulParameters simulParameters = modifySimulParameters();
3211 3212
		int sensorWidth=  getSensorWidth(subCam);
		int sensorHeight= getSensorHeight(subCam);
Andrey Filippov's avatar
Andrey Filippov committed
3213 3214 3215 3216 3217 3218

		double [][][] hintGrid=estimateGridOnSensor(
				stationNumber,
				subCam,
				goniometerTilt, // Tilt, goniometerHorizontal
				goniometerAxial,  // Axial,goniometerAxial
3219
				goniometerInterAxis, // inter-axis angle
3220 3221
				-1, // use camera parameters, not imageSet
				true // filter border
Andrey Filippov's avatar
Andrey Filippov committed
3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240
		);
		if (hintGrid==null){
			String msg="Grid is not visible for subcamera="+subCam+",  tilt="+goniometerTilt+", axial="+goniometerAxial;
			IJ.showMessage("Error",msg);
			System.out.println("Error: "+msg);
			return null;
		}
		if (global_debug_level>1){
			double [][] pixels=new double[4][hintGrid.length*hintGrid[0].length];
			int index=0;
			String [] titles={"pixel-X","pixel-Y","grid-U","grid-V"};
			for (int v=0; v<hintGrid.length;v++) for (int u=0;u<hintGrid[v].length;u++){
				if (hintGrid[v][u]!=null){
					for (int i=0; i<4;i++)	pixels[i][index]=hintGrid[v][u][i];
				} else {
					for (int i=0; i<4;i++)	pixels[i][index]=-1;
				}
				index++;
			}
3241
			ShowDoubleFloatArrays.showArrays(pixels, hintGrid[0].length, hintGrid.length,  true, "hintGrid", titles);
Andrey Filippov's avatar
Andrey Filippov committed
3242

Andrey Filippov's avatar
Andrey Filippov committed
3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280
		}

		if (global_debug_level>0){
			System.out.println("simulatePatternOnSensor(): subcamera="+subCam+",  tilt="+goniometerTilt+", axial="+goniometerAxial);
		}
		int numCells=matchSimulatedPattern.restoreSimulatedPatternGridFromHint(hintGrid, sensorWidth, sensorHeight);
		matchSimulatedPattern.recalculateWaveVectors (
				   updateStatus,
				   debug_level);// debug level used inside loops

		if (global_debug_level>0){
			System.out.println("simulatePatternOnSensor(): "+numCells+" grid cells");
		}
		SimulationPattern.SimulParameters simulParameters = simulParametersDefault.clone();
		SimulationPattern simulationPattern=new SimulationPattern(simulParameters);
		double [][] xy0={{simulParameters.offsetX,simulParameters.offsetY},{simulParameters.offsetX-0.5,simulParameters.offsetY-0.5}} ;
// TODO: add marks for the laser pointers when visible?
		float[] simPixels=simulationPattern.simulateGrid (
				matchSimulatedPattern.getDArray(),
				2, // gridFrac, // number of grid steps per pattern full period
				simulParameters,
				matchSimulatedPattern.getWOI(),
				1, // simulParameters.subdiv/2,
				xy0[0],    // add to patternGrid xy
				threadsMax,
				updateStatus,
				(debug_level>1)?1:0); //debug_level); // debug level
		if (global_debug_level>0){
			System.out.println("simulatePatternOnSensor(): simPixels.length="+simPixels.length+" sensorWidth="+sensorWidth+" sensorHeight="+sensorHeight);
		}
		for (int i=0;i<simPixels.length;i++) simPixels[i]*=255.0;
		ImageProcessor ip_simGrid = new FloatProcessor(sensorWidth, sensorHeight);
		ip_simGrid.setPixels(simPixels);
		ip_simGrid.resetMinAndMax();
		ImagePlus imp_simGrid= new ImagePlus("Simulated_Grid_CHN"+subCam+"_TILT"+goniometerTilt+"_AXIAL"+goniometerAxial, ip_simGrid);
		return imp_simGrid;
	}

Andrey Filippov's avatar
Andrey Filippov committed
3281
//TODO: add additional parameter - process all, but with matched pointers less than 2
Andrey Filippov's avatar
Andrey Filippov committed
3282
	public int applyHintedGrids(
3283
			LaserPointer laserPointer, // LaserPointer object that specifies actual laser pointers on the target
Andrey Filippov's avatar
Andrey Filippov committed
3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295
			boolean removeOutOfGridPointers,
			double  hintGridTolerance, // allowed mismatch (fraction of period) or 0 - orientation only
			boolean processAll, // if true - process all images, false - only disabled
			boolean ignoreLaserPointers, // ignore laser pointers, rely on hints only
			boolean processBlind, // try to match without known orientation and no laser pointers
			int     imageNumber, // <0 - all, >=0 only this image
			boolean useSetData,
			int threadsMax,
			boolean updateStatus,
			int mspDebugLevel,
			int global_debug_level, // DEBUG_LEVEL
			int debug_level // debug level used inside loops
3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332
	){
		return applyHintedGrids(
				laserPointer, // LaserPointer object that specifies actual laser pointers on the target
				removeOutOfGridPointers,
				hintGridTolerance, // allowed mismatch (fraction of period) or 0 - orientation only
				processAll, // if true - process all images, false - only disabled
				ignoreLaserPointers, // ignore laser pointers, rely on hints only
				processBlind, // try to match without known orientation and no laser pointers
				imageNumber, // <0 - all, >=0 only this image
				0, // int     start_set,
				this.fittingStrategy.distortionCalibrationData.getNumSets()-1, // int     end_set,
				useSetData,
				threadsMax,
				updateStatus,
				mspDebugLevel,
				global_debug_level, // DEBUG_LEVEL
				debug_level // debug level used inside loops
		);
	}


	public int applyHintedGrids(
			LaserPointer laserPointer, // LaserPointer object that specifies actual laser pointers on the target
			boolean removeOutOfGridPointers,
			double  hintGridTolerance, // allowed mismatch (fraction of period) or 0 - orientation only
			boolean processAll, // if true - process all images, false - only disabled
			boolean ignoreLaserPointers, // ignore laser pointers, rely on hints only
			boolean processBlind, // try to match without known orientation and no laser pointers
			int     imageNumber, // <0 - all, >=0 only this image
			int     start_set,
			int     end_set,
			boolean useSetData,
			int threadsMax,
			boolean updateStatus,
			int mspDebugLevel,
			int global_debug_level, // DEBUG_LEVEL
			int debug_level // debug level used inside loops
Andrey Filippov's avatar
Andrey Filippov committed
3333
	){
3334
		boolean invert = false;
Andrey Filippov's avatar
Andrey Filippov committed
3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356
		int debugThreshold0=0;
		int debugThreshold=2;
		MatchSimulatedPattern matchSimulatedPattern = new MatchSimulatedPattern(64); // new instance, all reset, FFTSize=64 will not be used
		// next 2 lines are not needed for the new instance, but can be
		// used alternatively if keeping it
		//		matchSimulatedPattern.invalidateFlatFieldForGrid(); // Reset Flat Filed calibration - different image.
		//		matchSimulatedPattern.invalidateFocusMask();
		matchSimulatedPattern.debugLevel = mspDebugLevel;
		//		ImagePlus imp_eq = matchSimulatedPattern.applyFlatField(images[nImg]); // current image with grid flat-field  correction

		//		if (debug_level > 0){
		//			System.out.println("\n   ======= Looking for grid, matching pointers in image " +images[nImg].getTitle()+
		//					", initial number of pointers was "+numPointers);
		//		}
		//matchSimulatedPatterns[numSensor].getChannel(images[numSensor])+" ");
		//		MatchSimulatedPattern.DistortionParameters distortionParameters = modifyDistortionParameters();
		//		SimulationPattern.SimulParameters simulParameters = modifySimulParameters();

		boolean noMessageBoxes=true;
		double [] xy0={0.0,0.0} ; //(old) debug only
		int numSuccess=0;
		DistortionCalibrationData dcd=fittingStrategy.distortionCalibrationData;
3357
		for (int numGridImage=0;numGridImage<dcd.gIP.length;numGridImage++) {
3358
			/*
3359 3360 3361 3362
			if (numGridImage >= 1680)	{
				System.out.println("Processing debug image "+numGridImage);
				System.out.println("Processing debug image "+numGridImage);
			}
3363 3364
			if ((set_number >= start_set) &&
					(set_number <= end_set) &&
3365
					(((imageNumber<0) || ((imageNumber==numGridImage)) && (processAll) ||
Andrey Filippov's avatar
Andrey Filippov committed
3366
					(!dcd.gIP[numGridImage].enabled &&
3367 3368 3369 3370 3371 3372 3373 3374 3375 3376
							((hintGridTolerance>0.0) ||
							 ((dcd.gIP[numGridImage].matchedPointers>0)) && !ignoreLaserPointers))))){ // skip no-pointers if only orientation is hinted
			*/
			int set_number = dcd.gIP[numGridImage].getSetNumber();
			if ((set_number >= start_set) && (set_number <= end_set) && // correct set range
					((imageNumber < 0) || (imageNumber==numGridImage)) && // either all images or selected image
					(processAll || !dcd.gIP[numGridImage].enabled) && // "process all" (including disabled) or this is disabled
					((hintGridTolerance > 0.0) || ((dcd.gIP[numGridImage].matchedPointers>0) && !ignoreLaserPointers)) // hint tolerance is provided, or there are lasers not disabled
					){ // skip no-pointers if only orientation is hinted
				
Andrey Filippov's avatar
Andrey Filippov committed
3377 3378 3379 3380 3381
				if (((dcd.gIP[numGridImage].matchedPointers==0) || ignoreLaserPointers)&&
						(dcd.gIS[dcd.get_gIS_index(numGridImage)].orientationEstimated)) {
					if ( !processBlind) {
						if (this.debugLevel>0) {
							System.out.println("\n**** Orientation is not known exactly for image # "+numGridImage+" - "+dcd.gIP[numGridImage].path+
3382
									", and there are no laser pointer references (processBlind==false) - skipping");
Andrey Filippov's avatar
Andrey Filippov committed
3383 3384 3385 3386 3387
						}
						continue;
					} else {
						if (this.debugLevel>0) {
							System.out.println("\n**** Orientation is not known exactly for image # "+numGridImage+" - "+dcd.gIP[numGridImage].path+
3388
									", and there are no laser pointer references, but processBlind is enabled, proceeding");
Andrey Filippov's avatar
Andrey Filippov committed
3389 3390 3391
						}
					}
				}
3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402
				if ((dcd.gIP[numGridImage].matchedPointers > 0) && !ignoreLaserPointers) { // just re-enable with the same shifts (will fail if pointers were just added, but it failed anyway) 
					if (!dcd.gIP[numGridImage].enabled) {
						if (this.debugLevel>0) {
							System.out.println("Re-enabling grid #"+numGridImage+" that has pointer(s) with the previously set UVShiftRot =={0,0,0}");
						}
						dcd.gIP[numGridImage].enabled = true;
						dcd.gIP[numGridImage].newEnabled = true;
					}
					continue;
				}
				
Andrey Filippov's avatar
Andrey Filippov committed
3403 3404 3405 3406
				if (this.debugLevel>debugThreshold0) {
					System.out.println("\n---- applyHintedGrids() image #"+numGridImage+" (imageNumber="+imageNumber+") "+
							" dcd.gIP["+numGridImage+"].pixelsXY.length="+dcd.gIP[numGridImage].pixelsXY.length+
							" dcd.gIP["+numGridImage+"].pixelsXY_extra.length="+dcd.gIP[numGridImage].pixelsXY_extra.length+
3407
							" grid period="+dcd.gIP[numGridImage].getGridPeriod()+
3408 3409
							" enabled="+dcd.gIP[numGridImage].enabled+
							" hintedMatch="+dcd.gIP[numGridImage].hintedMatch
Andrey Filippov's avatar
Andrey Filippov committed
3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425
							);
					if (this.debugLevel>(debugThreshold)){
						for (int i=0;i<dcd.gIP[numGridImage].pixelsXY.length;i++){
							System.out.println(i+": dcd.gIP["+numGridImage+"].pixelsXY={"+dcd.gIP[numGridImage].pixelsXY[i][0]+
									","+dcd.gIP[numGridImage].pixelsXY[i][1]+"}"+
									" uv={"+dcd.gIP[numGridImage].pixelsUV[i][0]+
									","+dcd.gIP[numGridImage].pixelsUV[i][1]+"}");
						}
						for (int i=0;i<dcd.gIP[numGridImage].pixelsXY_extra.length;i++){
							System.out.println(i+": dcd.gIP["+numGridImage+"].pixelsXY_extra={"+dcd.gIP[numGridImage].pixelsXY_extra[i][0]+
									","+dcd.gIP[numGridImage].pixelsXY_extra[i][1]+"}"+
									" uv={"+dcd.gIP[numGridImage].pixelsUV_extra[i][0]+
									","+dcd.gIP[numGridImage].pixelsUV_extra[i][1]+"}");
						}
					}
				}
Andrey Filippov's avatar
Andrey Filippov committed
3426

Andrey Filippov's avatar
Andrey Filippov committed
3427
				double [][][] pixelsXYSet={
3428 3429
						dcd.gIP[numGridImage].pixelsXY,
						dcd.gIP[numGridImage].pixelsXY_extra};
Andrey Filippov's avatar
Andrey Filippov committed
3430 3431 3432
				int   [][][] pixelsUVSet={
						dcd.gIP[numGridImage].pixelsUV,
						dcd.gIP[numGridImage].pixelsUV_extra};
3433
				// shifts pixelsUV to have minimal u,v of 0 (stores shift in this.minUV), sets PATTERN_GRID
Andrey Filippov's avatar
Andrey Filippov committed
3434
				matchSimulatedPattern.restorePatternGridFromGridList(
Andrey Filippov's avatar
Andrey Filippov committed
3435 3436 3437
						pixelsXYSet, //double [][] pixelsXY,
						pixelsUVSet, // int [][] pixelsUV,
						dcd.gIP[numGridImage].intensityRange
3438
						); // width and height will be calculated from maximal of pixelsXY
Andrey Filippov's avatar
Andrey Filippov committed
3439
				boolean OK=matchSimulatedPattern.createUV_INDEX( /// **** fails here
Andrey Filippov's avatar
Andrey Filippov committed
3440
						null, //imp, // or null - just to determine WOI (when getWOI matches image size)
Andrey Filippov's avatar
Andrey Filippov committed
3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455
						xy0, // add to patterGrid xy, null OK
						threadsMax,
						updateStatus,
						global_debug_level, // DEBUG_LEVEL
						debug_level); // debug level used inside loops
				if (!OK) {
					System.out.println("++++++ BUG: in applyHintedGrids() failed in createUV_INDEX()");
					continue;
				}
				double [] goniometerTiltAxial=dcd.getImagesetTiltAxial(numGridImage);
				if ((goniometerTiltAxial==null) || Double.isNaN(goniometerTiltAxial[0])  || Double.isNaN(goniometerTiltAxial[1])){
					if (this.debugLevel>0) {
						System.out.println("No goniometer orientation is available for image # "+numGridImage+" - "+dcd.gIP[numGridImage].path);
					}
				} else {
3456 3457 3458 3459
					if ((numGridImage >= 234) && (numGridImage< 245)) {
						System.out.println("debug numGridImage="+numGridImage);
						System.out.println();
					}
Andrey Filippov's avatar
Andrey Filippov committed
3460
					int station=dcd.getImageStation(numGridImage);
3461
					int setNumber=dcd.gIP[numGridImage].getSetNumber();
Andrey Filippov's avatar
Andrey Filippov committed
3462 3463 3464 3465 3466
					double [][][] hintGrid=estimateGridOnSensor(
							station, // station number
							dcd.gIP[numGridImage].channel,
							goniometerTiltAxial[0], // Tilt, goniometerHorizontal
							goniometerTiltAxial[1],  // Axial,goniometerAxial
3467
							goniometerTiltAxial[2],  // inter-axis angle
3468 3469
							setNumber, // -1 or specific image set
							true // filter border
3470
							);
Andrey Filippov's avatar
Andrey Filippov committed
3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483
					if (global_debug_level>0){
						System.out.println("\n**** applyHintedGrids(): processing grid image # "+numGridImage+", path="+dcd.gIP[numGridImage].path);
					}
					if (hintGrid==null){
						if (global_debug_level>0){
							System.out.println("estimateGridOnSensor() failed - skipping");
						}
						dcd.gIP[numGridImage].hintedMatch =0;
						continue;
					}
					int rslt= matchSimulatedPattern.combineGridCalibration(
							laserPointer, // LaserPointer object or null
							ignoreLaserPointers?null:dcd.gIP[numGridImage].laserPixelCoordinates, //pointersXY,
3484 3485 3486 3487 3488 3489
							removeOutOfGridPointers, //
							hintGrid, // predicted grid array (or null)
							hintGridTolerance, // allowed mismatch (fraction of period) or 0 - orientation only
							invert,
							global_debug_level, // DEBUG_LEVEL
							noMessageBoxes );
Andrey Filippov's avatar
Andrey Filippov committed
3490 3491 3492 3493 3494 3495
					if (global_debug_level>0){
						System.out.println("applyHintedGrids(): rslt="+rslt);
					}
					if (rslt<0) { // failed hinting
						dcd.gIP[numGridImage].hintedMatch =0;
					} else {
3496 3497 3498 3499
						// re-create pixelsXY, pixelsXY_extra, pixelsUV, pixelsUV_extra
						int size=0;
						int size_extra=0;
						/*	            		System.out.println("numGridImage="+numGridImage+" matchSimulatedPattern.getHeight()="+matchSimulatedPattern.getHeight()+
Andrey Filippov's avatar
Andrey Filippov committed
3500 3501 3502 3503 3504 3505 3506 3507
	            				" matchSimulatedPattern.getWidth()="+matchSimulatedPattern.getWidth()+
	            				" matchSimulatedPattern.targetUV is "+((matchSimulatedPattern.targetUV==null)?"null":"not null")+
	            				" matchSimulatedPattern.pixelsUV is "+((matchSimulatedPattern.pixelsUV==null)?"null":"not null")
	            				);
	            		System.out.println(
	            				" matchSimulatedPattern.targetUV[0] is "+((matchSimulatedPattern.targetUV[0]==null)?"null":"not null")+
	            				" matchSimulatedPattern.pixelsUV[0] is "+((matchSimulatedPattern.pixelsUV[0]==null)?"null":"not null")
	            				);*/
3508 3509
						for (int v=0;v<matchSimulatedPattern.getHeight();v++) for (int u=0;u<matchSimulatedPattern.getWidth();u++) {
							/*		            		System.out.println("v="+v+", u="+u);
Andrey Filippov's avatar
Andrey Filippov committed
3510 3511
		            		System.out.println(" matchSimulatedPattern.targetUV[v][u] is "+((matchSimulatedPattern.targetUV[v][u]==null)?"null":"not null"));
		            		System.out.println(" matchSimulatedPattern.pixelsUV[v][u] is "+((matchSimulatedPattern.pixelsUV[v][u]==null)?"null":"not null"));*/
3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540
							if ((matchSimulatedPattern.targetUV[v][u]!=null) && (matchSimulatedPattern.pXYUV [v][u]!=null)){

								if ((matchSimulatedPattern.targetUV[v][u]!=null) && (matchSimulatedPattern.pXYUV [v][u]!=null) &&
										(matchSimulatedPattern.pXYUV[v][u][0]>=0.0) || (matchSimulatedPattern.pXYUV[v][u][1]>=0.0)) { // disregard negative sensor pixels
									//				            		System.out.println(" matchSimulatedPattern.targetUV[v][u] is "+((matchSimulatedPattern.targetUV[v][u]==null)?"null":"not null"));
									//				            		System.out.println(" matchSimulatedPattern.targetUV[v][u][0]= "+matchSimulatedPattern.targetUV[v][u][0]);
									//				            		System.out.println(" matchSimulatedPattern.targetUV[v][u][1]= "+matchSimulatedPattern.targetUV[v][u][1]); //********
									//				            		System.out.println(" patternParameters is "+((patternParameters==null)?"null":"not null"));
									//				            		int tu=matchSimulatedPattern.targetUV[v][u][0];
									//				            		int tv=matchSimulatedPattern.targetUV[v][u][1];
									//
									if (patternParameters.getXYZM(matchSimulatedPattern.targetUV[v][u][0],matchSimulatedPattern.targetUV[v][u][1],false,station)!=null) {
										size++;
									} else {
										size_extra++;
									}
								}
							}
						}
						// Move to DCD?
						dcd.gIP[numGridImage].resetMask();
						dcd.gIP[numGridImage].pixelsXY=new double [size][6];
						dcd.gIP[numGridImage].pixelsUV=new int    [size][2];
						dcd.gIP[numGridImage].pixelsXY_extra=new double [size_extra][6];
						dcd.gIP[numGridImage].pixelsUV_extra=new int    [size_extra][2];
						int index=0;
						int index_extra=0;
						for (int v=0;v<matchSimulatedPattern.getHeight();v++) for (int u=0;u<matchSimulatedPattern.getWidth();u++) {
							/*		            		System.out.println("+ v="+v+", u="+u);
Andrey Filippov's avatar
Andrey Filippov committed
3541 3542
		            		System.out.println(" + matchSimulatedPattern.targetUV[v][u] is "+((matchSimulatedPattern.targetUV[v][u]==null)?"null":"not null"));
		            		System.out.println(" + matchSimulatedPattern.pixelsUV[v][u] is "+((matchSimulatedPattern.pixelsUV[v][u]==null)?"null":"not null"));*/
3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581
							if ((matchSimulatedPattern.targetUV[v][u]!=null) &&(matchSimulatedPattern.pXYUV[v][u]!=null) ) {
								//			            		System.out.println("++ v="+v+", u="+u+" index="+index+" ("+size+"), index_extra="+index_extra+" ("+size_extra+")");

								if ((matchSimulatedPattern.targetUV[v][u]!=null) &&(matchSimulatedPattern.pXYUV[v][u]!=null) &&
										(matchSimulatedPattern.pXYUV[v][u][0]>=0.0) || (matchSimulatedPattern.pXYUV[v][u][1]>=0.0)) { // disregard negative sensor pixels
									if (
											(v>=matchSimulatedPattern.gridContrastBrightness[0].length) ||
											(u>=matchSimulatedPattern.gridContrastBrightness[0][0].length)){
										System.out.println(
												" matchSimulatedPattern.gridContrastBrightness[0].length="+matchSimulatedPattern.gridContrastBrightness[0].length+
												" matchSimulatedPattern.gridContrastBrightness[0][0].length="+matchSimulatedPattern.gridContrastBrightness[0][0].length+
												" v="+v+" u="+u);
									}
								}
								// setting dcd.gIP[numGridImage].pixelsUV[index] with rotated/shifted
								if (patternParameters.getXYZM(matchSimulatedPattern.targetUV[v][u][0],matchSimulatedPattern.targetUV[v][u][1],false,station)!=null) {
									dcd.gIP[numGridImage].pixelsXY[index][0]=matchSimulatedPattern.pXYUV[v][u][0];
									dcd.gIP[numGridImage].pixelsXY[index][1]=matchSimulatedPattern.pXYUV[v][u][1];
									dcd.gIP[numGridImage].pixelsUV[index][0]=matchSimulatedPattern.targetUV[v][u][0];
									dcd.gIP[numGridImage].pixelsUV[index][1]=matchSimulatedPattern.targetUV[v][u][1];
									dcd.gIP[numGridImage].pixelsXY[index][2]=matchSimulatedPattern.gridContrastBrightness[0][v][u]; // grid contrast
									dcd.gIP[numGridImage].pixelsXY[index][3]=matchSimulatedPattern.gridContrastBrightness[1][v][u]/dcd.gIP[numGridImage].intensityRange[0]; // red
									dcd.gIP[numGridImage].pixelsXY[index][4]=matchSimulatedPattern.gridContrastBrightness[2][v][u]/dcd.gIP[numGridImage].intensityRange[1]; // green
									dcd.gIP[numGridImage].pixelsXY[index][5]=matchSimulatedPattern.gridContrastBrightness[3][v][u]/dcd.gIP[numGridImage].intensityRange[2]; // blue
									index++;
								} else {
									dcd.gIP[numGridImage].pixelsXY_extra[index_extra][0]=matchSimulatedPattern.pXYUV[v][u][0];
									dcd.gIP[numGridImage].pixelsXY_extra[index_extra][1]=matchSimulatedPattern.pXYUV[v][u][1];
									dcd.gIP[numGridImage].pixelsUV_extra[index_extra][0]=matchSimulatedPattern.targetUV[v][u][0];
									dcd.gIP[numGridImage].pixelsUV_extra[index_extra][1]=matchSimulatedPattern.targetUV[v][u][1];
									dcd.gIP[numGridImage].pixelsXY_extra[index_extra][2]=matchSimulatedPattern.gridContrastBrightness[0][v][u]; // grid contrast
									dcd.gIP[numGridImage].pixelsXY_extra[index_extra][3]=matchSimulatedPattern.gridContrastBrightness[1][v][u]/dcd.gIP[numGridImage].intensityRange[0]; // red
									dcd.gIP[numGridImage].pixelsXY_extra[index_extra][4]=matchSimulatedPattern.gridContrastBrightness[2][v][u]/dcd.gIP[numGridImage].intensityRange[1]; // green
									dcd.gIP[numGridImage].pixelsXY_extra[index_extra][5]=matchSimulatedPattern.gridContrastBrightness[3][v][u]/dcd.gIP[numGridImage].intensityRange[2]; // blue
									index_extra++;
								}
							}
						}
						dcd.gIP[numGridImage].hintedMatch =(hintGridTolerance>0.0)?2:1; // orientation or both orientation and translation
Andrey Filippov's avatar
Andrey Filippov committed
3582 3583
						dcd.gIP[numGridImage].matchedPointers=rslt; // update number of matched pointers
						if ((dcd.gIP[numGridImage].hintedMatch>1) || (dcd.gIP[numGridImage].matchedPointers>0)) numSuccess++;
3584 3585 3586 3587
						// Update rotation/shift
						//matchSimulatedPattern
						int [] fileUVShiftRot=dcd.gIP[numGridImage].getUVShiftRot();
						int [] extraUVShiftRot=matchSimulatedPattern.getUVShiftRot(true); // last shift/rotation during matching pattern, correct for zero shift
3588
						//						int [] extraDbg=matchSimulatedPattern.getUVShiftRot(false);
3589
						int [] combinedUVShiftRot=MatchSimulatedPattern.combineUVShiftRot(fileUVShiftRot,extraUVShiftRot);
3590
						dcd.gIP[numGridImage].setUVShiftRot(combinedUVShiftRot);
Andrey Filippov's avatar
Andrey Filippov committed
3591 3592
						System.out.println("applyHintedGrids(): dcd.gIP["+numGridImage+"].hintedMatch="+dcd.gIP[numGridImage].hintedMatch+
								" dcd.gIP["+numGridImage+"].matchedPointers="+dcd.gIP[numGridImage].matchedPointers+ " points:"+index+" extra points:"+index_extra);
3593 3594 3595 3596 3597
						// testing rot/shift:
						String nonzero=((extraUVShiftRot[0]==0)&&(extraUVShiftRot[1]==0)&&(extraUVShiftRot[2]==0))?" ":"*";
						System.out.println("applyHintedGrids(): fileUVShiftRot=    "+fileUVShiftRot[0]+"/"+fileUVShiftRot[1]+":"+fileUVShiftRot[2]);
						System.out.println("                   "+nonzero+"extraUVShiftRot=   "+extraUVShiftRot[0]+"/"+extraUVShiftRot[1]+":"+extraUVShiftRot[2]);
						System.out.println("                    combinedUVShiftRot="+combinedUVShiftRot[0]+"/"+combinedUVShiftRot[1]+":"+combinedUVShiftRot[2]);
3598
						//						System.out.println("                    extraDbg="+extraDbg[0]+"/"+extraDbg[1]+":"+extraDbg[2]);
Andrey Filippov's avatar
Andrey Filippov committed
3599 3600 3601
					}
				}
			}
3602
		}
Andrey Filippov's avatar
Andrey Filippov committed
3603 3604
		return numSuccess;
	}
3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615
	public void showSourceImage(int numGridImage){
		String source_path=fittingStrategy.distortionCalibrationData.gIP[numGridImage].source_path;
		if (source_path != null) {
			ImagePlus imp = new ImagePlus(source_path);
			imp.show();
		}
	}

	public int [][] getImageMarkers(int numGridImage){
		String source_path=fittingStrategy.distortionCalibrationData.gIP[numGridImage].source_path;
		if (source_path != null) {
3616
			ImagePlus imp = new ImagePlus(source_path);
3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641
			imp.show();
			/*
			Thread msg_box_thread  = new Thread() {
   				@Override
				public void run() {
   					IJ.showMessage("Please place point markers on the "+imp.getTitle());
   				}
   			};
   			msg_box_thread.setPriority(Thread.MIN_PRIORITY);
   			msg_box_thread.start();
   			try {
   				msg_box_thread.join();
   			} catch (InterruptedException ie) {
   				throw new RuntimeException(ie);
   			}
	*/


//			IJ.showMessage("Please place point markers on the "+imp.getTitle());
			System.out.println("got it");
			PointRoi pointRoi = null;

			if (imp.getRoi() instanceof PointRoi) {
				pointRoi =  (PointRoi) imp.getRoi();
			} else {
Andrey Filippov's avatar
Andrey Filippov committed
3642
				System.out.println("This image does not have point marks - please mark it in "+source_path);
3643 3644
				IJ.showMessage("This image does not have point marks - please mark it in "+source_path);
				return null;
3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663
				/*
				
				boolean mark_and_continue = IJ.showMessageWithCancel("Mark and Continue", "This image does not have point marks - please mark it in "+source_path);
				
				if (mark_and_continue) {
					imp = new ImagePlus(source_path);
					System.out.println("got it again!");
					pointRoi = null;
					if (imp.getRoi() instanceof PointRoi) {
						pointRoi =  (PointRoi) imp.getRoi();
					} else {
						System.out.println("This image does not have point marks - please mark it in "+source_path);
						IJ.showMessage("This image does not have point marks - please mark it in "+source_path);
						return null;
					}
				} else {
					return null;
				}
				*/
3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675
			}
			Point [] points = pointRoi.getContainedPoints();
			int [][] ipoints = new int [points.length][2];
			for (int n = 0; n < ipoints.length; n++) {
				ipoints[n][0] = points[n].x;
				ipoints[n][1] = points[n].y;
			}
			return ipoints;
		}
		return null;
	}

Andrey Filippov's avatar
Andrey Filippov committed
3676

Andrey Filippov's avatar
Andrey Filippov committed
3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742
	public void showGridImage(int numGridImage){
		DistortionCalibrationData.GridImageParameters grid=fittingStrategy.distortionCalibrationData.gIP[numGridImage];
		boolean valid=false;
		int minU=0,maxU=0,minV=0,maxV=0;
		for (int i=0;i<grid.pixelsUV.length;i++){
			if (!valid){
				minU=grid.pixelsUV[i][0];
				minV=grid.pixelsUV[i][1];
				maxU=minU;
				maxV=minV;
				valid=true;
			} else {
				if (minU>grid.pixelsUV[i][0]) minU=grid.pixelsUV[i][0];
				if (minV>grid.pixelsUV[i][1]) minV=grid.pixelsUV[i][1];
				if (maxU<grid.pixelsUV[i][0]) maxU=grid.pixelsUV[i][0];
				if (maxV<grid.pixelsUV[i][1]) maxV=grid.pixelsUV[i][1];
			}
		}
		for (int i=0;i<grid.pixelsUV_extra.length;i++){
			if (!valid){
				minU=grid.pixelsUV_extra[i][0];
				minV=grid.pixelsUV_extra[i][1];
				maxU=minU;
				maxV=minV;
				valid=true;
			} else {
				if (minU>grid.pixelsUV_extra[i][0]) minU=grid.pixelsUV_extra[i][0];
				if (minV>grid.pixelsUV_extra[i][1]) minV=grid.pixelsUV_extra[i][1];
				if (maxU<grid.pixelsUV_extra[i][0]) maxU=grid.pixelsUV_extra[i][0];
				if (maxV<grid.pixelsUV_extra[i][1]) maxV=grid.pixelsUV_extra[i][1];
			}
		}
		String [] titles={"X","Y","U","V","valid","extra"};
		int height=maxV-minV+1;
		int width= maxU-minU+1;
//		System.out.println("showGridImage(): minU="+minU+" maxU="+maxU+" minV="+minV+" maxV="+maxV+" width="+width+" height="+height);
//		System.out.println("showGridImage(): grid.pixelsXY.length="+grid.pixelsXY.length+" grid.pixelsXY.length="+grid.pixelsXY.length);
		double [][] pixels=new double [titles.length][width*height];
		for (int i=0;i<pixels[0].length;i++) {
			pixels[0][i]=-1.0; // x
			pixels[1][i]=-1.0; // y
			pixels[2][i]= 0.0; // u
			pixels[3][i]= 0.0; // v
			pixels[4][i]=-1000.0; // valid
			pixels[5][i]=-1000.0; // extra
		}
		for (int i=0;i<grid.pixelsUV.length;i++){
			int u=grid.pixelsUV[i][0]-minU;
			int v=grid.pixelsUV[i][1]-minV;
			int index=u+width*v;
			pixels[0][index]=grid.pixelsXY[i][0];
			pixels[1][index]=grid.pixelsXY[i][1];
			pixels[2][index]=grid.pixelsUV[i][0];
			pixels[3][index]=grid.pixelsUV[i][1];
			pixels[4][index]=1000.0;
		}
		for (int i=0;i<grid.pixelsUV_extra.length;i++){
			int u=grid.pixelsUV_extra[i][0]-minU;
			int v=grid.pixelsUV_extra[i][1]-minV;
			int index=u+width*v;
			pixels[0][index]=grid.pixelsXY_extra[i][0];
			pixels[1][index]=grid.pixelsXY_extra[i][1];
			pixels[2][index]=grid.pixelsUV_extra[i][0];
			pixels[3][index]=grid.pixelsUV_extra[i][1];
			pixels[4][index]=1000.0;
		}
3743
		ShowDoubleFloatArrays.showArrays(pixels, width, height,  true, "grid-"+numGridImage, titles);
Andrey Filippov's avatar
Andrey Filippov committed
3744
	}
3745 3746 3747 3748 3749 3750



	public void manualGridHint(int imgNumber) {
		int [][] markers = getImageMarkers(imgNumber);
		if ((markers != null) && (markers.length > 0)) {
3751 3752 3753 3754 3755
			if (markers.length > 1) {
				System.out.println("This image has multiple point marks - please remove extra");
				IJ.showMessage("This image has multiple point marks - please remove extra");
				return;
			}
3756 3757
			double [][] xyuv = new double [markers.length][4];
			for (int i =0; i < markers.length; i++) {
3758 3759 3760 3761
				xyuv[i][0] = markers[i][0];
				xyuv[i][1] = markers[i][1];
				xyuv[i][2] = lastUsedManualGridHint_UV[0]; // 16.5; // 15.5; // 0.5;
				xyuv[i][3] = lastUsedManualGridHint_UV[1]; //  0.5; // -8.5;//0.5;
3762 3763
			}
			GenericDialog gd=new GenericDialog("Specify U,V coordinates of the marker(s)");
Andrey Filippov's avatar
Andrey Filippov committed
3764
			gd.addMessage("Center white (LWIR black) cell U=0.5, V=0.5");
3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776
			for (int n = 0; n < markers.length; n++) {
				String label = "Marker "+(n+1)+" (x="+markers[n][0]+", y="+markers[n][1];
				gd.addNumericField(label+" U", xyuv[n][2], 1, 5, "");
				gd.addNumericField(label+" V", xyuv[n][3], 1, 5, "");
			}
			gd.showDialog();
			if (gd.wasCanceled()) return;
			for (int i =0; i < markers.length; i++) {
				xyuv[i][2] = gd.getNextNumber();
				xyuv[i][3] = gd.getNextNumber();
			}

3777 3778 3779 3780
		    lastUsedManualGridHint_UV[0] = xyuv[0][2];
		    lastUsedManualGridHint_UV[1] = xyuv[0][3];
			
			
3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822
			// read grid image

			String grid_path=fittingStrategy.distortionCalibrationData.gIP[imgNumber].path;
			if (grid_path != null) {
				ImagePlus imp = new ImagePlus(grid_path);
				JP46_Reader_camera jp4_instance= new JP46_Reader_camera(false);
				jp4_instance.decodeProperiesFromInfo(imp);
				MatchSimulatedPattern.setPointersXYUV(imp, xyuv);
				updateGridToPointer(imp, xyuv);
				jp4_instance.encodeProperiesToInfo(imp);
				System.out.println("Updated "+grid_path);
				(new FileSaver(imp)).saveAsTiff(grid_path);
//				imp.show();
			}
			return;
		}
	}
	public void updateGridToPointer(ImagePlus imp_grid, double[][] xyuv) {
		ImageStack stack=imp_grid.getStack();
		if ((stack==null) || (stack.getSize()<4)) {
			String msg="Expected a 8-slice stack in "+imp_grid.getTitle();
			IJ.showMessage("Error",msg);
			throw new IllegalArgumentException (msg);
		}
		float [][] pixels=new float[stack.getSize()][]; // now - 8 (x,y,u,v,contrast, vignR,vignG,vignB
		for (int i=0;i<pixels.length;i++) pixels[i]= (float[]) stack.getPixels(i+1); // pixel X : negative - no grid here
		int width = imp_grid.getWidth();
		int height = imp_grid.getHeight();
		// start with translation only using xyuv[0][], may use full matching - same as laser pointers later
		int    indx_best = -1;
		double d2_best = Double.NaN;
		for (int indx = 0; indx < pixels[0].length; indx++) {
			double dx = pixels[0][indx] - xyuv[0][0];
			double dy = pixels[1][indx] - xyuv[0][1] ;
			double d2 = dx*dx + dy*dy;
			if (Double.isNaN(d2_best) || (d2 < d2_best)) {
				indx_best = indx;
				d2_best = d2;
			}
		}
		int ix0 = indx_best % width;
		int iy0 = indx_best / width;
3823
		int half_range = 2; // was 1;
3824
		PolynomialApproximation polynomialApproximation =new PolynomialApproximation(0);// no debug
3825 3826
//		double [][][] data = new double[9][3][];
		double [][][] data = new double[(2*half_range+1)*(2*half_range+1)][3][];
3827
		int indx = 0;
3828
		for (int idy = -half_range; idy <=half_range; idy++) {
3829
			int iy = iy0+idy;
3830
			for (int idx = -half_range; idx <= half_range; idx++) {
3831 3832 3833 3834 3835 3836
				int ix = ix0 + idx;
				data[indx][0] = new double[2];
				data[indx][1] = new double[2];
				data[indx][2] = new double[1];
				data[indx][0][0] = idx;
				data[indx][0][1] = idy;
3837
				data[indx][2][0] = 0.0;
3838 3839
				if ((ix >= 0) && (ix < width) && (iy >= 0) && (iy < height)) {
					int offs = iy * width + ix;
3840 3841 3842 3843 3844
					if ((pixels[0][offs] >= 0) && (pixels[1][offs] >= 0)) {
						data[indx][1][0] = pixels[0][offs] - xyuv[0][0];
						data[indx][1][1] = pixels[1][offs] - xyuv[0][1];
						data[indx][2][0] = 1.0;
					}
3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891
				}
				indx++;
			}
		}
		double [][] coeff = polynomialApproximation.quadraticApproximation(
				data,
				true); // force linear
		double [][] aA = {{coeff[0][0],coeff[0][1]},{coeff[1][0],coeff[1][1]}};
		double [][] aB = {{-coeff[0][2]},{-coeff[1][2]}};
		Matrix A = new Matrix(aA);
		Matrix B = new Matrix(aB);
		Matrix V = A.solve(B);
		double [] av = V.getColumnPackedCopy();
		double u, v; //  = xyuv[0][2]-()
		if (av[0] < 0) {
			av[0] += 1.0;
			ix0 -= 1;
		}
		if (av[1] < 0) {
			av[1] += 1.0;
			iy0 -= 1;
		}
		u = xyuv[0][2] - (
				(1-av[0])*(1-av[1]) * pixels[2][(iy0 + 0) * width + ix0 + 0]+
				(  av[0])*(1-av[1]) * pixels[2][(iy0 + 0) * width + ix0 + 1]+
				(1-av[0])*(  av[1]) * pixels[2][(iy0 + 1) * width + ix0 + 0]+
				(  av[0])*(  av[1]) * pixels[2][(iy0 + 1) * width + ix0 + 1]);
		v = xyuv[0][3] - (
				(1-av[0])*(1-av[1]) * pixels[3][(iy0 + 0) * width + ix0 + 0]+
				(  av[0])*(1-av[1]) * pixels[3][(iy0 + 0) * width + ix0 + 1]+
				(1-av[0])*(  av[1]) * pixels[3][(iy0 + 1) * width + ix0 + 0]+
				(  av[0])*(  av[1]) * pixels[3][(iy0 + 1) * width + ix0 + 1]);
		int idu = (int)Math.round(u);
		int idv = (int)Math.round(v);
		// Verify that idy+idv - even number
		if (((idu + idv) & 1) != 0) {
			String msg = "Incorrect shift - u="+u+", v="+v+", idu="+idu+", idv="+idv+", idu+idv="+(idu+idv)+" SHOULD BE EVEN!";
			System.out.println(msg);
			IJ.showMessage(msg);
		}

		for (int i = 0; i < pixels[2].length; i++) {
			pixels[2][i] += idu;
			pixels[3][i] += idv;
		}
	}

Andrey Filippov's avatar
Andrey Filippov committed
3892 3893 3894
	public void showGridAndHint(){
		GenericDialog gd=new GenericDialog("Show selected grid and/or hint grid");
		gd.addNumericField("Grid Image index", 0,0);
3895
		gd.addCheckbox("Show source image (if available)", true);
Andrey Filippov's avatar
Andrey Filippov committed
3896 3897 3898 3899 3900 3901 3902 3903
		gd.addCheckbox("Show grid image", true);
		gd.addCheckbox("Show hint grid", true);
		gd.addCheckbox("Use imageSet data if available (unchecked - camera data)", true);

		gd.showDialog();
		if (gd.wasCanceled()) return;
		int numGridImage= (int) gd.getNextNumber();
		boolean showGrid=gd.getNextBoolean();
3904
		boolean showSource=gd.getNextBoolean();
Andrey Filippov's avatar
Andrey Filippov committed
3905 3906 3907 3908
		boolean showHint=gd.getNextBoolean();
		boolean useSetData=gd.getNextBoolean();
		IJ.showStatus("grid: "+((fittingStrategy.distortionCalibrationData.gIP[numGridImage].path==null)?"":fittingStrategy.distortionCalibrationData.gIP[numGridImage].path));
//		showStatus("grid: "+((fittingStrategy.distortionCalibrationData.gIP[numGridImage].path==null)?"":fittingStrategy.distortionCalibrationData.gIP[numGridImage].path),0);
Andrey Filippov's avatar
Andrey Filippov committed
3909 3910

        if (showGrid)	showGridImage(numGridImage);
3911 3912
        if (showSource)	showSourceImage(numGridImage);
//        if (showSource)	getImageMarkers(numGridImage);
Andrey Filippov's avatar
Andrey Filippov committed
3913
        if (showHint)	calcAndShowHintGrid(numGridImage,useSetData);
Andrey Filippov's avatar
Andrey Filippov committed
3914 3915
	}

Andrey Filippov's avatar
Andrey Filippov committed
3916 3917


Andrey Filippov's avatar
Andrey Filippov committed
3918 3919 3920 3921 3922 3923 3924
	public void calcAndShowHintGrid(int numGridImage, boolean useSetData){
		double [] goniometerTiltAxial=fittingStrategy.distortionCalibrationData.getImagesetTiltAxial(numGridImage);
		if ((goniometerTiltAxial==null) || Double.isNaN(goniometerTiltAxial[0])  || Double.isNaN(goniometerTiltAxial[1])){
			if (this.debugLevel>0)System.out.println("No goniometer orientation is available for image # "+numGridImage+" - "+fittingStrategy.distortionCalibrationData.gIP[numGridImage].path);
			GenericDialog gd=new GenericDialog("Specify camera orientation (channel"+fittingStrategy.distortionCalibrationData.gIP[numGridImage].channel+")");
			gd.addMessage("No goniometer orientation is available for image # "+numGridImage+" - "+fittingStrategy.distortionCalibrationData.gIP[numGridImage].path+
			", please specify orientation manually");
3925 3926 3927
			gd.addNumericField("Camera tilt (0 - vertical, >0 looking above horizon on the target)", 0.0, 1,6,"degrees");
			gd.addNumericField("Camera axial (0 - subcamera 0 looking to the target, >0 - rotated clockwise)", 0.0, 1,6,"degrees");
			gd.addNumericField("Camera inter-axis angle (from 90) ", 0.0, 1,6,"degrees");
Andrey Filippov's avatar
Andrey Filippov committed
3928 3929
			gd.showDialog();
			if (gd.wasCanceled()) return;
3930 3931
			goniometerTiltAxial=new double[3];
			goniometerTiltAxial[0]=      gd.getNextNumber();
Andrey Filippov's avatar
Andrey Filippov committed
3932
			goniometerTiltAxial[1]=      gd.getNextNumber();
3933
			goniometerTiltAxial[2]=      gd.getNextNumber();
Andrey Filippov's avatar
Andrey Filippov committed
3934 3935 3936 3937 3938 3939
		}
		double [][][] hintGrid=estimateGridOnSensor(
				fittingStrategy.distortionCalibrationData.getImageStation(numGridImage), // station number
				fittingStrategy.distortionCalibrationData.gIP[numGridImage].channel,
				goniometerTiltAxial[0], // Tilt, goniometerHorizontal
				goniometerTiltAxial[1],  // Axial,goniometerAxial
3940
				goniometerTiltAxial[2],  // inter-axis angle
3941
				(useSetData?fittingStrategy.distortionCalibrationData.gIP[numGridImage].getSetNumber():-1),
3942 3943
				true // filter border
				);
3944 3945 3946 3947 3948 3949
		if (hintGrid == null) {
			String msg = "hintGrid is null";
			IJ.showMessage("Error",msg);
			System.out.println(msg);
			return;
		}
Andrey Filippov's avatar
Andrey Filippov committed
3950 3951 3952 3953 3954 3955
		showHintGrid(hintGrid,"hint-"+numGridImage);

	}
	public void showHintGrid(double [][][] hintGrid){
		showHintGrid(hintGrid,"hintGrid");
	}
Andrey Filippov's avatar
Andrey Filippov committed
3956

Andrey Filippov's avatar
Andrey Filippov committed
3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968
	public void showHintGrid(double [][][] hintGrid, String title){
		double [][] pixels=new double[4][hintGrid.length*hintGrid[0].length];
		int index=0;
		String [] titles={"pixel-X","pixel-Y","grid-U","grid-V"};
		for (int v=0; v<hintGrid.length;v++) for (int u=0;u<hintGrid[v].length;u++){
			if (hintGrid[v][u]!=null){
				for (int i=0; i<4;i++)	pixels[i][index]=hintGrid[v][u][i];
			} else {
				for (int i=0; i<4;i++)	pixels[i][index]=0;
			}
			index++;
		}
3969
		ShowDoubleFloatArrays.showArrays(pixels, hintGrid[0].length, hintGrid.length,  true, title, titles);
Andrey Filippov's avatar
Andrey Filippov committed
3970
	}
Andrey Filippov's avatar
Andrey Filippov committed
3971

Andrey Filippov's avatar
Andrey Filippov committed
3972 3973 3974
	/**
	 * Calculate grid on sensor using current camera parameters (including goniometer angles), sub-camera number
	 * @param subCamera
Andrey Filippov's avatar
Andrey Filippov committed
3975
	 * @return grid array [v][u][0- x,  1 - y, 2 - u, 3 - v]
Andrey Filippov's avatar
Andrey Filippov committed
3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988
	 */
	/*
	 // wrong, orientation depends on timestamp
	public double [][][] estimateGridOnSensor(
			int subCamera){
		double [] parVector=fittingStrategy.distortionCalibrationData.eyesisCameraParameters.getParametersVector(subCamera);
		return estimateGridOnSensor(
				subCamera,
				parVector[fittingStrategy.distortionCalibrationData.eyesisCameraParameters.getGoniometerHorizontalIndex()],
				parVector[fittingStrategy.distortionCalibrationData.eyesisCameraParameters.getGoniometerAxialIndex()]);
	}
	*/

Andrey Filippov's avatar
Andrey Filippov committed
3989

Andrey Filippov's avatar
Andrey Filippov committed
3990 3991 3992
	public LensDistortionParameters setupLensDistortionParameters(
			int numImg,
			int debugLevel){     // Axial - may be Double.NaN
Andrey Filippov's avatar
Andrey Filippov committed
3993

Andrey Filippov's avatar
Andrey Filippov committed
3994
		LensDistortionParameters lensDistortionParameters = new LensDistortionParameters (
3995 3996 3997 3998
				this.fittingStrategy.distortionCalibrationData.isTripod(),
				this.fittingStrategy.distortionCalibrationData.isCartesian(),
	    		this.fittingStrategy.distortionCalibrationData.getPixelSize(numImg),
	    		this.fittingStrategy.distortionCalibrationData.getDistortionRadius(numImg),
Andrey Filippov's avatar
Andrey Filippov committed
3999 4000 4001 4002 4003 4004 4005
	            null, //double [][] interParameterDerivatives, //partial derivative matrix from subcamera-camera-goniometer to single camera (12x21) if null - just values, no derivatives
	            this.fittingStrategy.distortionCalibrationData.getParameters(numImg), //parVector,
	    		null, //boolean [] mask, // calculate only selected derivatives (all parVect values are still
	    		debugLevel
				);
		return lensDistortionParameters;
	}
Andrey Filippov's avatar
Andrey Filippov committed
4006

Andrey Filippov's avatar
Andrey Filippov committed
4007 4008 4009
	public LensDistortionParameters setupLensDistortionParameters(
			int stationNumber,
			int subCamera,
Andrey Filippov's avatar
Andrey Filippov committed
4010
			double goniometerHorizontal, // Tilt - may be Double.NaN
Andrey Filippov's avatar
Andrey Filippov committed
4011 4012 4013 4014 4015 4016 4017 4018
			double goniometerAxial,
			int debugLevel){     // Axial - may be Double.NaN
		double [] parVector=fittingStrategy.distortionCalibrationData.eyesisCameraParameters.getParametersVector(stationNumber,subCamera);
		int goniometerHorizontalIndex=fittingStrategy.distortionCalibrationData.eyesisCameraParameters.getGoniometerHorizontalIndex();
		int goniometerAxialIndex=fittingStrategy.distortionCalibrationData.eyesisCameraParameters.getGoniometerAxialIndex();
		if (!Double.isNaN(goniometerHorizontal))parVector[goniometerHorizontalIndex]=goniometerHorizontal;
		if (!Double.isNaN(goniometerAxial))parVector[goniometerAxialIndex]=goniometerAxial;
		LensDistortionParameters lensDistortionParameters = new LensDistortionParameters (
4019 4020 4021 4022
				this.fittingStrategy.distortionCalibrationData.isTripod(),
				this.fittingStrategy.distortionCalibrationData.isCartesian(),
	    		this.fittingStrategy.distortionCalibrationData.getPixelSize(stationNumber, subCamera),
	    		this.fittingStrategy.distortionCalibrationData.getDistortionRadius(stationNumber, subCamera),
Andrey Filippov's avatar
Andrey Filippov committed
4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042
	            null, //double [][] interParameterDerivatives, //partial derivative matrix from subcamera-camera-goniometer to single camera (12x21) if null - just values, no derivatives
	    		parVector,
	    		null, //boolean [] mask, // calculate only selected derivatives (all parVect values are still
	    		debugLevel
				);
		return lensDistortionParameters;
	}

	/**
	 * Calculate grid projection to pixel X, Y (not counting sensor correction (add?) and grid photometrics
	 * @param lensDistortionParameters LensDistortionParameters instance created for particular image with setupLensDistortionParameters()
	 * @param numImg image number
	 * @param u grid U (signed, 0 in the center)
	 * @param v grid V (signed, 0 in the center)
	 * @return [7] {pX,pY,grid mask (binary), grid R, grid G, grid B, alpha}
	 */
	public double [] reprojectGridNode(
			LensDistortionParameters lensDistortionParameters,
			int numImg,
			int u, // grid signed u,v
4043
			int v){
4044 4045 4046 4047 4048 4049 4050 4051

		
		int subCamera=   this.fittingStrategy.distortionCalibrationData.gIP[numImg].channel;
		int sensorWidth=fittingStrategy.distortionCalibrationData.eyesisCameraParameters.getSensorWidth(subCamera);
		int sensorHeight=fittingStrategy.distortionCalibrationData.eyesisCameraParameters.getSensorHeight(subCamera);
//		double maxRelativeRadius=this.hintedMaxRelativeRadius; // make adjustable
		double maxRelativeRadius=hintedMaxRelativeRadiusToDiagonal * Math.sqrt(sensorWidth * sensorWidth + sensorHeight*sensorHeight)/ sensorWidth;
		
4052 4053 4054 4055 4056 4057
		return  reprojectGridNode(
				lensDistortionParameters,
				numImg,
				u, // grid signed u,v
				v,
		       	maxRelativeRadius);
Andrey Filippov's avatar
Andrey Filippov committed
4058
	}
4059 4060 4061 4062 4063 4064
	public double [] reprojectGridNode(
			LensDistortionParameters lensDistortionParameters,
			int numImg,
			int u, // grid signed u,v
			int v,
	       	double maxRelativeRadius //=2.0;
Andrey Filippov's avatar
Andrey Filippov committed
4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078
	){
		int debugThreshold=1;
		int nChn=   this.fittingStrategy.distortionCalibrationData.gIP[numImg].channel;
		int station=this.fittingStrategy.distortionCalibrationData.gIP[numImg].getStationNumber();
//		if (!lensDistortionParameters.isTargetVisible(false)) return null; // camera is looking away from the target (does not mean target is in FOV)
//		double [][][] patternGeometry=this.patternParameters.getGeometry(); // [v][u]{x,y,z,alpha} - no photometric
		double [] result= new double[7];
			double [] XYZMP=this.patternParameters.getXYZMP( // null pointer
					u,
					v,
					station,
					nChn,
					false);
			if (XYZMP==null) return null;
Andrey Filippov's avatar
Andrey Filippov committed
4079
			// project the target point to this sensor
Andrey Filippov's avatar
Andrey Filippov committed
4080 4081 4082 4083
			double [][]pXY=  lensDistortionParameters.calcPartialDerivatives(
					XYZMP[0], // target point horizontal, positive - right,  mm
					XYZMP[1], // target point vertical,   positive - down,  mm
					XYZMP[2], // target point horizontal, positive - away from camera,  mm
4084
					maxRelativeRadius, //
Andrey Filippov's avatar
Andrey Filippov committed
4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099
					false); // calculate derivatives, false - values only (NaN for behind points - only when false here)
			if (Double.isNaN(pXY[0][0])) {
				if (this.debugLevel>debugThreshold){
					System.out.println("reprojectGridNode(...,"+numImg+","+u+","+"v"+") - point behind the sensor");
				}
				return null; // point behind camera
			}
			result[0]=pXY[0][0];
			result[1]=pXY[0][1];
			result[2]=XYZMP[3]; // binary mask
			result[3]=XYZMP[4]; // R
			result[4]=XYZMP[5]; // G
			result[5]=XYZMP[6]; // B
			result[6]=XYZMP[7]; // alpha
// get photometrics here
Andrey Filippov's avatar
Andrey Filippov committed
4100

Andrey Filippov's avatar
Andrey Filippov committed
4101
		return result;
4102
	}
Andrey Filippov's avatar
Andrey Filippov committed
4103

4104
	/**
Andrey Filippov's avatar
Andrey Filippov committed
4105 4106
	 * Apply sensor correction to the projected grid (generated by estimateGridOnSensor())
	 * @param gridOnSensor array [v][u][0- x,  1 - y, 2 - targetAbsolute-u, 3 - targetAbsolute-v]
4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119
	 * @param subCamera channel number
	 * @return true if the correction was applied (in-place) false if no correction is available
	 */
	public boolean correctGridOnSensor(
			double [][][] gridOnSensor,
			int subCamera){
		if (this.pixelCorrection==null) return false;
		for (double [][] row:gridOnSensor) for (double [] cell:row) if ((cell!=null) && (cell.length>1)){
			double [] corrXYARGB=interpolateCorrectionVector ( // vector of {corrX, corrY, alpha, flatfield_red, flatfield_green, flatfield_blue}
					subCamera, //int chnNum,
					cell[0], //double px,
					cell[1]); //double py)
			cell[0]+=corrXYARGB[0]; // measured-> corrected : subtract, projected->simulated:add;
4120
			cell[1]+=corrXYARGB[1]+0.0; // Debugging by adding +1.0!!
4121
		}
4122
//		System.out.println("================== Added +0.0 to pixel y for debugging purposes! =====================");
4123
		return true;
Andrey Filippov's avatar
Andrey Filippov committed
4124
	}
Andrey Filippov's avatar
Andrey Filippov committed
4125

Andrey Filippov's avatar
Andrey Filippov committed
4126 4127 4128 4129 4130 4131 4132
	/**
	 * Calculate grid on sensor using current Camera parameters, sub-camera number and the two goniometer angles
	 * @param stationNumber
	 * @param subCamera
	 * @param goniometerHorizontal
	 * @param goniometerAxial
	 * @param imageSet - if >=0 - use this set number data  instead of the camera data)
Andrey Filippov's avatar
Andrey Filippov committed
4133
	 * @return grid array [v][u][0- x,  1 - y, 2 - u, 3 - v]
Andrey Filippov's avatar
Andrey Filippov committed
4134
	 */
Andrey Filippov's avatar
Andrey Filippov committed
4135

Andrey Filippov's avatar
Andrey Filippov committed
4136 4137 4138 4139
	// TODO:calcInterParamers() -> lensDistortionParameters.lensCalcInterParamers
	public double [][][] estimateGridOnSensor( // not yet thread safe
			int stationNumber,
			int subCamera,
Andrey Filippov's avatar
Andrey Filippov committed
4140
			double goniometerHorizontal, // Tilt
Andrey Filippov's avatar
Andrey Filippov committed
4141
			double goniometerAxial,     // Axial
4142
			double goniometerInterAxis,     // interAxisAngle
4143 4144
			int  imageSet,
			boolean filterBorder){
4145 4146 4147 4148 4149 4150
		int sensorWidth=fittingStrategy.distortionCalibrationData.eyesisCameraParameters.getSensorWidth(subCamera);
		int sensorHeight=fittingStrategy.distortionCalibrationData.eyesisCameraParameters.getSensorHeight(subCamera);
//		double maxRelativeRadius=this.hintedMaxRelativeRadius; // make adjustable
		double maxRelativeRadius=hintedMaxRelativeRadiusToDiagonal * Math.sqrt(sensorWidth * sensorWidth + sensorHeight*sensorHeight)/ sensorWidth;
		// 1.1 is sufficient
//		double maxRelativeRadius= 2.0*Math.sqrt(sensorWidth * sensorWidth + sensorHeight*sensorHeight)/ sensorWidth;
Andrey Filippov's avatar
Andrey Filippov committed
4151
		int debugThreshold=2;
Andrey Filippov's avatar
Andrey Filippov committed
4152
		// Get parameter vector (22) for the selected sensor, current Eyesisparameters and specified orientation angles
Andrey Filippov's avatar
Andrey Filippov committed
4153 4154 4155 4156 4157 4158
		double [] parVector=fittingStrategy.distortionCalibrationData.eyesisCameraParameters.getParametersVector(stationNumber,subCamera);
		if ((imageSet>=0) &&
				(this.fittingStrategy.distortionCalibrationData.gIS!=null) &&
				(this.fittingStrategy.distortionCalibrationData.gIS[imageSet]!=null)){
			this.fittingStrategy.distortionCalibrationData.gIS[imageSet].updateParameterVectorFromSet(parVector);
		}
4159 4160 4161 4162 4163 4164 4165 4166
		if (!Double.isNaN(goniometerHorizontal)) {
			int goniometerHorizontalIndex=fittingStrategy.distortionCalibrationData.eyesisCameraParameters.getGoniometerHorizontalIndex();
			parVector[goniometerHorizontalIndex]=goniometerHorizontal;
		}
		if (!Double.isNaN(goniometerAxial)) {
			int goniometerAxialIndex=fittingStrategy.distortionCalibrationData.eyesisCameraParameters.getGoniometerAxialIndex();
			parVector[goniometerAxialIndex]=     goniometerAxial;
		}
4167 4168 4169 4170 4171
		if (!Double.isNaN(goniometerInterAxis)) {
			int goniometerInterAxisAngleIndex=fittingStrategy.distortionCalibrationData.eyesisCameraParameters.getInterAxisAngleIndex();
			parVector[goniometerInterAxisAngleIndex]=  goniometerInterAxis;
		}
//		/interAxis
Andrey Filippov's avatar
Andrey Filippov committed
4172
		System.out.println("estimateGridOnSensor(): subCamera="+subCamera+", goniometerHorizontal="+goniometerHorizontal+", goniometerAxial="+goniometerAxial);
Andrey Filippov's avatar
Andrey Filippov committed
4173 4174
		this.lensDistortionParameters.lensCalcInterParamers(
				this.lensDistortionParameters, // 22-long parameter vector for the image
4175 4176 4177 4178
				this.fittingStrategy.distortionCalibrationData.isTripod(),
				this.fittingStrategy.distortionCalibrationData.isCartesian(),
	    		this.fittingStrategy.distortionCalibrationData.getPixelSize(stationNumber, subCamera),
	    		this.fittingStrategy.distortionCalibrationData.getDistortionRadius(stationNumber, subCamera),
Andrey Filippov's avatar
Andrey Filippov committed
4179 4180 4181
				null, // this.interParameterDerivatives, // [22][]
				parVector,
				null); // if no derivatives, null is OK
Andrey Filippov's avatar
Andrey Filippov committed
4182 4183


Andrey Filippov's avatar
Andrey Filippov committed
4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198
		if (!lensDistortionParameters.isTargetVisible(this.debugLevel>0)) {
			if (this.debugLevel>debugThreshold) System.out.println("Camera is looking away from the target");
//			return null; // camera is looking away from the target (does not mean target is in FOV)
		}
		double [][][] patternGeometry=this.patternParameters.getGeometry(); // [v][u]{x,y,z,alpha} - no photometric
		double [][][] result= new double[patternGeometry.length][patternGeometry[0].length][4];
		int visibleCells=0;
		double [][] debugPixels=null;
		String [] debugTitles={"pX","pY","X","Y","Z","mask"};
		if (this.debugLevel>debugThreshold){
			debugPixels=new double [6][patternGeometry.length*patternGeometry[0].length];
			for (int c=0;c<debugPixels.length;c++) for (int i=0;i<debugPixels[c].length;i++) debugPixels[c][i]=Double.NaN;
		}
		// was bug cased by +/- infinity (and sometimes numbers falling into the sensor range) when the image plane intersected target
		// simple fix - remove pixels with too few neighbors (maybe just all border pixels?
Andrey Filippov's avatar
Andrey Filippov committed
4199 4200


4201 4202 4203 4204
		for (int v=0;v<result.length;v++) {
			for (int u=0;u<result[v].length;u++){
				int [] iUV=this.patternParameters.uvIndicesToUV (u, v);
				if (iUV==null) {
Andrey Filippov's avatar
Andrey Filippov committed
4205 4206
					result[v][u]=null;
				} else {
4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231
					double [] XYZM=this.patternParameters.getXYZM(iUV[0],iUV[1],stationNumber);
					// project the target point to this sensor
					double [][]pXY=  this.lensDistortionParameters.calcPartialDerivatives(
							XYZM[0], // target point horizontal, positive - right,  mm
							XYZM[1], // target point vertical,   positive - down,  mm
							XYZM[2], // target point horizontal, positive - away from camera,  mm
							maxRelativeRadius,
							false); // calculate derivatives, false - values only (NaN for behind points - only when false here)
					// verify the grid is inside the sensor area (may use sensor mask later too? probably not needed)
					// Now NaN if point is behind the sensor
					if (Double.isNaN(pXY[0][0]) || (pXY[0][0]<0) || (pXY[0][0]>=sensorWidth) || (pXY[0][1]<0) || (pXY[0][1]>=sensorHeight)){
						if (this.debugLevel>debugThreshold){
							System.out.println("--- estimateGridOnSensor():v="+v+" u="+u+" X="+XYZM[0]+" Y="+XYZM[1]+" Z="+XYZM[2]+" M="+XYZM[3]+
									" pXY[0][0]="+pXY[0][0]+", pXY[0][1]="+pXY[0][1]+", iUV[0]="+iUV[0]+", iUV[1]="+iUV[1]);
						}
						result[v][u]=null;
					} else {
						double [] resultCell={pXY[0][0],pXY[0][1],iUV[0],iUV[1]};
						result[v][u]=resultCell;
						if (this.debugLevel>debugThreshold){
							System.out.println("+++ estimateGridOnSensor():v="+v+" u="+u+" X="+XYZM[0]+" Y="+XYZM[1]+" Z="+XYZM[2]+" M="+XYZM[3]+
									" pXY[0][0]="+pXY[0][0]+", pXY[0][1]="+pXY[0][1]+", iUV[0]="+iUV[0]+", iUV[1]="+iUV[1]);
						}
						visibleCells++;
					}
Andrey Filippov's avatar
Andrey Filippov committed
4232
					if (this.debugLevel>debugThreshold){
4233 4234 4235 4236 4237 4238
						int uv=u+v*result[v].length;
						debugPixels[0][uv]=pXY[0][0];
						debugPixels[1][uv]=pXY[0][1];
						debugPixels[2][uv]=XYZM[0];
						debugPixels[3][uv]=XYZM[1];
						debugPixels[4][uv]=XYZM[2];
Andrey Filippov's avatar
Andrey Filippov committed
4239 4240 4241 4242
					}
				}
			}
		}
4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257
		if (filterBorder){
			// now filter border nodes
			boolean [] mask= new boolean [patternGeometry.length*patternGeometry[0].length];
			int index=0;
			for (int v=0;v<result.length;v++) for (int u=0;u<result[v].length;u++){
				mask [index++]=(result[v][u]!=null) &&
						((v==0) || (result[v-1][u]!=null)) &&
						((v==(result.length-1)) || (result[v+1][u]!=null)) &&
						((u==0) || (result[v][u-1]!=null))&&
						((u==(result[v].length-1)) || (result[v][u+1]!=null));
			}
			index=0;
			for (int v=0;v<result.length;v++) for (int u=0;u<result[v].length;u++){
				if (!mask[index++]) result[v][u]=null;
			}
Andrey Filippov's avatar
Andrey Filippov committed
4258 4259 4260 4261 4262 4263
		}
		if (this.debugLevel>debugThreshold){
			for (int v=0;v<result.length;v++) for (int u=0;u<result[v].length;u++){
				int uv=u+v*result[v].length;
				debugPixels[5][uv]=(result[v][u]!=null)?3000:-3000; // masked
			}
4264
			ShowDoubleFloatArrays.showArrays(
Andrey Filippov's avatar
Andrey Filippov committed
4265 4266 4267 4268 4269 4270
					debugPixels,
					result[0].length,
					result.length,
					true,
					"Hinted-All",
					debugTitles);
Andrey Filippov's avatar
Andrey Filippov committed
4271
		}
4272
		if (this.debugLevel>0) {
Andrey Filippov's avatar
Andrey Filippov committed
4273 4274 4275 4276 4277 4278
			System.out.println("Grid in the FOV of the subcamera "+subCamera+
					" tilt="+goniometerHorizontal+" axial="+goniometerAxial+" has "+visibleCells+" cells");
		}
		if (visibleCells==0) return null; // no grid cells in FOV
		return result;
	}
Andrey Filippov's avatar
Andrey Filippov committed
4279

Andrey Filippov's avatar
Andrey Filippov committed
4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295
    public void debugCompareInterparameterDerivatives(
    		double [] vector,
    		int imgNum,
    		double delta){
		if (this.debugLevel>1) {
			System.out.println("debugCompareInterparameterDerivatives(vector, imgNum="+imgNum+", delta="+delta+")");
			for (int ii=0;ii<vector.length;ii++) System.out.println(ii+": "+vector[ii]);
		}
		int numImg=fittingStrategy.distortionCalibrationData.getNumImages();
		if (imgNum<0){ // find first selected image
			boolean [] selectedImages=fittingStrategy.selectedImages();
			imgNum=0;
			while ((imgNum<numImg) && (!selectedImages[imgNum])) imgNum++;
		}
		if (imgNum>=numImg){
			IJ.showMessage("No images found for this fitting strategy");
Andrey Filippov's avatar
Andrey Filippov committed
4296
			return; // no images found
Andrey Filippov's avatar
Andrey Filippov committed
4297 4298 4299 4300
		}
		double [] imgVector=fittingStrategy.getImageParametersVector(imgNum, vector); //this.currentVector);
		boolean [] imgMask= new boolean[imgVector.length];
		for (int i=0;i<imgMask.length;i++) imgMask[i]=true;
Andrey Filippov's avatar
Andrey Filippov committed
4301
		this.lensDistortionParameters.lensCalcInterParamers(
Andrey Filippov's avatar
Andrey Filippov committed
4302
				this.lensDistortionParameters,
4303 4304 4305 4306
				this.fittingStrategy.distortionCalibrationData.isTripod(),
				this.fittingStrategy.distortionCalibrationData.isCartesian(),
	    		this.fittingStrategy.distortionCalibrationData.getPixelSize(imgNum),
	    		this.fittingStrategy.distortionCalibrationData.getDistortionRadius(imgNum),
Andrey Filippov's avatar
Andrey Filippov committed
4307 4308 4309 4310 4311 4312 4313
				this.interParameterDerivatives, // [22][]
				imgVector,
				imgMask); // calculate only selected derivatives (all parVect values are still
//				true); // calculate this.interParameterDerivatives -derivatives array (false - just this.values)
// reorder derivatives to match lensDistortionParameters.getExtrinsicVector(); (dist,x0,y0,yaw,pitch,roll)
//					double [] parameterVector0=lensDistortionParameters.getAllVector();
		double [] values=lensDistortionParameters.getExtrinsicVector();
4314 4315
		double [][] derivatives_true = new double [this.lensDistortionParameters.getNumInputs()][6];
		for (int i=0;i<this.lensDistortionParameters.getNumInputs();i++){
Andrey Filippov's avatar
Andrey Filippov committed
4316 4317 4318 4319 4320 4321 4322
			derivatives_true[i][0]=this.interParameterDerivatives[i][2]; // d distance /d vector[i]
			derivatives_true[i][1]=this.interParameterDerivatives[i][0]; // d x0 /d vector[i]
			derivatives_true[i][2]=this.interParameterDerivatives[i][1]; // d y0 /d vector[i]
			derivatives_true[i][3]=this.interParameterDerivatives[i][3]; // d jaw /d vector[i]
			derivatives_true[i][4]=this.interParameterDerivatives[i][4]; // d pitch /d vector[i]
			derivatives_true[i][5]=this.interParameterDerivatives[i][5]; // d roll /d vector[i]
		}
4323 4324
		double [][] derivatives_delta = new double [this.lensDistortionParameters.getNumInputs()][values.length];
		for (int i=0;i<this.lensDistortionParameters.getNumInputs();i++){
Andrey Filippov's avatar
Andrey Filippov committed
4325 4326
			double [] vector_delta=imgVector.clone();
			vector_delta[i]+=delta;
Andrey Filippov's avatar
Andrey Filippov committed
4327
			this.lensDistortionParameters.lensCalcInterParamers(
Andrey Filippov's avatar
Andrey Filippov committed
4328
					this.lensDistortionParameters,
4329 4330 4331 4332
					this.fittingStrategy.distortionCalibrationData.isTripod(),
					this.fittingStrategy.distortionCalibrationData.isCartesian(),
		    		this.fittingStrategy.distortionCalibrationData.getPixelSize(imgNum),
		    		this.fittingStrategy.distortionCalibrationData.getDistortionRadius(imgNum),
Andrey Filippov's avatar
Andrey Filippov committed
4333
					null, // this.interParameterDerivatives, // just values, no derivatives
Andrey Filippov's avatar
Andrey Filippov committed
4334
					vector_delta,
Andrey Filippov's avatar
Andrey Filippov committed
4335 4336 4337
					imgMask);
//					false); // just values, no derivatives
			double [] values_delta=lensDistortionParameters.getExtrinsicVector();
Andrey Filippov's avatar
Andrey Filippov committed
4338 4339
			for (int j=0;j<derivatives_delta[i].length;j++) derivatives_delta[i][j]=(values_delta[j]-values[j])/delta;
		}
Andrey Filippov's avatar
Andrey Filippov committed
4340 4341 4342 4343
		String [] lensParNames = lensDistortionParameters.getExtrinsicNames();
	    String header="#\tphysical/lens\t ";
	    for (int i=0;i<lensParNames.length;i++)header+="\t"+lensParNames[i];
	    StringBuffer sb = new StringBuffer();
4344
	    for (int parNum=0;parNum<this.lensDistortionParameters.getNumInputs();parNum++){
4345
	    	sb.append(parNum+"\t"+fittingStrategy.distortionCalibrationData.descrField(parNum,0)+"\tderivative");
Andrey Filippov's avatar
Andrey Filippov committed
4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361
	    	for (int i=0;i<lensParNames.length;i++) sb.append("\t"+derivatives_true[parNum][i]);
	    	sb.append("\n");
	    	sb.append("\t \tdelta");
	    	for (int i=0;i<lensParNames.length;i++) sb.append("\t"+derivatives_delta[parNum][i]);
	    	sb.append("\n");
	    	sb.append("\t \tdifference");
	    	for (int i=0;i<lensParNames.length;i++) sb.append("\t"+(derivatives_true[parNum][i]-derivatives_delta[parNum][i]));
	    	sb.append("\n");
	    	sb.append("---\t---\t---");
	    	for (int i=0;i<lensParNames.length;i++) sb.append("\t---");
	    	sb.append("\n");
	    }
	    new TextWindow("Comparisison of the interparameter dcerivatives (true and compared as deltas)", header, sb.toString(), 500,900);
    }
// after stepping back - no need to rerun calculateFxAndJacobian(false), just keep
	/**
Andrey Filippov's avatar
Andrey Filippov committed
4362
	 *  Calculates f(X) and optionally Jacobian for the current parameters
Andrey Filippov's avatar
Andrey Filippov committed
4363 4364 4365 4366 4367 4368
	 *  @parameter vector - parameter vector to be used
	 *  @parameter calcJacobian  if true, calculates Jacobian as this.jacobian
	 *  @return  f(X) - pixel coordinates for each (visible) grid pattern node for current parameters this.currentVector
	 *   as a 1-d array that alternates pixel-X and pixel-Y for all images
	 *   NOTE: this one is not thread safe
	 */
Andrey Filippov's avatar
Andrey Filippov committed
4369 4370 4371
	public double [] calculateFxAndJacobian(
			double [] vector,
			boolean calcJacobian){ // when false, modifies only this.lensDistortionParameters.*
Andrey Filippov's avatar
Andrey Filippov committed
4372 4373 4374 4375 4376
		if (vector==null) {
			calcJacobian=false;
//			vector = new double[0];
		}
		// TODO: verify classes/arrays exist?
Andrey Filippov's avatar
Andrey Filippov committed
4377
        int doubleNumAllPoints=this.Y.length; // all points in all images multiplied by 2 (x and y error are separate)
Andrey Filippov's avatar
Andrey Filippov committed
4378 4379 4380 4381
		int fittedParNumber=(vector==null)?0:vector.length; //this.currentVector.length;
		double [] vectorFX=new double[doubleNumAllPoints];
//		this.fX=new double[doubleNumAllPoints];
		if (this.debugLevel>2) {
4382
			System.out.println("calculateFxAndJacobian(), calcJacobian="+calcJacobian+" D3304 + this.debugLevel="+this.debugLevel);
Andrey Filippov's avatar
Andrey Filippov committed
4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413
			if (vector!=null) {
			  for (int ii=0;ii<vector.length;ii++) System.out.println(ii+": "+vector[ii]);
			} else {
				System.out.println("calculateFxAndJacobian() : vector==null");
			}
		}
		if (calcJacobian) {
			this.jacobian=new double[fittedParNumber][doubleNumAllPoints];
			for (int i=0;i<fittedParNumber;i++) for (int j=0;j<doubleNumAllPoints;j++) this.jacobian[i][j]=0.0;
		}
		int numImg=fittingStrategy.distortionCalibrationData.getNumImages();
		boolean [] selectedImages=fittingStrategy.selectedImages();
		int index=0;
		IJ.showProgress(0);
		for (int imgNum=0;imgNum<numImg;imgNum++) if (selectedImages[imgNum]) {
//			initialize arrays for parameters and derivatives conversion
			double [] imgVector=fittingStrategy.getImageParametersVector(imgNum, vector); // null is OK now
			boolean [] imgMask=null;
			int []     imgMap= null;
			if (calcJacobian) {
				imgMask= fittingStrategy.getImageParametersVectorMask(imgNum);
				int []     imgRMap=  fittingStrategy.getImageParametersVectorReverseMap(imgNum);
				imgMap=new int[vector.length];
				for (int i=0;i<imgMap.length;i++) imgMap[i]=-1;
				for (int i=0;i<imgRMap.length;i++) if (imgRMap[i]>=0)imgMap[imgRMap[i]]=i;
			}

// Calculate/set  this.lensDistortionParameters class, so it will calculate values/derivatives correctly)
// and this.interParameterDerivatives
//			if (this.debugLevel>1) {
			if (this.debugLevel>2) {
4414
				System.out.println("calculateFxAndJacobian(), imgNum="+imgNum+" calcInterParamers(): (D3336)");
Andrey Filippov's avatar
Andrey Filippov committed
4415
			}
4416
			this.lensDistortionParameters.debugLevel=this.debugLevel;
Andrey Filippov's avatar
Andrey Filippov committed
4417
			this.lensDistortionParameters.lensCalcInterParamers(
Andrey Filippov's avatar
Andrey Filippov committed
4418
					this.lensDistortionParameters,
4419 4420 4421 4422
					this.fittingStrategy.distortionCalibrationData.isTripod(),
					this.fittingStrategy.distortionCalibrationData.isCartesian(),
		    		this.fittingStrategy.distortionCalibrationData.getPixelSize(imgNum),
		    		this.fittingStrategy.distortionCalibrationData.getDistortionRadius(imgNum),
Andrey Filippov's avatar
Andrey Filippov committed
4423 4424 4425 4426 4427 4428 4429
					calcJacobian?this.interParameterDerivatives:null, // [22][]
					imgVector,
					imgMask); // imgMask may be null if no derivativescalculate only selected derivatives (all parVect values are still
			int numPoints=fittingStrategy.distortionCalibrationData.getImageNumPoints(imgNum);
			if (this.debugLevel>2) {
				System.out.println("calculateFxAndJacobian(), numPoints="+numPoints+" (imgNum="+imgNum+")");
			}
Andrey Filippov's avatar
Andrey Filippov committed
4430
// iterate through points, for each calculate pixelx, pixely and derivatives
Andrey Filippov's avatar
Andrey Filippov committed
4431 4432 4433 4434 4435
			for (int pointNum=0;pointNum<numPoints;pointNum++){
				int fullIndex=index+pointNum;
				if (fullIndex>=this.targetXYZ.length){
					System.out.println("BUG: calculateFxAndJacobian() imgNum="+imgNum+" pointNum="+pointNum+" fullIndex="+fullIndex+" this.targetXYZ.length="+this.targetXYZ.length);
				}
4436
				double [][]derivatives15=  lensDistortionParameters.calcPartialDerivatives( // [NaN, NaN]
Andrey Filippov's avatar
Andrey Filippov committed
4437 4438 4439 4440 4441 4442 4443 4444 4445
						this.targetXYZ[fullIndex][0], // target point horizontal, positive - right,  mm
						this.targetXYZ[fullIndex][1], // target point vertical,   positive - down,  mm
						this.targetXYZ[fullIndex][2], // target point horizontal, positive - away from camera,  mm
						calcJacobian); // calculate derivatives, false - values only
	       		if (this.debugLevel>3) {
	    			System.out.println(fullIndex+": calculateFxAndJacobian->calcPartialDerivatives("+IJ.d2s(targetXYZ[fullIndex][0],2)+","+
	    					IJ.d2s(targetXYZ[fullIndex][1],2)+","+
	    					IJ.d2s(targetXYZ[fullIndex][2],2)+" ("+calcJacobian+") -> "+
	    					IJ.d2s(derivatives15[0][0],2)+"/"+IJ.d2s(derivatives15[0][1],2));
4446
	    			String all="derivatives15: D3365";
Andrey Filippov's avatar
Andrey Filippov committed
4447 4448 4449
	    			for (int ii=0;ii<derivatives15.length;ii++) all+=" "+ii+":"+IJ.d2s(derivatives15[ii][0],3)+"/"+IJ.d2s(derivatives15[ii][1],3);
	    			System.out.println(all);
	    		}
Andrey Filippov's avatar
Andrey Filippov committed
4450
				vectorFX[2*fullIndex]=  derivatives15[0][0];
Andrey Filippov's avatar
Andrey Filippov committed
4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484
				vectorFX[2*fullIndex+1]=derivatives15[0][1];
				if (calcJacobian) {
					double [][]derivatives = lensDistortionParameters.reorderPartialDerivatives(derivatives15);
		       		if (this.debugLevel>3) {
		    			String all="derivatives:";
		    			for (int ii=0;ii<derivatives.length;ii++) all+=" "+ii+":"+IJ.d2s(derivatives[ii][0],3)+"/"+IJ.d2s(derivatives[ii][1],3);
		    			System.out.println(all);
		    		}
					for (int i=0;i<this.jacobian.length;i++) if (imgMap[i]>=0){
						double sX=0,sY=0;
						for (int k=0;k<derivatives.length;k++){
							sX+=this.interParameterDerivatives[imgMap[i]][k]*derivatives[k][0];
							sY+=this.interParameterDerivatives[imgMap[i]][k]*derivatives[k][1];
						}
						this.jacobian[i][2*fullIndex]=  sX;
						this.jacobian[i][2*fullIndex+1]=sY;
					}
				}
			}
			index+=numPoints;
			IJ.showProgress(imgNum, numImg-1);
		}
//		IJ.showProgress(0); not needed, will turn off automatically

		return vectorFX;
	}

	/**
	 * Calculate FX and (optionally) Jacobian for one image. FX is a single vector for all images, jacobian - only for one (to save on memory usage)
	 * @param numImage    number of image being processed
	 * @param vector      parameters vector
	 * @param patternXYZ  X,Y,Z of the physical target for each node of each image (TODO: memory may be reduced)
	 * @param vectorFX    Vector to be filled here , twice length as patternXYZ (x and y alternating)
	 * @param imageStartIndex  start index in patternXYZ array (length - difference to the next, includes extra last element)
Andrey Filippov's avatar
Andrey Filippov committed
4485
	 * @param lensDistortionParameters LensDistortionParameters class instance (may be reused between calls)
Andrey Filippov's avatar
Andrey Filippov committed
4486 4487 4488 4489
	 * @param calcJacobian calculate Jacobian matrix (if false - only FX)
	 * @return partial Jacobian matrix, number of rows= vector.length, number of columns - 2*indexCount
	 *   NOTE: this one is thread safe
	 */
Andrey Filippov's avatar
Andrey Filippov committed
4490

Andrey Filippov's avatar
Andrey Filippov committed
4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525
	public double [][] calculatePartialFxAndJacobian(
			final int numImage,      // number of grid image
			final double [] vector,  // parameters vector
			final double [][] patternXYZ, // this.targetXYZ
			final double [] vectorFX,     // non-overlapping segments will be filled
			final int []  imageStartIndex, // start index in patternXYZ array (length - difference to the next, includes extra last element)
			final LensDistortionParameters lensDistortionParameters, // initialize one per each thread? Or for each call?
			boolean calcJacobian){ // when false, modifies only this.lensDistortionParameters.*
		final int    indexStart=imageStartIndex[numImage];      // start index in patternXYZ array
		final int    indexCount=imageStartIndex[numImage+1]-imageStartIndex[numImage]; // number of nodes in the current grid image
		int fittedParNumber=vector.length; //this.currentVector.length;
		if (this.debugLevel>3) {
			System.out.println("calculatePartialFxAndJacobian(), calcJacobian="+calcJacobian+" indexStart="+indexStart+" indexCount="+indexCount);
			for (int ii=0;ii<vector.length;ii++) System.out.println("vector["+ii+"]: "+vector[ii]);
		}
		boolean [] imgMask= fittingStrategy.getImageParametersVectorMask(numImage);        // thread safe
		int []     imgRMap=  fittingStrategy.getImageParametersVectorReverseMap(numImage); // thread safe
		int []     imgMap=new int[vector.length];
		for (int i=0;i<imgMap.length;i++) imgMap[i]=-1;
		for (int i=0;i<imgRMap.length;i++) if (imgRMap[i]>=0)imgMap[imgRMap[i]]=i;
		double [][] jacobian=null;
		if (calcJacobian) {
//			jacobian=new double[fittedParNumber][indexCount*2];
//			for (int i=0;i<fittedParNumber;i++) for (int j=0;j<jacobian[0].length;j++) jacobian[i][j]=0.0;
			jacobian=new double[fittedParNumber][];
			// TODO: verify that only small number of rows is calculated
			for (int i=0;i<fittedParNumber;i++) {
				if (imgMap[i]>=0) {
					jacobian[i]=new double [indexCount*2];
					for (int j=0;j<jacobian[i].length;j++) jacobian[i][j]=0.0;
				} else {
					jacobian[i]=null;
				}
			}
		}
4526
		double [][] interParameterDerivatives=new double [this.lensDistortionParameters.getNumInputs()][];
Andrey Filippov's avatar
Andrey Filippov committed
4527 4528 4529 4530 4531 4532 4533 4534 4535 4536
		//			initialize arrays for parameters and derivatives conversion
		double [] imgVector=fittingStrategy.getImageParametersVector(numImage, vector);     // thread safe
		if (this.debugLevel>3) {
			String all="imgVector: ";
			for (int jj=0;jj<imgVector.length;jj++) all+=" "+imgVector[jj];
			System.out.println(all);
		}
		// Calculate/set  this.lensDistortionParameters class, so it will calculate values/derivatives correctly)
		// and this.interParameterDerivatives
		if (this.debugLevel>3) System.out.println("calculatePartialFxAndJacobian(), numImage="+numImage+" calcInterParamers():");
Andrey Filippov's avatar
Andrey Filippov committed
4537
		lensDistortionParameters.lensCalcInterParamers(
Andrey Filippov's avatar
Andrey Filippov committed
4538
				lensDistortionParameters,
4539 4540 4541 4542
				this.fittingStrategy.distortionCalibrationData.isTripod(),
				this.fittingStrategy.distortionCalibrationData.isCartesian(),
	    		this.fittingStrategy.distortionCalibrationData.getPixelSize(numImage),
	    		this.fittingStrategy.distortionCalibrationData.getDistortionRadius(numImage),
Andrey Filippov's avatar
Andrey Filippov committed
4543 4544 4545 4546
				calcJacobian?interParameterDerivatives:null, // [22][]
						imgVector,
						imgMask); // calculate only selected derivatives (all parVect values are still

Andrey Filippov's avatar
Andrey Filippov committed
4547
		// iterate through points, for each calculate pixelx, pixely and derivatives
Andrey Filippov's avatar
Andrey Filippov committed
4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559
		for (int pointNum=0;pointNum<indexCount;pointNum++){
			int fullIndex=indexStart+pointNum;
			double [][]derivatives15=  lensDistortionParameters.calcPartialDerivatives(
					patternXYZ[fullIndex][0], // target point horizontal, positive - right,  mm
					patternXYZ[fullIndex][1], // target point vertical,   positive - down,  mm
					patternXYZ[fullIndex][2], // target point horizontal, positive - away from camera,  mm
					calcJacobian); // calculate derivatives, false - values only
			if (this.debugLevel>3) {
				System.out.println(fullIndex+": calculateFxAndJacobian->calcPartialDerivatives("+IJ.d2s(patternXYZ[fullIndex][0],2)+","+
						IJ.d2s(patternXYZ[fullIndex][1],2)+","+
						IJ.d2s(patternXYZ[fullIndex][2],2)+" ("+calcJacobian+") -> "+
						IJ.d2s(derivatives15[0][0],2)+"/"+IJ.d2s(derivatives15[0][1],2));
4560
				String all="derivatives15: D3476";
Andrey Filippov's avatar
Andrey Filippov committed
4561 4562 4563
				for (int ii=0;ii<derivatives15.length;ii++) all+=" "+ii+":"+IJ.d2s(derivatives15[ii][0],3)+"/"+IJ.d2s(derivatives15[ii][1],3);
				System.out.println(all);
			}
Andrey Filippov's avatar
Andrey Filippov committed
4564
			vectorFX[2*fullIndex]=  derivatives15[0][0];
Andrey Filippov's avatar
Andrey Filippov committed
4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585
			vectorFX[2*fullIndex+1]=derivatives15[0][1];
			if (calcJacobian) {
				double [][]derivatives = lensDistortionParameters.reorderPartialDerivatives(derivatives15);
				if (this.debugLevel>3) {
					String all="derivatives:";
					for (int ii=0;ii<derivatives.length;ii++) all+=" "+ii+":"+IJ.d2s(derivatives[ii][0],3)+"/"+IJ.d2s(derivatives[ii][1],3);
					System.out.println(all);
				}
				for (int i=0;i<jacobian.length;i++) if (imgMap[i]>=0){
					double sX=0,sY=0;
					for (int k=0;k<derivatives.length;k++){
						sX+=interParameterDerivatives[imgMap[i]][k]*derivatives[k][0];
						sY+=interParameterDerivatives[imgMap[i]][k]*derivatives[k][1];
					}
					jacobian[i][2*pointNum]=  sX;
					jacobian[i][2*pointNum+1]=sY;
				}
			}
		}
		return jacobian;
	}
Andrey Filippov's avatar
Andrey Filippov committed
4586 4587


Andrey Filippov's avatar
Andrey Filippov committed
4588
	/**
Andrey Filippov's avatar
Andrey Filippov committed
4589
	 *
Andrey Filippov's avatar
Andrey Filippov committed
4590 4591 4592 4593 4594 4595
	 * @param vector - parameter vector to be used
	 * @param imgNumber - number of image to process or -1 - use the first of selected in this strategy
	 * @return return Jacobian matrix for the selected image and individual parameters
	 *   NOTE: this one is not thread safe (used this.lensDistortionParameters)
	 */
	// used only to debug derivatives (delta==0 - real derivatives, delta>0 - difference)
Andrey Filippov's avatar
Andrey Filippov committed
4596 4597 4598 4599
	public double [][] calculateJacobian16(
			double [] vector,
			int imgNumber,
			double delta){ // these parameters can work for one image only
Andrey Filippov's avatar
Andrey Filippov committed
4600
        int doubleNumAllPoints=this.Y.length; // all points in all images multiplied by 2 (x and y error are separate)
Andrey Filippov's avatar
Andrey Filippov committed
4601
		double [][] jacobian16=new double[lensDistortionParameters.getNumOutputs()][doubleNumAllPoints];
Andrey Filippov's avatar
Andrey Filippov committed
4602
		double []   values=    new double[doubleNumAllPoints];
Andrey Filippov's avatar
Andrey Filippov committed
4603

Andrey Filippov's avatar
Andrey Filippov committed
4604 4605 4606 4607 4608 4609
		for (int i=0;i<jacobian16.length;i++) for (int j=0;j<doubleNumAllPoints;j++) jacobian16[i][j]=0.0;
		int numImg=fittingStrategy.distortionCalibrationData.getNumImages();
		boolean [] selectedImages=fittingStrategy.selectedImages();
		int index=0;
		for (int imgNum=0;imgNum<numImg;imgNum++) if (selectedImages[imgNum]) {
			int numPoints=fittingStrategy.distortionCalibrationData.getImageNumPoints(imgNum);
Andrey Filippov's avatar
Andrey Filippov committed
4610
			if (imgNumber<0) imgNumber=imgNum; // -1 - use the first image in the list
Andrey Filippov's avatar
Andrey Filippov committed
4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622
			if (imgNum==imgNumber) {
				double [] imgVector=fittingStrategy.getImageParametersVector(imgNum, vector); //this.currentVector);
				boolean [] imgMask= fittingStrategy.getImageParametersVectorMask(imgNum);
				int []     imgRMap=  fittingStrategy.getImageParametersVectorReverseMap(imgNum);
				int []     imgMap=new int[vector.length];
				for (int i=0;i<imgMap.length;i++) imgMap[i]=-1;
				for (int i=0;i<imgRMap.length;i++) if (imgRMap[i]>=0)imgMap[imgRMap[i]]=i;
				// Calculate/set  this.lensDistortionParameters class, so it will calculate values/derivatives correctly)
				// and this.interParameterDerivatives
				if (this.debugLevel>2) {
					System.out.println("calculateJacobian15(), imgNum="+imgNum+" calcInterParamers():");
				}
Andrey Filippov's avatar
Andrey Filippov committed
4623
				this.lensDistortionParameters.lensCalcInterParamers(
Andrey Filippov's avatar
Andrey Filippov committed
4624
						this.lensDistortionParameters,
4625 4626 4627 4628
						this.fittingStrategy.distortionCalibrationData.isTripod(),
						this.fittingStrategy.distortionCalibrationData.isCartesian(),
			    		this.fittingStrategy.distortionCalibrationData.getPixelSize(imgNum),
			    		this.fittingStrategy.distortionCalibrationData.getDistortionRadius(imgNum),
Andrey Filippov's avatar
Andrey Filippov committed
4629 4630 4631 4632 4633 4634 4635 4636
						null, //this.interParameterDerivatives, // [22][]
						imgVector,
						imgMask); // calculate only selected derivatives (all parVect values are still
//						false); // probably can use false
				if (this.debugLevel>2) {
					System.out.println("calculateJacobian16(), numPoints="+numPoints+" (imgNum="+imgNum+")");
				}
				if (delta<=0) {
Andrey Filippov's avatar
Andrey Filippov committed
4637
					// iterate through points, for each calculate pixelx, pixely and derivatives
Andrey Filippov's avatar
Andrey Filippov committed
4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649
					for (int pointNum=0;pointNum<numPoints;pointNum++){
						int fullIndex=index+pointNum;
						double [][]derivatives15=  lensDistortionParameters.calcPartialDerivatives(
								targetXYZ[fullIndex][0], // target point horizontal, positive - right,  mm
								targetXYZ[fullIndex][1], // target point vertical,   positive - down,  mm
								targetXYZ[fullIndex][2], // target point horizontal, positive - away from camera,  mm
								true); // calculate derivatives, false - values only
						if (this.debugLevel>3) {
							System.out.println(fullIndex+": calculateFxAndJacobian->calcPartialDerivatives("+IJ.d2s(targetXYZ[fullIndex][0],2)+","+
									IJ.d2s(targetXYZ[fullIndex][1],2)+","+
									IJ.d2s(targetXYZ[fullIndex][2],2)+" -> "+
									IJ.d2s(derivatives15[0][0],2)+"/"+IJ.d2s(derivatives15[0][1],2));
4650
							String all="derivatives15: D3563";
Andrey Filippov's avatar
Andrey Filippov committed
4651 4652 4653 4654 4655 4656 4657 4658 4659 4660
							for (int ii=0;ii<derivatives15.length;ii++) all+=" "+ii+":"+IJ.d2s(derivatives15[ii][0],3)+"/"+IJ.d2s(derivatives15[ii][1],3);
							System.out.println(all);
						}
						double [][]derivatives = lensDistortionParameters.reorderPartialDerivativesAsNames(derivatives15);
						if (this.debugLevel>3) {
							String all="derivatives:";
							for (int ii=0;ii<derivatives.length;ii++) all+=" "+ii+":"+IJ.d2s(derivatives[ii][0],3)+"/"+IJ.d2s(derivatives[ii][1],3);
							System.out.println(all);
						}
						for (int i=0;i<derivatives.length;i++){
Andrey Filippov's avatar
Andrey Filippov committed
4661
							jacobian16[i][2*fullIndex]= derivatives[i][0]; // oob 16
Andrey Filippov's avatar
Andrey Filippov committed
4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699
							jacobian16[i][2*fullIndex+1]=derivatives[i][1];
						}

					}
				} else {
					double [] parameterVector0=lensDistortionParameters.getAllVector();
					for (int pointNum=0;pointNum<numPoints;pointNum++){
						int fullIndex=index+pointNum;
						double [][]values2=  lensDistortionParameters.calcPartialDerivatives(
								targetXYZ[fullIndex][0], // target point horizontal, positive - right,  mm
								targetXYZ[fullIndex][1], // target point vertical,   positive - down,  mm
								targetXYZ[fullIndex][2], // target point horizontal, positive - away from camera,  mm
								false); // calculate derivatives, false - values only
						values[2*fullIndex]= values2[0][0];
						values[2*fullIndex+1]=values2[0][1];
					}
					for (int nPar=0;nPar<jacobian16.length;nPar++){
						double [] parameterVector=parameterVector0.clone();
						parameterVector[nPar]+=delta;
						lensDistortionParameters.setAllVector(parameterVector);
						for (int pointNum=0;pointNum<numPoints;pointNum++){
							int fullIndex=index+pointNum;
							double [][] values2=lensDistortionParameters.calcPartialDerivatives(
									targetXYZ[fullIndex][0], // target point horizontal, positive - right,  mm
									targetXYZ[fullIndex][1], // target point vertical,   positive - down,  mm
									targetXYZ[fullIndex][2], // target point horizontal, positive - away from camera,  mm
									false); // calculate derivatives, false - values only
							jacobian16[nPar][2*fullIndex]=  (values2[0][0]- values[2*fullIndex])/delta;
							jacobian16[nPar][2*fullIndex+1]=(values2[0][1]- values[2*fullIndex+1])/delta;
						}
					}
				}
				return jacobian16;
			}
			index+=numPoints;
		}
		return null; // should normally return from inside the for loop
	}
Andrey Filippov's avatar
Andrey Filippov committed
4700 4701


Andrey Filippov's avatar
Andrey Filippov committed
4702
/*
Andrey Filippov's avatar
Andrey Filippov committed
4703
List calibration
Andrey Filippov's avatar
Andrey Filippov committed
4704 4705 4706 4707 4708 4709 4710 4711 4712
 */
    public boolean listImageParameters(boolean silent){
    	if (this.fittingStrategy==null) {
        		String msg="Fitting strategy does not exist, exiting";
        		IJ.showMessage("Error",msg);
        		throw new IllegalArgumentException (msg);
    	}
    	int numSeries=fittingStrategy.getNumSeries();
    	if (silent) {
Andrey Filippov's avatar
Andrey Filippov committed
4713
    		this.seriesNumber=0;
Andrey Filippov's avatar
Andrey Filippov committed
4714 4715 4716 4717 4718 4719 4720 4721 4722 4723
    	} else {
    		GenericDialog gd = new GenericDialog("Settings for the parameter list");
    		gd.addNumericField("Iteration number to start (0.."+(numSeries-1)+")", this.seriesNumber, 0);
    		gd.addCheckbox("Show image number (from 0)",                           this.showIndex);
    		gd.addCheckbox("Show per-image RMS",                                   this.showRMS);
    		gd.addCheckbox("Show number of grid points",                           this.showPoints);
    		gd.addCheckbox("Show lens coordinates (relative to target)",           this.showLensLocation);

    		gd.addCheckbox("Show physical camera parameters",                      this.showEyesisParameters);
    		gd.addCheckbox("Show intrinsic lens/sensor parameters ",               this.showIntrinsicParameters);
4724
    		gd.addCheckbox("Show extrinsic lens/sensor parameters",                this.showExtrinsicParameters);
Andrey Filippov's avatar
Andrey Filippov committed
4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746
    		gd.addNumericField("Extra decimal places (precision) in the list",     this.extraDecimals, 0);
    		gd.showDialog();
    		if (gd.wasCanceled()) return false;
    		this.seriesNumber=          (int) gd.getNextNumber();
    		this.showIndex=                   gd.getNextBoolean();
    		this.showRMS=                     gd.getNextBoolean();
    		this.showPoints=                  gd.getNextBoolean();
    		this.showLensLocation=            gd.getNextBoolean();
    		this.showEyesisParameters=        gd.getNextBoolean();
    		this.showIntrinsicParameters=     gd.getNextBoolean();
    		this.showExtrinsicParameters=     gd.getNextBoolean();
    		this.extraDecimals=         (int) gd.getNextNumber();
    	}
// need to select strategy
	    initFittingSeries(true,this.filterForAll,this.seriesNumber); // will set this.currentVector
		this.currentfX=calculateFxAndJacobian(this.currentVector, false); // is it always true here (this.jacobian==null)
		double [] errors=calcErrors(calcYminusFx(this.currentfX));
		double    rms=   calcError (calcYminusFx(this.currentfX));
		int [] numPairs=calcNumPairs();


		boolean [] selectedImages=fittingStrategy.selectedImages();
Andrey Filippov's avatar
Andrey Filippov committed
4747
//TODO: add display of per-image RMS
Andrey Filippov's avatar
Andrey Filippov committed
4748 4749 4750 4751 4752 4753
	    listImageParameters (
	    		selectedImages,
	    		rms,
	    		errors,
	    		numPairs,
	    		this.showIndex,
4754
	    		true, // grid match
Andrey Filippov's avatar
Andrey Filippov committed
4755 4756 4757 4758 4759 4760 4761 4762 4763
	    		this.showRMS,
	    		this.showPoints,
	    		this.showLensLocation,
	    		this.showEyesisParameters,
	    		this.showIntrinsicParameters,
	    		this.showExtrinsicParameters,
	    		this.extraDecimals);
    	return true;
    }
Andrey Filippov's avatar
Andrey Filippov committed
4764

Andrey Filippov's avatar
Andrey Filippov committed
4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805
    public void markBadNodces(int seriesNumber,
    		int debugLevel){
    	int oldSeries=this.seriesNumber;
    	this.seriesNumber=seriesNumber;
    	int totalBadNodes=markBadNodes(
    			fittingStrategy.distortionCalibrationData.eyesisCameraParameters.removeOverRMS,
    			fittingStrategy.distortionCalibrationData.eyesisCameraParameters.removeOverRMSNonweighted,
    			false,
    			debugLevel
    	);
    	if (debugLevel>0) {
    		System.out.println("Marked "+totalBadNodes+" nodes as bad (excessive errors, used fitting series #"+this.seriesNumber+")");
    	}
    	this.seriesNumber=oldSeries;
    }

    public boolean dialogMarkBadNodes(int debugLevel){
    	int numSeries=fittingStrategy.getNumSeries();
    	boolean verbose=false;
    	GenericDialog gd = new GenericDialog("Select parameters for marking bad nodes");
    	gd.addNumericField("Series number to use for selection (0.."+(numSeries-1)+")", this.seriesNumber, 0);
    	gd.addNumericField("Remove nodes with error greater than scaled RMS in that image, weighted",  fittingStrategy.distortionCalibrationData.eyesisCameraParameters.removeOverRMS, 2,6,"xRMS");
    	gd.addNumericField("Same, not weghted (not more permissive near the borders with low weight)", fittingStrategy.distortionCalibrationData.eyesisCameraParameters.removeOverRMSNonweighted, 2,6,"xRMS");
    	gd.addCheckbox    ("Verbose (report number of bad nodes per image)",verbose);
    	gd.showDialog();
    	if (gd.wasCanceled()) return false;
    	this.seriesNumber=          (int) gd.getNextNumber();
    	fittingStrategy.distortionCalibrationData.eyesisCameraParameters.removeOverRMS=            gd.getNextNumber();
    	fittingStrategy.distortionCalibrationData.eyesisCameraParameters.removeOverRMSNonweighted= gd.getNextNumber();
    	verbose=                                                                                   gd.getNextBoolean();
    	int totalBadNodes=markBadNodes(
    			fittingStrategy.distortionCalibrationData.eyesisCameraParameters.removeOverRMS,
    			fittingStrategy.distortionCalibrationData.eyesisCameraParameters.removeOverRMSNonweighted,
    			verbose,
    			debugLevel
    	);
    	if (debugLevel>0) {
    		System.out.println("Marked "+totalBadNodes+" nodes as bad (excessive errors");
    	}
    	return true;
    }
Andrey Filippov's avatar
Andrey Filippov committed
4806

4807
    public boolean removeOutLiers(
4808
    		int series,
4809
    		int numOutLiers,
4810
    		boolean [] selectedChannels){
Andrey Filippov's avatar
Andrey Filippov committed
4811 4812 4813
    	int numSeries=fittingStrategy.getNumSeries();
    	boolean removeEmpty=false;
    	boolean recalculate=false;
4814
    	boolean applyChannelFilter=false;
Andrey Filippov's avatar
Andrey Filippov committed
4815
		int filter=filterForAll;
4816
    	if ((series<0) || (numOutLiers<0)) {
Andrey Filippov's avatar
Andrey Filippov committed
4817 4818
    		GenericDialog gd = new GenericDialog("Select series to process");
    		gd.addNumericField("Iteration number to start (0.."+(numSeries-1)+")", this.seriesNumber, 0);
4819 4820 4821 4822 4823
    		if (selectedChannels != null) {
    			String s="";
    			for (boolean b:selectedChannels)s+=b?"+":"-";
    			gd.addCheckbox("Filter by channel selection ("+s+")", applyChannelFilter);
    		}
Andrey Filippov's avatar
Andrey Filippov committed
4824
    		gd.addCheckbox("Recalculate parameters vector from selected strategy",recalculate);
4825
    		gd.addNumericField("Number of outliers to show", 10, 0);
Andrey Filippov's avatar
Andrey Filippov committed
4826 4827 4828 4829
    		gd.addCheckbox("Remove empty (rms==NaN) images", removeEmpty);
    		gd.addCheckbox("Ask filter (current filter="+filter+")",    this.askFilter);
    		gd.showDialog();
    		if (gd.wasCanceled()) return false;
4830 4831 4832
    		this.seriesNumber=                           (int) gd.getNextNumber();
    		if (selectedChannels != null) applyChannelFilter=  gd.getNextBoolean();
    		recalculate=                                       gd.getNextBoolean();
4833
    		numOutLiers=                                (int) gd.getNextNumber();
4834 4835
    		removeEmpty=                                       gd.getNextBoolean();
    		this.askFilter=                                    gd.getNextBoolean();
Andrey Filippov's avatar
Andrey Filippov committed
4836 4837 4838 4839 4840
    		if (this.askFilter) filter=  selectFilter(filter);
    		filter=0;
    	} else {
    		this.seriesNumber=series;
    	}
4841
    	if (!applyChannelFilter) selectedChannels=null;
4842 4843 4844
    	if (recalculate) {
    		resetGridImageMasks(); // FIXME: move elsewhere?
    	}
Andrey Filippov's avatar
Andrey Filippov committed
4845 4846 4847 4848 4849 4850
//	    initFittingSeries(!recalculate,this.filterForAll,this.seriesNumber); // will set this.currentVector
	    initFittingSeries(!recalculate,this.filterForAll,this.seriesNumber); // will set this.currentVector
		this.currentfX=calculateFxAndJacobian(this.currentVector, false); // is it always true here (this.jacobian==null)
		double [] errors=calcErrors(calcYminusFx(this.currentfX)); // seem to have errors? - now may return NaN!
		double    rms=   calcError (calcYminusFx(this.currentfX));
		boolean [] selectedImages=fittingStrategy.selectedImages();
4851 4852 4853 4854 4855 4856 4857
		if (selectedChannels!=null){
			selectedImages=selectedImages.clone(); // disconnect from original for modification
			for (int i=0;i<selectedImages.length;i++) if (selectedImages[i]){
				int chn=this.fittingStrategy.distortionCalibrationData.gIP[i].channel;
				if ((chn<0) || (chn>=selectedChannels.length) || !selectedChannels[chn]){
					selectedImages[i]=false;
				}
Andrey Filippov's avatar
Andrey Filippov committed
4858
			}
4859
		}
Andrey Filippov's avatar
Andrey Filippov committed
4860 4861 4862 4863 4864 4865 4866 4867 4868 4869
		int numSelectedNotNaNImages=0;
		int numNaN=0;
		for (int i=0;i<selectedImages.length;i++) if (selectedImages[i]) {
			if (!Double.isNaN(errors[i])) numSelectedNotNaNImages++;
			else numNaN++;
		}
		int [] imgIndices=new int[numSelectedNotNaNImages];
		int index=0;
		for (int i=0;i<selectedImages.length;i++) if ( selectedImages[i] && !Double.isNaN(errors[i])) imgIndices[index++]=i; // OOB 2389

4870 4871
		if (numOutLiers>numSelectedNotNaNImages) numOutLiers=numSelectedNotNaNImages;
		int [] indices=new int [numOutLiers];
Andrey Filippov's avatar
Andrey Filippov committed
4872 4873
		boolean [] availableImages=selectedImages.clone();
		for (int i=0;i<selectedImages.length;i++) if (selectedImages[i] && Double.isNaN(errors[i])) availableImages[i]=false;
Andrey Filippov's avatar
Andrey Filippov committed
4874 4875


Andrey Filippov's avatar
Andrey Filippov committed
4876
		if ((this.debugLevel>0) && (numNaN>0)){
4877
			System.out.println("removeOutLiers(): Number of empty (rms=NaN) images="+numNaN+":");
Andrey Filippov's avatar
Andrey Filippov committed
4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893
			int n=0;
			for (int i=0;i<selectedImages.length;i++) if (selectedImages[i] && Double.isNaN(errors[i])){
				n++;
				System.out.println(n+": "+i+": "+this.fittingStrategy.distortionCalibrationData.gIP[i].path);
			}
		}
		if (removeEmpty){
			int n=0;
			for (int i=0;i<selectedImages.length;i++) if (selectedImages[i] && Double.isNaN(errors[i])){
				n++;
				if (this.debugLevel>0) System.out.println(n+"removing empty image #"+i+": "+this.fittingStrategy.distortionCalibrationData.gIP[i].path);
				this.fittingStrategy.distortionCalibrationData.gIP[i].enabled=false;
				this.fittingStrategy.distortionCalibrationData.gIP[i].hintedMatch=-1; // so can be re-calibrated again w/o others
			}

		}
Andrey Filippov's avatar
Andrey Filippov committed
4894

4895 4896
		System.out.println("removeOutLiers(): availableImages.length="+availableImages.length+" numSelectedNotNaNImages="+numSelectedNotNaNImages);
		for (int n=0;n<numOutLiers;n++){
Andrey Filippov's avatar
Andrey Filippov committed
4897 4898 4899 4900 4901 4902 4903
			double maxRMS=-1.0;
			indices[n]=-1;
			for (int i=0;i<availableImages.length;i++)if (availableImages[i] && (Double.isNaN(errors[i]) || (errors[i]>maxRMS))){ // Double.NaN will be greater
					maxRMS=errors[i];
					indices[n]=i;
			}
			if (indices[n]<0){
4904
				System.out.println("removeOutLiers(): indices["+n+"]="+indices[n]);
Andrey Filippov's avatar
Andrey Filippov committed
4905 4906 4907 4908
				continue;
			}
			availableImages[indices[n]]=false; // java.lang.ArrayIndexOutOfBoundsException: -1
		}
Andrey Filippov's avatar
Andrey Filippov committed
4909

Andrey Filippov's avatar
Andrey Filippov committed
4910
		GenericDialog gd = new GenericDialog("Select images to remove (RMS="+IJ.d2s(rms,3)+")");
4911
		if (this.debugLevel>0) System.out.println("Listing "+numOutLiers+" worst images:");
Andrey Filippov's avatar
Andrey Filippov committed
4912
		for (int n=0;n<indices.length;n++){
4913
			String msg=n+" ("+indices[n]+" / "+ this.fittingStrategy.distortionCalibrationData.gIP[indices[n]].getSetNumber()+"): "+
Andrey Filippov's avatar
Andrey Filippov committed
4914 4915 4916 4917
			IJ.d2s(errors[indices[n]],3)+" "+
			this.fittingStrategy.distortionCalibrationData.gIP[indices[n]].path+
			" ("+this.fittingStrategy.distortionCalibrationData.gIP[indices[n]].pixelsXY.length+
			" points) "+selectedImages[indices[n]];
Andrey Filippov's avatar
Andrey Filippov committed
4918

Andrey Filippov's avatar
Andrey Filippov committed
4919 4920 4921 4922 4923 4924 4925
			if (this.debugLevel>0) System.out.println(
					msg);
			gd.addCheckbox(msg, true);
		}
		WindowTools.addScrollBars(gd);
		gd.showDialog();
		if (gd.wasCanceled()) return false;
4926
		if (this.debugLevel>0) System.out.println("Removing outliers:");
Andrey Filippov's avatar
Andrey Filippov committed
4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937
		for (int n=0;n<indices.length;n++){
			if (gd.getNextBoolean()) {
				if (this.debugLevel>0) System.out.println(n+" :"+IJ.d2s(errors[indices[n]],3)+" "+this.fittingStrategy.distortionCalibrationData.gIP[indices[n]].path);
				this.fittingStrategy.distortionCalibrationData.gIP[indices[n]].enabled=false;
				this.fittingStrategy.distortionCalibrationData.gIP[indices[n]].hintedMatch=-1; // so can be re-calibrated again w/o others
			}
		}
		fittingStrategy.distortionCalibrationData.updateSetOrientation(null); // remove orientation information from the image set if none is enabled
		return true;
    }

4938
    public boolean removeOutLierSets(int numOutLiers){
4939
    	boolean removeEmptySets=true; // false;
4940
    	if (numOutLiers<0) {
Andrey Filippov's avatar
Andrey Filippov committed
4941 4942
    		GenericDialog gd = new GenericDialog("Select sets to process");
    		gd.addNumericField("Series number (<0 - all images)", -1, 0);
4943
    		gd.addNumericField("Number of outliers to show", 5, 0);
Andrey Filippov's avatar
Andrey Filippov committed
4944 4945 4946 4947 4948
    		gd.addCheckbox("Remove empty sets", removeEmptySets);
    		gd.addCheckbox("Ask for weight function filter",     this.askFilter);
    		gd.showDialog();
    		if (gd.wasCanceled()) return false;
    		this.seriesNumber= (int) gd.getNextNumber();
4949
    		numOutLiers=      (int) gd.getNextNumber();
Andrey Filippov's avatar
Andrey Filippov committed
4950 4951 4952 4953 4954 4955
    		removeEmptySets=         gd.getNextBoolean();
    		this.askFilter=         gd.getNextBoolean();
    	}
//		boolean [] oldSelection=this.fittingStrategy.selectAllImages(0); // enable all images in series 0
		int filter=this.filterForAll;
		if (this.askFilter) filter=selectFilter(filter);
4956 4957 4958 4959 4960 4961 4962 4963

    	initFittingSeries(true,filter, -1); // this.seriesNumber); // will set this.currentVector
		this.currentfX=calculateFxAndJacobian(this.currentVector, false); // is it always true here (this.jacobian==null)
		double [] errors=calcErrors(calcYminusFx(this.currentfX)); // for all images
		double    rms=   calcError (calcYminusFx(this.currentfX));
		int []    numPairs=calcNumPairs(); // for all images, not only selected

// re-init for the selected series
Andrey Filippov's avatar
Andrey Filippov committed
4964 4965 4966
    	initFittingSeries(true,filter,this.seriesNumber); // will set this.currentVector
//    	initFittingSeries(true,this.filterForAll,this.seriesNumber); // will set this.currentVector
		this.currentfX=calculateFxAndJacobian(this.currentVector, false); // is it always true here (this.jacobian==null)
4967 4968 4969 4970 4971 4972 4973
//		double [] errors=calcErrors(calcYminusFx(this.currentfX)); // error - always for -1?
		rms=   calcError (calcYminusFx(this.currentfX)); // for selected series



		boolean [] selectedImages=fittingStrategy.selectedImages(this.seriesNumber);
//		int [] numPairs=calcNumPairs();
4974 4975 4976 4977
		int [][] imageSets=this.fittingStrategy.distortionCalibrationData.listImages(
				false, // true - only enabled images
				null);    // do not filter eo, lwir
    
Andrey Filippov's avatar
Andrey Filippov committed
4978 4979 4980 4981 4982 4983 4984
	    int [] numSetPoints=new int [imageSets.length];
	    double [] rmsPerSet=new double[imageSets.length];
	    boolean [] hasNaNInSet=new boolean[imageSets.length];
	    boolean [] allNaNInSet=new boolean[imageSets.length];
	    for (int setNum=0;setNum<imageSets.length;setNum++){
	    	double error2=0.0;
	    	int numInSet=0;
4985
	    	int numInSetOther=0; // not selected in this
Andrey Filippov's avatar
Andrey Filippov committed
4986
    		hasNaNInSet[setNum]=false;
4987
    		boolean has_selected = false; // remove selected with all nan in selected, and unselected with all nans
Andrey Filippov's avatar
Andrey Filippov committed
4988
    		for (int imgInSet=0;imgInSet<imageSets[setNum].length;imgInSet++){
4989 4990 4991 4992 4993 4994 4995 4996 4997
    			int imgNum=imageSets[setNum][imgInSet];
				int num=numPairs[imgNum];
    			if (selectedImages[imgNum]) {
    				has_selected = true;
    				if (Double.isNaN(errors[imgNum])){
    					hasNaNInSet[setNum]=true;
    				} else {
    					error2+=errors[imgNum]*errors[imgNum]*num;
    					numInSet+=num;
Andrey Filippov's avatar
Andrey Filippov committed
4998

4999 5000 5001 5002 5003 5004
    				}
    			} else {
    				if (!Double.isNaN(errors[imgNum])){
    					numInSetOther += num;
    				}
    			}
Andrey Filippov's avatar
Andrey Filippov committed
5005
	    	}
5006 5007
//    		allNaNInSet[setNum]= hasNaNInSet[setNum] && (numInSet==0);
    		allNaNInSet[setNum]= has_selected? (numInSet == 0) : ((numInSet + numInSetOther) == 0);
Andrey Filippov's avatar
Andrey Filippov committed
5008
	    	numSetPoints[setNum]=numInSet;
5009
	    	rmsPerSet[setNum]=(numInSet>0)?Math.sqrt(error2/numInSet) : Double.NaN; // only count selected images (i.e. only eo, ignore lwir)
Andrey Filippov's avatar
Andrey Filippov committed
5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022
	    }
//		int numSelectedNotNaNSets=0;
		int numSelectedSets=0;
		int numNaN=0;
		for (int i=0;i<imageSets.length;i++)  {
//			if (!Double.isNaN(rmsPerSet[i])) numSelectedSets++;
			if (!allNaNInSet[i]) numSelectedSets++;
			else numNaN++;
		}
//		int [] imgIndices=new int[numSelectedNotNaNSets];
//		int index=0;
//		for (int i=0;i<imageSets.length;i++) if ( selectedImages[i]) imgIndices[index++]=i;

5023 5024
		if (numOutLiers>numSelectedSets) numOutLiers=numSelectedSets;
		int [] indices=new int [numOutLiers];
Andrey Filippov's avatar
Andrey Filippov committed
5025 5026
		boolean [] availableSets= new boolean  [imageSets.length];
		for (int i=0;i<imageSets.length;i++) availableSets[i]= !allNaNInSet[i]; //!Double.isNaN(rmsPerSet[i]);
5027 5028
/*
		// Remove all empty, not just selected by strategy. Now errors are calculated for all images, not juet selected
Andrey Filippov's avatar
Andrey Filippov committed
5029
		if (removeEmptySets  && (numNaN>0)){ //(this.debugLevel>0)
5030
			if (this.debugLevel>-1) System.out.println("removeOutLierSets(): Number of empty (rms=NaN) sets="+numNaN+":");
5031
//			int n=0;
Andrey Filippov's avatar
Andrey Filippov committed
5032
			for (int setNum=0;setNum<imageSets.length;setNum++) if (!availableSets[setNum]){
5033
//				n++;
Andrey Filippov's avatar
Andrey Filippov committed
5034 5035 5036 5037 5038 5039 5040 5041 5042 5043
				if (this.debugLevel>0) System.out.println("Set "+setNum);
	    		for (int imgInSet=0;imgInSet<imageSets[setNum].length;imgInSet++){
					int numImg=imageSets[setNum][imgInSet];
					if (this.debugLevel>0) System.out.println(setNum+":"+imgInSet+" #"+ numImg+" "+IJ.d2s(errors[numImg],3)+" "+
							this.fittingStrategy.distortionCalibrationData.gIP[numImg].path);
					this.fittingStrategy.distortionCalibrationData.gIP[numImg].enabled=false;
					this.fittingStrategy.distortionCalibrationData.gIP[numImg].hintedMatch=-1; // so can be re-calibrated again w/o others
	    		}
			}
		}
5044
*/
5045 5046
		System.out.println("removeOutLierSets(): availableSets.length="+availableSets.length+" numSelectedSets="+numSelectedSets);
		for (int n=0;n<numOutLiers;n++){
Andrey Filippov's avatar
Andrey Filippov committed
5047 5048 5049 5050 5051 5052 5053
			double maxRMS=-1.0;
			indices[n]=-1;
			for (int i=0;i<availableSets.length;i++)if (availableSets[i] && (rmsPerSet[i]>maxRMS)){ // NaN are already skipped
					maxRMS=rmsPerSet[i];
					indices[n]=i;
			}
			if (indices[n]<0){
5054
				System.out.println("removeOutLierSets(): indices["+n+"]="+indices[n]);
Andrey Filippov's avatar
Andrey Filippov committed
5055 5056 5057 5058
				continue;
			}
			availableSets[indices[n]]=false; // java.lang.ArrayIndexOutOfBoundsException: -1
		}
Andrey Filippov's avatar
Andrey Filippov committed
5059

Andrey Filippov's avatar
Andrey Filippov committed
5060
		GenericDialog gd = new GenericDialog("Select image Sets to remove (RMS="+IJ.d2s(rms,3)+")");
5061
		if (this.debugLevel>0) System.out.println("Listing "+numOutLiers+" worst image sets");
Andrey Filippov's avatar
Andrey Filippov committed
5062 5063
		for (int n=0;n<indices.length;n++){
			int numSet=indices[n];
5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078
			if (numSet >= 0) {
				double setWeight=this.fittingStrategy.distortionCalibrationData.gIS[numSet].setWeight; //-1
				if (this.debugLevel>0) System.out.println(n+" ("+numSet+"): "+(hasNaNInSet[numSet]?"* ":"")+IJ.d2s(rmsPerSet[numSet],3)+
						" points: "+numSetPoints[numSet]+" weight:"+setWeight);
				gd.addCheckbox(n+": "+numSet+": "+(hasNaNInSet[numSet]?"* ":"")+IJ.d2s(rmsPerSet[numSet],3)+" weight:"+setWeight, true);
				for (int i=0;i<imageSets[numSet].length;i++){
					int numImg=imageSets[numSet][i];
					double diameter=this.fittingStrategy.distortionCalibrationData.gIP[numImg].getGridDiameter();
					gd.addMessage(i+":"+numImg+": "+IJ.d2s(errors[numImg],3)+" "+
							" ("+this.fittingStrategy.distortionCalibrationData.gIP[numImg].pixelsXY.length+" points, diameter="+diameter+") "+
							this.fittingStrategy.distortionCalibrationData.gIP[numImg].path);
					if (this.debugLevel>0) System.out.println("  --- "+numImg+": "+IJ.d2s(errors[numImg],3)+" "+
							" ("+this.fittingStrategy.distortionCalibrationData.gIP[numImg].pixelsXY.length+" points, diameter="+diameter+") "+
							this.fittingStrategy.distortionCalibrationData.gIP[numImg].path);
				}
Andrey Filippov's avatar
Andrey Filippov committed
5079 5080 5081 5082 5083 5084 5085 5086
			}
		}
		WindowTools.addScrollBars(gd);
		gd.showDialog();
		if (gd.wasCanceled()){
//			this.fittingStrategy.setImageSelection(0, oldSelection); // restore original selection in series 0
			return false;
		}
5087
		if (this.debugLevel>0) System.out.println("Removing outliers:");
Andrey Filippov's avatar
Andrey Filippov committed
5088
		for (int n=0;n<indices.length;n++){
5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113
			int numSet=indices[n];
			if (numSet >= 0) {
				if (gd.getNextBoolean()) {
					if (this.debugLevel>0) System.out.println(" Removing imgages in image set "+numSet);
					for (int i=0;i<imageSets[numSet].length;i++){
						int numImg=imageSets[numSet][i];
						if (this.debugLevel>0) System.out.println(n+":"+i+"("+numImg+")"+IJ.d2s(errors[numImg],3)+" "+
								this.fittingStrategy.distortionCalibrationData.gIP[numImg].path);
						this.fittingStrategy.distortionCalibrationData.gIP[numImg].enabled=false;
						this.fittingStrategy.distortionCalibrationData.gIP[numImg].hintedMatch=-1; // so can be re-calibrated again w/o others
					}
				}
			}
		}

		// Remove all empty, not just selected by strategy. Now errors are calculated for all images, not juet selected
		if (removeEmptySets  && (numNaN>0)){ //(this.debugLevel>0)
			if (this.debugLevel>-1) System.out.println("removeOutLierSets(): Number of empty (rms=NaN) sets="+numNaN+":");
//			int n=0;
			for (int setNum=0;setNum<imageSets.length;setNum++) if (!availableSets[setNum]){
//				n++;
				if (this.debugLevel>0) System.out.println("Set "+setNum);
	    		for (int imgInSet=0;imgInSet<imageSets[setNum].length;imgInSet++){
					int numImg=imageSets[setNum][imgInSet];
					if (this.debugLevel>0) System.out.println(setNum+":"+imgInSet+" #"+ numImg+" "+IJ.d2s(errors[numImg],3)+" "+
Andrey Filippov's avatar
Andrey Filippov committed
5114 5115 5116
							this.fittingStrategy.distortionCalibrationData.gIP[numImg].path);
					this.fittingStrategy.distortionCalibrationData.gIP[numImg].enabled=false;
					this.fittingStrategy.distortionCalibrationData.gIP[numImg].hintedMatch=-1; // so can be re-calibrated again w/o others
5117
	    		}
Andrey Filippov's avatar
Andrey Filippov committed
5118 5119
			}
		}
5120 5121


Andrey Filippov's avatar
Andrey Filippov committed
5122
		// next is not needed
5123
		fittingStrategy.distortionCalibrationData.updateSetOrientation(null); //selectedImages); // null); // remove orientation information from the image set if none is enabled
Andrey Filippov's avatar
Andrey Filippov committed
5124 5125 5126
//		this.fittingStrategy.setImageSelection(0, oldSelection); // restore original selection in series 0
		return true;
    }
Andrey Filippov's avatar
Andrey Filippov committed
5127

5128
    public boolean removeOutLiersJunk(int series, int numOutLiers){
Andrey Filippov's avatar
Andrey Filippov committed
5129
    	int numSeries=fittingStrategy.getNumSeries();
5130
    	if ((series<0) || (numOutLiers<0)) {
Andrey Filippov's avatar
Andrey Filippov committed
5131 5132
    		GenericDialog gd = new GenericDialog("Select series to process");
    		gd.addNumericField("Iteration number to start (0.."+(numSeries-1)+")", this.seriesNumber, 0);
5133
    		gd.addNumericField("Number of outliers to show", 10, 0);
Andrey Filippov's avatar
Andrey Filippov committed
5134 5135 5136
    		gd.showDialog();
    		if (gd.wasCanceled()) return false;
    		this.seriesNumber=          (int) gd.getNextNumber();
5137
    		numOutLiers=               (int) gd.getNextNumber();
Andrey Filippov's avatar
Andrey Filippov committed
5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151
    	} else {
    		this.seriesNumber=series;
    	}
	    initFittingSeries(true,this.filterForAll,this.seriesNumber); // will set this.currentVector
		this.currentfX=calculateFxAndJacobian(this.currentVector, false); // is it always true here (this.jacobian==null)
		double [] errors=calcErrors(calcYminusFx(this.currentfX));
		double    rms=   calcError (calcYminusFx(this.currentfX));
		boolean [] selectedImages=fittingStrategy.selectedImages();
		int numSelectedImages=0;
		for (int i=0;i<selectedImages.length;i++) if (selectedImages[i]) numSelectedImages++;
		int [] imgIndices=new int[numSelectedImages];
		int index=0;
		for (int i=0;i<selectedImages.length;i++) if ( selectedImages[i]) imgIndices[index++]=i;

5152 5153 5154
		if (numOutLiers>numSelectedImages) numOutLiers=numSelectedImages;
		int [] indices=new int [numOutLiers];
		int [] indicesSelected=new int [numOutLiers];
Andrey Filippov's avatar
Andrey Filippov committed
5155 5156
		boolean [] availableImages=new boolean[numSelectedImages];
		for (int i=0;i<availableImages.length;i++)availableImages[i]=true;
5157
		for (int n=0;n<numOutLiers;n++){
Andrey Filippov's avatar
Andrey Filippov committed
5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183
			double maxRMS=0;
			indices[n]=-1;
			indicesSelected[n]=-1;
			int imgIndex=0;
			for (int i=0;i<selectedImages.length;i++)if (selectedImages[i]){
				if (availableImages[imgIndex] && (errors[imgIndex]>maxRMS)){
					maxRMS=errors[imgIndex];
					indicesSelected[n]=imgIndex;
					indices[n]=i;
				}
				imgIndex++;
			}
			availableImages[indicesSelected[n]]=false;
		}
		GenericDialog gd = new GenericDialog("Select images to remove (RMS="+IJ.d2s(rms,3)+")");
		for (int n=0;n<indices.length;n++){
			gd.addCheckbox(indices[n]+": "+IJ.d2s(errors[indicesSelected[n]],3)+" "+this.fittingStrategy.distortionCalibrationData.gIP[indices[n]].path, true);
		}
		WindowTools.addScrollBars(gd);
		gd.showDialog();
		if (gd.wasCanceled()) return false;
		for (int n=0;n<indices.length;n++){
			if (gd.getNextBoolean()) this.fittingStrategy.distortionCalibrationData.gIP[indices[n]].enabled=false;
		}
		return true;
    }
Andrey Filippov's avatar
Andrey Filippov committed
5184

Andrey Filippov's avatar
Andrey Filippov committed
5185 5186 5187 5188 5189 5190
	/**
	 * Opens a text window with the parameter table
	 * @param imageSelection which images include in the output
	 * @param showEyesisParameters show physical location/attitude based on Eyesis
	 * @param showIntrinsicParameters show lens distortion/alignment parameters)
	 * @param showExtrinsicParameters show position/attitude of the individual cameras
Andrey Filippov's avatar
Andrey Filippov committed
5191
	 * @param extraDecimals add this many decimals to data
Andrey Filippov's avatar
Andrey Filippov committed
5192 5193 5194 5195 5196 5197
	 */
	public void listImageParameters (boolean [] imageSelection,
    		double rms,
    		double [] errors,
    		int    [] numPairs,
    		boolean showIndex,
5198
    		boolean showGridMatch,
Andrey Filippov's avatar
Andrey Filippov committed
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
    		boolean showErrors,
    	    boolean showPoints,
    		boolean showLensCoordinates,
			boolean showEyesisParameters,
			boolean showIntrinsicParameters,
			boolean showExtrinsicParameters,
			int extraDecimals){
		int numImages=0;

		for (int i=0;i<fittingStrategy.distortionCalibrationData.getNumImages();i++) {
			if((imageSelection==null) || ((i<imageSelection.length) && imageSelection[i])) numImages++;
		}
		double  [][] intrinsic=new double [numImages][];
		double  [][] extrinsic=new double [numImages][];
		double  [][] lensCoordinates=new double [numImages][];
		int [] imgIndices=new int[numImages];
		int index=0;
		for (int i=0;i<fittingStrategy.distortionCalibrationData.getNumImages();i++) {
			if((imageSelection==null) || ((i<imageSelection.length) && imageSelection[i])) imgIndices[index++]=i;
		}
		for (int imgIndex=0;imgIndex<numImages;imgIndex++) {
			int imgNum=imgIndices[imgIndex]; // image number
			if (this.debugLevel>2) {
				System.out.println("listImageParameters(), imgNum="+imgNum+" calcInterParamers():");
			}
Andrey Filippov's avatar
Andrey Filippov committed
5224
			this.lensDistortionParameters.lensCalcInterParamers(
Andrey Filippov's avatar
Andrey Filippov committed
5225
					this.lensDistortionParameters,
5226 5227 5228 5229
					this.fittingStrategy.distortionCalibrationData.isTripod(),
					this.fittingStrategy.distortionCalibrationData.isCartesian(),
		    		this.fittingStrategy.distortionCalibrationData.getPixelSize(imgNum),
		    		this.fittingStrategy.distortionCalibrationData.getDistortionRadius(imgNum),
Andrey Filippov's avatar
Andrey Filippov committed
5230 5231 5232 5233 5234 5235 5236 5237 5238
					null, //this.interParameterDerivatives, // [22][]
//					fittingStrategy.distortionCalibrationData.pars[imgNum], // 22-long parameter vector for the image
					fittingStrategy.distortionCalibrationData.getParameters(imgNum), // 22-long parameter vector for the image
					null); // if no derivatives, null is OK
//					false); // calculate this.interParameterDerivatives -derivatives array (false - just this.values)
			intrinsic[imgIndex]=      lensDistortionParameters.getIntrinsicVector().clone();
			extrinsic[imgIndex]=      lensDistortionParameters.getExtrinsicVector().clone();
			lensCoordinates[imgIndex]=lensDistortionParameters.getLensCenterCoordinates();
		}
Andrey Filippov's avatar
Andrey Filippov committed
5239

Andrey Filippov's avatar
Andrey Filippov committed
5240 5241 5242 5243 5244
	    String header="Name\tUnits";
		for (int imgIndex=0;imgIndex<numImages;imgIndex++)
			header+="\t"+IJ.d2s(fittingStrategy.distortionCalibrationData.getImageTimestamp(imgIndices[imgIndex]),6);
	    StringBuffer sb = new StringBuffer();
	    if (showIndex) {
5245
			sb.append("Station \t");
Andrey Filippov's avatar
Andrey Filippov committed
5246
			for (int imgIndex=0;imgIndex<numImages;imgIndex++){
5247
				sb.append("\t"+fittingStrategy.distortionCalibrationData.gIP[imgIndices[imgIndex]].getStationNumber());
Andrey Filippov's avatar
Andrey Filippov committed
5248 5249
			}
			sb.append("\n");
5250 5251 5252 5253 5254 5255 5256 5257 5258
			sb.append("Set \t");
			for (int imgIndex=0;imgIndex<numImages;imgIndex++){
				sb.append("\t"+fittingStrategy.distortionCalibrationData.gIP[imgIndices[imgIndex]].getSetNumber());
			}
			sb.append("\n");
			sb.append("Index \t");
			for (int imgIndex=0;imgIndex<numImages;imgIndex++){
				sb.append("\t"+imgIndices[imgIndex]);
			}
Andrey Filippov's avatar
Andrey Filippov committed
5259

5260 5261 5262 5263 5264 5265 5266 5267 5268
	    }
	    if (showGridMatch){
			sb.append("Grid Match"+"\tX/Y:ROT");
			for (int imgIndex=0;imgIndex<numImages;imgIndex++){
				int imgNum=imgIndices[imgIndex]; // image number
				int [] shiftRot=fittingStrategy.distortionCalibrationData.getUVShiftRot(imgNum);
				sb.append("\t"+shiftRot[0]+"/"+shiftRot[1]+":"+shiftRot[2]);
			}
			sb.append("\n");
Andrey Filippov's avatar
Andrey Filippov committed
5269

5270 5271 5272
			sb.append("Lasers(matched)"+"\t");
			for (int imgIndex=0;imgIndex<numImages;imgIndex++){
				int imgNum=imgIndices[imgIndex]; // image number
Andrey Filippov's avatar
Andrey Filippov committed
5273

5274 5275 5276 5277 5278 5279 5280 5281
    			int numPointers=0; // count number of laser pointers
    	        DistortionCalibrationData.GridImageParameters gip=fittingStrategy.distortionCalibrationData.getGridImageParameters(imgNum);
    			if (gip.laserPixelCoordinates!=null){
    				for (int j=0;j<gip.laserPixelCoordinates.length;j++) if (gip.laserPixelCoordinates[j]!=null) numPointers++;
    			}
    			sb.append("\t");
    			if (!gip.enabled) sb.append("(");
    			sb.append(numPointers+"("+gip.matchedPointers+"):"+gip.hintedMatch +
5282
    					" "+IJ.d2s(gip.getGridPeriod(),1));
5283 5284 5285
    			if (!gip.enabled) sb.append(")");
			}
			sb.append("\n");
Andrey Filippov's avatar
Andrey Filippov committed
5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319
	    }
		if (showErrors) {
				sb.append("--- RMS "+IJ.d2s(rms,3+extraDecimals)+"\tpix");
				for (int imgIndex=0;imgIndex<numImages;imgIndex++){
					int imgNum=imgIndices[imgIndex]; // image number
					sb.append("\t"+IJ.d2s(errors[imgNum],3+extraDecimals));
				}
				sb.append("\n");
		}
		if (showPoints) {
			int totalPoints=0;
			for (int imgIndex=0;imgIndex<numImages;imgIndex++){
				totalPoints+=numPairs[imgIndices[imgIndex]];
			}
			sb.append(" points "+totalPoints+"\t");
			for (int imgIndex=0;imgIndex<numImages;imgIndex++){
				sb.append("\t"+numPairs[imgIndices[imgIndex]]);
			}
			sb.append("\n");
			sb.append(" Diameter\trel");
			for (int imgIndex=0;imgIndex<numImages;imgIndex++){
				int imgNum=imgIndices[imgIndex]; // image number
				sb.append("\t"+IJ.d2s(this.fittingStrategy.distortionCalibrationData.gIP[imgNum].getGridDiameter(),2));
			}
			sb.append("\n");
		}
		if (showEyesisParameters) {
//			getImageSubcamera
			sb.append("Sub-camera\t");
			for (int imgIndex=0;imgIndex<numImages;imgIndex++){
				int imgNum=imgIndices[imgIndex]; // image number
				sb.append("\t"+fittingStrategy.distortionCalibrationData.getImageSubcamera(imgNum));
			}
			sb.append("\n");
Andrey Filippov's avatar
Andrey Filippov committed
5320

5321
			for (int parNumber=0;parNumber<fittingStrategy.distortionCalibrationData.getNumDescriptions();parNumber++){
Andrey Filippov's avatar
Andrey Filippov committed
5322
				sb.append(
5323 5324
						fittingStrategy.distortionCalibrationData.descrField(parNumber,0)+"\t"+
						fittingStrategy.distortionCalibrationData.descrField(parNumber,2));
Andrey Filippov's avatar
Andrey Filippov committed
5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384
				for (int imgIndex=0;imgIndex<numImages;imgIndex++){
					int imgNum=imgIndices[imgIndex]; // image number
//					sb.append("\t"+IJ.d2s(fittingStrategy.distortionCalibrationData.pars[imgNum][parNumber],3+extraDecimals)); // TODO: make an array of decimals per parameter
					sb.append("\t"+IJ.d2s(fittingStrategy.distortionCalibrationData.getParameterValue(imgNum,parNumber),3+extraDecimals)); // TODO: make an array of decimals per parameter
				}
				sb.append("\n");
			}
		}
		if (showIntrinsicParameters) {
			sb.append("--- Intrinsic\t");
			for (int imgIndex=0;imgIndex<numImages;imgIndex++) sb.append("\t---");
			sb.append("\n");
			for (int parNumber=0;parNumber<lensDistortionParameters.getIntrinsicNames().length;parNumber++){
				sb.append(
						lensDistortionParameters.getIntrinsicNames()[parNumber]+"\t"+
						lensDistortionParameters.getIntrinsicUnits()[parNumber]);
				for (int imgIndex=0;imgIndex<numImages;imgIndex++){
					sb.append("\t"+IJ.d2s(intrinsic[imgIndex][parNumber],3+extraDecimals)); // TODO: make an array of decimals per parameter
				}
				sb.append("\n");
			}
		}
		if (showExtrinsicParameters ||  showLensCoordinates) {
			sb.append("--- Extrinsic\t");
			for (int imgIndex=0;imgIndex<numImages;imgIndex++) sb.append("\t---");
			sb.append("\n");
	        if (showLensCoordinates){
				sb.append("Lens X(right)\tmm");
				for (int imgIndex=0;imgIndex<numImages;imgIndex++){
//					int imgNum=imgIndices[imgIndex]; // image number
					sb.append("\t"+IJ.d2s(lensCoordinates[imgIndex][0],3+extraDecimals));
				}
				sb.append("\n");
				sb.append("Lens Y(down)\tmm");
				for (int imgIndex=0;imgIndex<numImages;imgIndex++){
//					int imgNum=imgIndices[imgIndex]; // image number
					sb.append("\t"+IJ.d2s(lensCoordinates[imgIndex][1],3+extraDecimals));
				}
				sb.append("\n");
				sb.append("Lens Z(into)\tmm");
				for (int imgIndex=0;imgIndex<numImages;imgIndex++){
//					int imgNum=imgIndices[imgIndex]; // image number
					sb.append("\t"+IJ.d2s(lensCoordinates[imgIndex][2],3+extraDecimals));
				}
				sb.append("\n");
	        }
			if (showExtrinsicParameters){
				for (int parNumber=0;parNumber<lensDistortionParameters.getExtrinsicNames().length;parNumber++){
					sb.append(
							lensDistortionParameters.getExtrinsicNames()[parNumber]+"\t"+
							lensDistortionParameters.getExtrinsicUnits()[parNumber]);
					for (int imgIndex=0;imgIndex<numImages;imgIndex++){
						sb.append("\t"+IJ.d2s(extrinsic[imgIndex][parNumber],3+extraDecimals)); // TODO: make an array of decimals per parameter
					}
					sb.append("\n");
				}
			}
		}
	    new TextWindow("Camera/lens parameters", header, sb.toString(), 500,900);
	}
Andrey Filippov's avatar
Andrey Filippov committed
5385

Andrey Filippov's avatar
Andrey Filippov committed
5386 5387 5388 5389 5390 5391 5392 5393
	/**
	 * Calculate differences vector
	 * @param fX vector of calculated pixelX,pixelY on the sensors
	 * @return same dimension vector of differences from this.Y (measured grid pixelxX, pixelY)
	 */
	public double [] calcYminusFx(double [] fX){
		double [] result=this.Y.clone();
		for (int i=0;i<result.length;i++) result[i]-=fX[i];
Andrey Filippov's avatar
Andrey Filippov committed
5394
	    return result;
Andrey Filippov's avatar
Andrey Filippov committed
5395 5396
	}
	/**
Andrey Filippov's avatar
Andrey Filippov committed
5397
	 * Calcualte partial differences vector
Andrey Filippov's avatar
Andrey Filippov committed
5398 5399 5400
	 * @param fX vector of reprojected pixelX,pixelY on the sensors (number of elements - double number of points
	 * @param startIndex start index to extract (even number, twice point index)
	 * @param endIndex end index (1 greater than the last to extract)
Andrey Filippov's avatar
Andrey Filippov committed
5401
	 * @return partial differences (measured/corrected -reprojected), twice number of points long
Andrey Filippov's avatar
Andrey Filippov committed
5402 5403 5404 5405 5406 5407 5408
	 */
	public double [] calcYminusFx(double [] fX, int startIndex, int endIndex){
		double [] result=new double [endIndex-startIndex];
		for (int i=0;i<result.length;i++) {
			int index=startIndex+i;
			result[i]=this.Y[index]-fX[index];
		}
Andrey Filippov's avatar
Andrey Filippov committed
5409
		return result;
Andrey Filippov's avatar
Andrey Filippov committed
5410 5411
	}

Andrey Filippov's avatar
Andrey Filippov committed
5412

Andrey Filippov's avatar
Andrey Filippov committed
5413 5414 5415
	/**
	 * Calculate the RMS from the differences vector
	 * @param diff - differences vector
Andrey Filippov's avatar
Andrey Filippov committed
5416
	 * @return RMS for the mean error (in sensor pixels)
Andrey Filippov's avatar
Andrey Filippov committed
5417 5418 5419
	 */
	public double calcError(double [] diff){
		double result=0;
5420
		double sumw = 0;
Andrey Filippov's avatar
Andrey Filippov committed
5421
		if (this.weightFunction!=null) {
5422 5423 5424 5425 5426
			for (int i=0;i<diff.length;i++) if (!Double.isNaN(diff[i])){
				result+=diff[i]*diff[i]*this.weightFunction[i];
				sumw += this.weightFunction[i];
			}
			result/=sumw; // this.sumWeights;
Andrey Filippov's avatar
Andrey Filippov committed
5427
		} else {
5428 5429 5430 5431 5432
			for (int i=0;i<diff.length;i++)  if (!Double.isNaN(diff[i])){
				result+=diff[i]*diff[i];
				sumw += 1.0;
			}
			result/=sumw; // diff.length;
Andrey Filippov's avatar
Andrey Filippov committed
5433 5434 5435 5436
		}
		return Math.sqrt(result)*this.RMSscale;
	}

Andrey Filippov's avatar
Andrey Filippov committed
5437

Andrey Filippov's avatar
Andrey Filippov committed
5438 5439
	public double calcErrorDiffY(double [] fX){
		double result=0;
5440
		double dbg_maxdiff = 0.0+0.0;
Andrey Filippov's avatar
Andrey Filippov committed
5441
		if (this.weightFunction!=null) {
5442
			for (int i=0;i<fX.length;i++)if (this.weightFunction[i] != 0.0){
Andrey Filippov's avatar
Andrey Filippov committed
5443
				double diff=this.Y[i]-fX[i];
5444 5445 5446 5447
				if ((this.debugLevel>1) &&(Math.abs(diff) > dbg_maxdiff)) {
					System.out.println("i="+i+", diff="+diff+" y="+this.Y[i]+" fX="+fX[i]+ " w="+this.weightFunction[i]);
					dbg_maxdiff = Math.abs(diff);
				}
Andrey Filippov's avatar
Andrey Filippov committed
5448 5449 5450 5451 5452 5453
				result+=diff*diff*this.weightFunction[i];
			}
			result/=this.sumWeights;
		} else {
			for (int i=0;i<fX.length;i++){
				double diff=this.Y[i]-fX[i];
5454 5455 5456
//				if (Math.abs(diff) > 1.0) {
//					System.out.print("");
//				}
Andrey Filippov's avatar
Andrey Filippov committed
5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472
				result+=diff*diff;
			}
			result/=fX.length;
		}
		return Math.sqrt(result)*this.RMSscale;
	}
	public double calcErrorDiffY(
			double [] fX,
			double [] extraWeightedErrors,
			double [] extraWeights){
		double result=0;
		double effectiveWeight;
		if (this.weightFunction!=null) {
			effectiveWeight=this.sumWeights;
			for (int i=0;i<fX.length;i++){
				double diff=this.Y[i]-fX[i];
5473 5474 5475
//				if (Math.abs(diff) > 1.0) {
//					System.out.print("");
//				}
Andrey Filippov's avatar
Andrey Filippov committed
5476 5477 5478 5479 5480 5481
				result+=diff*diff*this.weightFunction[i];
			}
		} else {
			effectiveWeight=fX.length;
			for (int i=0;i<fX.length;i++){
				double diff=this.Y[i]-fX[i];
5482 5483 5484
//				if (Math.abs(diff) > 1.0) {
//					System.out.print("");
//				}
Andrey Filippov's avatar
Andrey Filippov committed
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
				result+=diff*diff;
			}
		}
		if ((extraWeightedErrors!=null) && (extraWeights!=null)) {
			for (int i=0;i<extraWeightedErrors.length;i++){
				result+=extraWeightedErrors[i];
				effectiveWeight+=extraWeights[i];
			}
		}
		result/=effectiveWeight;
		return Math.sqrt(result)*this.RMSscale;
	}

	public void resetBadNodes(){
		for (int imgNum=0;imgNum<fittingStrategy.distortionCalibrationData.gIP.length;imgNum++) if (fittingStrategy.distortionCalibrationData.gIP[imgNum]!=null){
			fittingStrategy.distortionCalibrationData.gIP[imgNum].resetBadNodes();
		}
	}

    public int markBadNodes(
//    		int numSeries,
    		double removeOverRMS,
    		double removeOverRMSNonweighted,
    		boolean verbose,
    		int debugLevel){
    	int debugThreshold=2;
//		this.seriesNumber=series;
    	resetBadNodes(); // before calculating weight function
Andrey Filippov's avatar
Andrey Filippov committed
5513
	    initFittingSeries(false,this.filterForAll,this.seriesNumber); // recalculate
Andrey Filippov's avatar
Andrey Filippov committed
5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 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 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587
		this.currentfX=calculateFxAndJacobian(this.currentVector, false); // is it always true here (this.jacobian==null)
    	int totalBadNodes=0;
		boolean [] selectedImages=fittingStrategy.selectedImages();
		double [] diff=calcYminusFx(this.currentfX);
		int index=0;
		for (int imgNum=0;imgNum<selectedImages.length;imgNum++) {
			double e2 =0.0;
//			errors[imgNum]=0.0;
			if (selectedImages[imgNum]) {
				int numThisRemoved=0;
				int len=fittingStrategy.distortionCalibrationData.gIP[imgNum].pixelsUV.length*2;
				double w=0;
				int nw=0;
				if (this.weightFunction!=null) {
					for (int i=index;i<index+len;i++) {
						e2+=diff[i]*diff[i]*this.weightFunction[i];
						w+=this.weightFunction[i];
						if (this.weightFunction[i]>0.0) nw++;
					}
				} else {
					for (int i=index;i<index+len;i++) {
						e2+=diff[i]*diff[i];
						w+=1.0;
						nw++;
					}
				}
				if (w>0.0) {
//					e2/=w;
					double threshold2Weighted=   2.0*removeOverRMS*removeOverRMS*e2/nw; // 2.0 because x^2+y^2
					double threshold2NonWeighted=2.0*removeOverRMSNonweighted*removeOverRMSNonweighted*e2/w; // 2.0 because x^2+y^2
					if (debugLevel>debugThreshold){
						boolean someRemoved=false;
						for (int i=index;i<index+len;i+=2) {
							e2=(diff[i]*diff[i]+ diff[i+1]*diff[i+1]);
							if ((e2>threshold2NonWeighted) || ((this.weightFunction!=null) && ((e2*this.weightFunction[i]) > threshold2Weighted )) ) {
								double ww=(this.weightFunction==null)?1.0:(this.weightFunction[i]);
								if (ww>0.0) someRemoved=true;

							}
						}
						if (someRemoved || (debugLevel>2)) System.out.println("imgNum="+imgNum+" len="+len+" e2/w="+(e2/w)+" w="+w+" e2/nw="+(e2/nw)+
								" threshold2Weighted="+threshold2Weighted+" threshold2NonWeighted="+threshold2NonWeighted);
					}

					for (int i=index;i<index+len;i+=2) {
						e2=(diff[i]*diff[i]+ diff[i+1]*diff[i+1]);
						if ((e2>threshold2NonWeighted) || ((this.weightFunction!=null) && ((e2*this.weightFunction[i]) > threshold2Weighted )) ) {
							double ww=(this.weightFunction==null)?1.0:(this.weightFunction[i]);
							int pointIndex=(i-index)/2;
							if (ww>0.0) {
								fittingStrategy.distortionCalibrationData.gIP[imgNum].setBadNode(pointIndex);
								numThisRemoved++;
								if (debugLevel>debugThreshold){
									int iu=fittingStrategy.distortionCalibrationData.gIP[imgNum].pixelsUV[pointIndex][0];
									int iv=fittingStrategy.distortionCalibrationData.gIP[imgNum].pixelsUV[pointIndex][1];
									System.out.println(numThisRemoved+": "+pointIndex +
											" uv="+iu+":"+iv+
											" e2="+e2+" ww="+ww+" e2w="+
											(e2*ww)+" ["+diff[i]+":"+diff[i+1]+"]");
								}
							}
						}
					}
					if (verbose && (numThisRemoved>0)) {
						System.out.println("Image "+imgNum+": removed "+numThisRemoved+" nodes over threshold");
					}
					totalBadNodes+=numThisRemoved;
				}
				index+=len;
			}
		}
    	return totalBadNodes;
    }
	public boolean showImageReprojectionErrorsDialog( int debugLevel){
5588
		boolean eachImageInSet=false;
5589
		boolean showGrids = false;
Andrey Filippov's avatar
Andrey Filippov committed
5590 5591 5592 5593
	    GenericDialog gd = new GenericDialog("Show Reprojection errors for image/image set/image selection");
		gd.addNumericField("Series number for image selection (-1 - all enabled images)", -1, 0);
		gd.addNumericField("Single image number to show (<0 - do not select)", -1,0);
		gd.addNumericField("Image set number to show (<0 - do not select)", -1,0);
5594
		gd.addCheckbox("Open each image in the set",     eachImageInSet);
Andrey Filippov's avatar
Andrey Filippov committed
5595
		gd.addCheckbox("Ask for weight function filter",     this.askFilter);
5596
		gd.addCheckbox("Show grid images",                   showGrids);
Andrey Filippov's avatar
Andrey Filippov committed
5597 5598 5599 5600 5601 5602
//		gd.addNumericField("Weight function filter (-1 - use default for all )",-1,0);
	    gd.showDialog();
	    if (gd.wasCanceled()) return false;
	    this.seriesNumber=        (int) gd.getNextNumber();
	    int singleImageNumber=    (int) gd.getNextNumber();
	    int imageSetNumber=       (int) gd.getNextNumber();
5603
	    eachImageInSet=                 gd.getNextBoolean();
Andrey Filippov's avatar
Andrey Filippov committed
5604 5605
	    this.askFilter=                 gd.getNextBoolean();
//	    int weightFunctionFilter= (int) gd.getNextNumber();
5606
	    showGrids =                  gd.getNextBoolean();
Andrey Filippov's avatar
Andrey Filippov committed
5607 5608 5609 5610 5611 5612
		int filter=this.filterForAll;
		if (this.askFilter) filter=selectFilter(filter);
	    int [] imageNumbers = null;
	    if (singleImageNumber>=0){
	    	imageNumbers=new int [1];
	    	imageNumbers[0]=singleImageNumber;
5613 5614 5615
	    	if (showGrids) {
	    		this.fittingStrategy.distortionCalibrationData.gIP[singleImageNumber].showGridImage();
	    	}
Andrey Filippov's avatar
Andrey Filippov committed
5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627
	    } else if (imageSetNumber>=0){
	    	int numInSet=0;
	    	for (int nChn=0;nChn<this.fittingStrategy.distortionCalibrationData.gIS[imageSetNumber].imageSet.length;nChn++){
	    		if (this.fittingStrategy.distortionCalibrationData.gIS[imageSetNumber].imageSet[nChn]!=null) numInSet++;
	    	}
	    	imageNumbers=new int [numInSet];
	    	numInSet=0;
	    	for (int nChn=0;nChn<this.fittingStrategy.distortionCalibrationData.gIS[imageSetNumber].imageSet.length;nChn++){
	    		if (this.fittingStrategy.distortionCalibrationData.gIS[imageSetNumber].imageSet[nChn]!=null) {
	    			imageNumbers[numInSet++]=this.fittingStrategy.distortionCalibrationData.gIS[imageSetNumber].imageSet[nChn].imgNumber;
	    		}
	    	}
5628 5629 5630 5631 5632 5633 5634

	    	if (showGrids) {
	    		for (int nChn=0;nChn<imageNumbers.length;nChn++){
	    			int img_num= imageNumbers[nChn];
	    			this.fittingStrategy.distortionCalibrationData.gIP[img_num].showGridImage();
	    		}
	    	}
5635 5636 5637 5638 5639 5640 5641 5642 5643 5644
	    	if (eachImageInSet){
	    		for (int nChn=0;nChn<imageNumbers.length;nChn++){
	    			int [] imageNumber={imageNumbers[nChn]};
	    			showImageReprojectionErrors(
	    		    		imageNumber, // if null - use all images in a series
	    		    		filter, //weightFunctionFilter,
	    		    		debugLevel);
	    		}
	    		// Do not exit, continue and show combine reprojection errors for all set
	    	}
Andrey Filippov's avatar
Andrey Filippov committed
5645 5646 5647 5648 5649 5650
	    }
	    showImageReprojectionErrors(
	    		imageNumbers, // if null - use all images in a series
	    		filter, //weightFunctionFilter,
	    		debugLevel);
	    return true;
Andrey Filippov's avatar
Andrey Filippov committed
5651

Andrey Filippov's avatar
Andrey Filippov committed
5652
	}
Andrey Filippov's avatar
Andrey Filippov committed
5653

Andrey Filippov's avatar
Andrey Filippov committed
5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666
    public void showImageReprojectionErrors(
    		int [] imageNumbers, // if null - use all images in a series
    		int filter,
    		int debugLevel){
    	if (filter<0) filter=this.filterForAll;
    	if (debugLevel>1) {
    		System.out.print("showImageReprojectionErrors: ");
    		if (imageNumbers!=null){
    			for (int i=0;i<imageNumbers.length;i++) System.out.print(" "+imageNumbers[i]);
    		} else {
        		System.out.println("imageNumbers is NULL");
    		}
    	}
Andrey Filippov's avatar
Andrey Filippov committed
5667
	    initFittingSeries(false, filter,this.seriesNumber); // recalculate
Andrey Filippov's avatar
Andrey Filippov committed
5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679
		this.currentfX=calculateFxAndJacobian(this.currentVector, false); // is it always true here (this.jacobian==null)
		boolean [] tmpSelectedImages=fittingStrategy.selectedImages();
		boolean [] selectedImages;
		double [] diff=calcYminusFx(this.currentfX);
		if ((imageNumbers!=null) && (imageNumbers.length>0)){
			selectedImages=new boolean[tmpSelectedImages.length];
			for (int i=0;i<selectedImages.length;i++) selectedImages[i]=false;
			for (int i=0;i<imageNumbers.length;i++) if ((imageNumbers[i]>=0) && (imageNumbers[i]<=selectedImages.length)){
				selectedImages[imageNumbers[i]]=tmpSelectedImages[imageNumbers[i]];
			}
		} else {
			selectedImages=tmpSelectedImages;
5680 5681 5682 5683 5684 5685 5686
			int numImg = 0;
			for (int i=0;i<selectedImages.length;i++) if (selectedImages[i]) numImg++;
			imageNumbers = new int [numImg];
			numImg = 0;
			for (int i=0;i<selectedImages.length;i++)  if (selectedImages[i]) {
				imageNumbers[numImg++] = i;
			}
Andrey Filippov's avatar
Andrey Filippov committed
5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734
		}
		int width= getGridWidth();
		int height=getGridHeight();
		double [][] imgData=new double[5][height * width]; // dPX, dPY, err
		String [] titles={"dX","dY", "Err","W_Err","Weight"};
		for (int i=0;i<(width*height);i++){
			for (int c=0;c<imgData.length;c++) imgData[c][i]=Double.NaN;
		}
		for (int imgNum=0;imgNum<selectedImages.length;imgNum++) if (selectedImages[imgNum]){
			int len=fittingStrategy.distortionCalibrationData.gIP[imgNum].pixelsUV.length;
			int index=this.imageStartIndex[imgNum]; // pair index
			for (int i=0;i<len;i++){
				int u=fittingStrategy.distortionCalibrationData.gIP[imgNum].pixelsUV[i][0]+this.patternParameters.U0;
				int v=fittingStrategy.distortionCalibrationData.gIP[imgNum].pixelsUV[i][1]+this.patternParameters.V0;
				int vu=u+width*v;
				double w=this.weightFunction[2*(index+i)];
				double dx=diff[2*(index+i)];
				double dy=diff[2*(index+i)+1];
				double e2=dx*dx+dy*dy;
				if (w>0.0){
					if (Double.isNaN(imgData[0][vu])) for (int c=0;c<imgData.length;c++) imgData[c][vu]=0.0;
					imgData[0][vu]+=dx*w;
					imgData[1][vu]+=dy*w;
					imgData[2][vu]+=e2*w;
					imgData[4][vu]+=w;
				}
			}
		}
		int nonEmpty=0;
	    double sumWeights=0.0;
	    for (int vu=0;vu<(width*height);vu++) if (!Double.isNaN(imgData[0][vu])){
	    	nonEmpty++;
	    	sumWeights+=imgData[4][vu];
	    }
		if ((nonEmpty==0) || (sumWeights==0.0)){
			System.out.println("showImageReprojectionErrors():  No non-empty points");
			return;
		}
		double averageWeight=sumWeights/nonEmpty;
	    for (int vu=0;vu<(width*height);vu++) if (!Double.isNaN(imgData[0][vu])){
	    	imgData[0][vu]/=imgData[4][vu];
	    	imgData[1][vu]/=imgData[4][vu];
	    	imgData[2][vu] =Math.sqrt(imgData[2][vu]/imgData[4][vu]);
	    	imgData[3][vu] =Math.sqrt(imgData[2][vu]/averageWeight);
	    }
	    String title="RPRJ";
	    int maxNumInTitle=10;
	    for (int i=0;(i<imageNumbers.length) && (i<maxNumInTitle); i++) title+="-"+imageNumbers[i];
5735
		ShowDoubleFloatArrays.showArrays(
Andrey Filippov's avatar
Andrey Filippov committed
5736 5737 5738 5739 5740 5741 5742
				imgData,
				width,
				height,
				true,
				title,
				titles);
    }
Andrey Filippov's avatar
Andrey Filippov committed
5743 5744 5745 5746




Andrey Filippov's avatar
Andrey Filippov committed
5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794
	public double [] calcErrors(double [] diff){
		boolean [] selectedImages=fittingStrategy.selectedImages();
		double [] errors=new double [selectedImages.length];
		int index=0;
		for (int imgNum=0;imgNum<selectedImages.length;imgNum++) {
			errors[imgNum]=Double.NaN; //0.0;
			if (selectedImages[imgNum]) {
				errors[imgNum]=0.0;
				int len=fittingStrategy.distortionCalibrationData.gIP[imgNum].pixelsUV.length*2;
				double w=0;
				if (this.weightFunction!=null) {
					for (int i=index;i<index+len;i++) {
						errors[imgNum]+=diff[i]*diff[i]*this.weightFunction[i];
						w+=this.weightFunction[i];
					}
				} else {
					for (int i=index;i<index+len;i++) {
						errors[imgNum]+=diff[i]*diff[i];
						w+=1.0;
					}
				}
				if (w>0.0) {
					errors[imgNum]/=w;
					errors[imgNum]=Math.sqrt(errors[imgNum])*this.RMSscale;
				} else {
					errors[imgNum]=Double.NaN;
				}
				index+=len;
			}
		}
		return errors;
	}
	/**
	 * Calculate number of used grid points (x/y pairs) for each image in the current fitting series
	 * @return
	 */
	public int [] calcNumPairs(){
		boolean [] selectedImages=fittingStrategy.selectedImages();
		int [] numPairs=new int [selectedImages.length];
		for (int imgNum=0;imgNum<selectedImages.length;imgNum++) {
			numPairs[imgNum]=0;
			if (selectedImages[imgNum]) {
				numPairs[imgNum]=fittingStrategy.distortionCalibrationData.gIP[imgNum].pixelsUV.length;
			}
		}
		return numPairs;
	}
	/**
Andrey Filippov's avatar
Andrey Filippov committed
5795
	 * Calculate corrections to the current parameter values
Andrey Filippov's avatar
Andrey Filippov committed
5796 5797 5798 5799 5800 5801 5802 5803
	 * @param fX calculated grid pixelX, PixelY for current parameter values
	 * @param lambda damping parameter
	 * @return array of deltas to be applied to the coefficients
	 */
	public double [] solveLevenbergMarquardtOldNotUsed(double [] fX, double lambda){
		// calculate JtJ
		double [] diff=calcYminusFx(fX);
		int numPars=this.jacobian.length; // number of parameters to be adjusted
Andrey Filippov's avatar
Andrey Filippov committed
5804
		int length=diff.length; // should be the same as this.jacobian[0].length
Andrey Filippov's avatar
Andrey Filippov committed
5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841
	    double [][] JtByJmod=new double [numPars][numPars]; //Transposed Jacobian multiplied by Jacobian
	    double [] JtByDiff=new double [numPars];
	    for (int i=0;i<numPars;i++) for (int j=i;j<numPars;j++){
	    	JtByJmod[i][j]=0.0;
	    	if (this.weightFunction!=null)
	    		for (int k=0;k<length;k++) JtByJmod[i][j]+=this.jacobian[i][k]*this.jacobian[j][k]*this.weightFunction[k];
	    	else
	    		for (int k=0;k<length;k++) JtByJmod[i][j]+=this.jacobian[i][k]*this.jacobian[j][k];
	    }
	    for (int i=0;i<numPars;i++) { // subtract lambda*diagonal , fill the symmetrical half below the diagonal
	    	JtByJmod[i][i]+=lambda*JtByJmod[i][i]; //Marquardt mod
	    	for (int j=0;j<i;j++) JtByJmod[i][j]= JtByJmod[j][i]; // it is symmetrical matrix, just copy
	    }
	    for (int i=0;i<numPars;i++) {
	    	JtByDiff[i]=0.0;
	    	if (this.weightFunction!=null)
		    	for (int k=0;k<length;k++) JtByDiff[i]+=this.jacobian[i][k]*diff[k]*this.weightFunction[k];
	    	else
		    	for (int k=0;k<length;k++) JtByDiff[i]+=this.jacobian[i][k]*diff[k];

	    }
//	    M*Ma=Mb
	    Matrix M=new Matrix(JtByJmod);
//  public Matrix (double vals[], int m) {
/*
		if (this.debugLevel>2) {
			for (int n=0;n<fittingStrategy.distortionCalibrationData.pixelsXY.length;n++) {
				for (int i=0;i<fittingStrategy.distortionCalibrationData.pixelsXY[n].length;i++){
					System.out.println(n+":"+i+"  "+
							fittingStrategy.distortionCalibrationData.pixelsUV[n][i][0]+"/"+
							fittingStrategy.distortionCalibrationData.pixelsUV[n][i][1]+"  "+
							IJ.d2s(fittingStrategy.distortionCalibrationData.pixelsXY[n][i][0], 2)+"/"+
							IJ.d2s(fittingStrategy.distortionCalibrationData.pixelsXY[n][i][1], 2)
					);
				}
			}
		}
Andrey Filippov's avatar
Andrey Filippov committed
5842

Andrey Filippov's avatar
Andrey Filippov committed
5843
 */
Andrey Filippov's avatar
Andrey Filippov committed
5844

Andrey Filippov's avatar
Andrey Filippov committed
5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868
		if (this.debugLevel>3) {
//		if (this.debugLevel>1) {
			System.out.println("Jt*J -lambda* diag(Jt*J), lambda="+lambda+":");
			M.print(10, 5);
		}

	    Matrix Mb=new Matrix(JtByDiff,numPars); // single column
	    if (!(new LUDecomposition(M)).isNonsingular()){
	    	double [][] arr=M.getArray();
			System.out.println("Singular Matrix "+arr.length+"x"+arr[0].length);
			// any rowsx off all 0.0?
			for (int n=0;n<arr.length;n++){
				boolean zeroRow=true;
				for (int i=0;i<arr[n].length;i++) if (arr[n][i]!=0.0){
					zeroRow=false;
					break;
				}
				if (zeroRow){
					System.out.println("Row of all zeros: "+n);
				}
			}
//			M.print(10, 5);
	    	return null;
	    }
Andrey Filippov's avatar
Andrey Filippov committed
5869

Andrey Filippov's avatar
Andrey Filippov committed
5870 5871 5872 5873 5874 5875
//	    Matrix Ma=M.solve(Mb); // singular
	    if (this.debugLevel>0) System.out.print("Running Cholesky decomposition...");
	    long decompositionTime=System.nanoTime();
	    Matrix Ma=M.chol().solve(Mb); // singular
	    decompositionTime=System.nanoTime()-decompositionTime;
	    if (this.debugLevel>0) System.out.println("done in "+(decompositionTime/1E9)+" sec");
Andrey Filippov's avatar
Andrey Filippov committed
5876

Andrey Filippov's avatar
Andrey Filippov committed
5877 5878 5879
	    return Ma.getColumnPackedCopy();
	}

Andrey Filippov's avatar
Andrey Filippov committed
5880 5881


Andrey Filippov's avatar
Andrey Filippov committed
5882 5883 5884 5885
	public LMAArrays calculateJacobianArrays(double [] fX){
		// calculate JtJ
		double [] diff=calcYminusFx(fX);
		int numPars=this.jacobian.length; // number of parameters to be adjusted
Andrey Filippov's avatar
Andrey Filippov committed
5886
		int length=diff.length; // should be the same as this.jacobian[0].length
Andrey Filippov's avatar
Andrey Filippov committed
5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907
	    double [][] JtByJmod=new double [numPars][numPars]; //Transposed Jacobian multiplied by Jacobian
	    double [] JtByDiff=new double [numPars];
	    for (int i=0;i<numPars;i++) for (int j=i;j<numPars;j++){
	    	JtByJmod[i][j]=0.0;
	    	if (this.weightFunction!=null)
	    		for (int k=0;k<length;k++) JtByJmod[i][j]+=this.jacobian[i][k]*this.jacobian[j][k]*this.weightFunction[k];
	    	else
	    		for (int k=0;k<length;k++) JtByJmod[i][j]+=this.jacobian[i][k]*this.jacobian[j][k];
	    }
	    for (int i=0;i<numPars;i++) { // subtract lambda*diagonal , fill the symmetrical half below the diagonal
//	    	JtByJmod[i][i]+=lambda*JtByJmod[i][i]; //Marquardt mod
	    	for (int j=0;j<i;j++) JtByJmod[i][j]= JtByJmod[j][i]; // it is symmetrical matrix, just copy
	    }
	    for (int i=0;i<numPars;i++) {
	    	JtByDiff[i]=0.0;
	    	if (this.weightFunction!=null)
		    	for (int k=0;k<length;k++) JtByDiff[i]+=this.jacobian[i][k]*diff[k]*this.weightFunction[k];
	    	else
		    	for (int k=0;k<length;k++) JtByDiff[i]+=this.jacobian[i][k]*diff[k];

	    }
Andrey Filippov's avatar
Andrey Filippov committed
5908

Andrey Filippov's avatar
Andrey Filippov committed
5909 5910 5911 5912
   		LMAArrays lMAArrays = new LMAArrays();
   		lMAArrays.jTByJ=JtByJmod;
   		lMAArrays.jTByDiff=JtByDiff;
   		return lMAArrays;
Andrey Filippov's avatar
Andrey Filippov committed
5913 5914
/*

Andrey Filippov's avatar
Andrey Filippov committed
5915 5916 5917
//	    M*Ma=Mb
	    Matrix M=new Matrix(JtByJmod);
//  public Matrix (double vals[], int m) {
Andrey Filippov's avatar
Andrey Filippov committed
5918

Andrey Filippov's avatar
Andrey Filippov committed
5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932
		if (this.debugLevel>2) {
//		if (this.debugLevel>1) {
			System.out.println("Jt*J -lambda* diag(Jt*J), lambda="+lambda+":");
			M.print(10, 5);
		}

	    Matrix Mb=new Matrix(JtByDiff,numPars); // single column
	    if (!(new LUDecomposition(M)).isNonsingular()){
			System.out.println("Singular Matrix");
			M.print(10, 5);
	    	return null;
	    }
	    Matrix Ma=M.solve(Mb); // singular
	    return Ma.getColumnPackedCopy();
Andrey Filippov's avatar
Andrey Filippov committed
5933
*/
Andrey Filippov's avatar
Andrey Filippov committed
5934
	}
Andrey Filippov's avatar
Andrey Filippov committed
5935 5936 5937



Andrey Filippov's avatar
Andrey Filippov committed
5938 5939
	public LMAArrays calculateJacobianArrays (
			final boolean [] selectedImages, // selected images to process
Andrey Filippov's avatar
Andrey Filippov committed
5940
			final double [] Y,  // should be initialized
Andrey Filippov's avatar
Andrey Filippov committed
5941 5942 5943 5944 5945 5946
			final double [] fX, // should be initialized to correct length, data is not needed
			final double [] vector,  // parameters vector
			final int    [] imageStartIndex, // index of the first point of each image (including extra element in the end so n+1 is always valid)
			final double [][] patternXYZ, // this.targetXYZ
			final double [] weightFunction, // may be null - make it twice smaller? - same for X and Y?
			final LensDistortionParameters lensDistortionParametersProto,
5947
			final double [][] dTA_dUV, // null or double [][] to return averaged per-image {{dU/dAz,dU/dTl}{dV/dAz,dV/dTl}}
Andrey Filippov's avatar
Andrey Filippov committed
5948 5949
			int threadsMax,
			boolean updateStatus){
Andrey Filippov's avatar
Andrey Filippov committed
5950

Andrey Filippov's avatar
Andrey Filippov committed
5951 5952 5953 5954
		// calculate JtJ
//		double [] diff=calcYminusFx(fX);
//		int numPars=this.jacobian.length; // number of parameters to be adjusted
		final int numPars=vector.length; // number of parameters to be adjusted
Andrey Filippov's avatar
Andrey Filippov committed
5955 5956
//		int length=diff.length; // should be the same as this.jacobian[0].length
//		final int length=fX.length; // should be the same as this.jacobian[0].length
Andrey Filippov's avatar
Andrey Filippov committed
5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975
		final double [][] JtByJmod=new double [numPars][numPars]; //Transposed Jacobian multiplied by Jacobian
		final double [] JtByDiff=new double [numPars];
	    for (int i=0;i<numPars;i++){
	    	JtByDiff[i]=0.0;
	    	for (int j=0;j<numPars;j++) JtByJmod[i][j]=0.0;
	    }
	    final int debugLevel=this.debugLevel;
   		final Thread[] threads = newThreadArray(threadsMax);
   		final AtomicInteger imageNumberAtomic = new AtomicInteger(0);
   		final AtomicInteger imageFinishedAtomic = new AtomicInteger(0);
   		final double [] progressValues=new double [selectedImages.length];
   		int numSelectedImages=0;
   		for (int i=0;i<selectedImages.length;i++) if (selectedImages[i]) numSelectedImages++;
   		int selectedIndex=0;
   		for (int i=0;i<selectedImages.length;i++) {
   			progressValues[i]=(selectedIndex+1.0)/numSelectedImages;
   			if (selectedImages[i]) selectedIndex++;
   			if (selectedIndex>=numSelectedImages) selectedIndex--;
   		}
5976 5977
   		final double [][][] dUV_image =   (dTA_dUV != null) ? new double [selectedImages.length][][]: null;
   		final double []     dUV_weights = (dTA_dUV != null) ? new double [selectedImages.length]: null;
Andrey Filippov's avatar
Andrey Filippov committed
5978 5979 5980 5981
   		final AtomicInteger stopRequested=this.stopRequested;
		final AtomicBoolean interruptedAtomic=new AtomicBoolean();
   		for (int ithread = 0; ithread < threads.length; ithread++) {
   			threads[ithread] = new Thread() {
Andrey Filippov's avatar
Andrey Filippov committed
5982 5983
   				@Override
				public void run() {
Andrey Filippov's avatar
Andrey Filippov committed
5984 5985 5986
   					LensDistortionParameters lensDistortionParameters=lensDistortionParametersProto.clone(); // see - if that is needed - maybe new is OK
   					//   					LensDistortionParameters lensDistortionParameters= new LensDistortionParameters();
   					for (int numImage=imageNumberAtomic.getAndIncrement(); (numImage<selectedImages.length) && !interruptedAtomic.get();numImage=imageNumberAtomic.getAndIncrement()){
5987 5988 5989 5990 5991
   						int length=2*(imageStartIndex[numImage+1]-imageStartIndex[numImage]);
   						if (length == 0) {
   							continue;
   						}
   						int start= 2*imageStartIndex[numImage];
Andrey Filippov's avatar
Andrey Filippov committed
5992 5993 5994 5995 5996 5997 5998 5999 6000
   						double [][] partialJacobian= calculatePartialFxAndJacobian(
   								numImage,      // number of grid image
   								vector,  // parameters vector
   								patternXYZ, // this.targetXYZ
   								fX,     // non-overlapping segments will be filled
   								imageStartIndex, // start index in patternXYZ array (length - difference to the next, includes extra last element)
   								lensDistortionParameters, // initialize one per each tread? Or for each call?
   								true); // when false, modifies only this.lensDistortionParameters.*

6001 6002
//   						int length=2*(imageStartIndex[numImage+1]-imageStartIndex[numImage]);
//   						int start= 2*imageStartIndex[numImage];
Andrey Filippov's avatar
Andrey Filippov committed
6003 6004 6005

   						double [][] partialJtByJmod=new double [numPars][numPars]; // out of heap space
   						double []   partialJtByDiff=new double [numPars];
Andrey Filippov's avatar
Andrey Filippov committed
6006

Andrey Filippov's avatar
Andrey Filippov committed
6007 6008 6009 6010 6011 6012 6013 6014
   						for (int i=0;i<numPars;i++) if (partialJacobian[i]!=null) {
   							for (int j=i;j<numPars;j++) if (partialJacobian[j]!=null) {
   								partialJtByJmod[i][j]=0.0;
   								if (weightFunction!=null) {
   									for (int k=0;k<length;k++) partialJtByJmod[i][j]+=partialJacobian[i][k]*partialJacobian[j][k]*weightFunction[start+k];
   								} else {
   									for (int k=0;k<length;k++) partialJtByJmod[i][j]+=partialJacobian[i][k]*partialJacobian[j][k];
   								}
Andrey Filippov's avatar
Andrey Filippov committed
6015
   							}
Andrey Filippov's avatar
Andrey Filippov committed
6016 6017 6018 6019 6020 6021 6022 6023
   						}

   						double [] partialDiff=new double[length];
   						for (int k=0;k<length;k++) 	partialDiff[k]=Y[start+k]-fX[start+k];

   						for (int i=0;i<numPars;i++) if (partialJacobian[i]!=null) {
   							partialJtByDiff[i]=0.0;
   							if (weightFunction!=null)
6024 6025 6026 6027 6028 6029 6030
   								for (int k=0;k<length;k++) {
   									if (Double.isNaN(partialDiff[k])) {
   										System.out.println("calculateJacobianArrays() BUG1:partialDiff["+k+"]=NaN, i="+i);
   									} else {
   										partialJtByDiff[i]+=partialJacobian[i][k]*partialDiff[k]*weightFunction[start+k];
   									}
   								}
Andrey Filippov's avatar
Andrey Filippov committed
6031
   							else
6032 6033 6034 6035 6036 6037 6038
   								for (int k=0;k<length;k++) {
   									if (Double.isNaN(partialDiff[k])) {
   										System.out.println("calculateJacobianArrays() BUG2:partialDiff["+k+"]=NaN, i="+i);
   									} else {
   										partialJtByDiff[i]+=partialJacobian[i][k]*partialDiff[k];
   									}
   								}
Andrey Filippov's avatar
Andrey Filippov committed
6039 6040

   						}
6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116
   						int par_gh = -1;
   						int par_ga = -1;
   						if (dUV_image != null) {
   							dUV_image[numImage] = null; //new double [2][2];
   							for (int i = 0; i < numPars; i++) {
   								int parNum=fittingStrategy.parameterMap[i][1];
   								if (parNum == fittingStrategy.distortionCalibrationData.index_gh) {
   									par_gh = i;
   								} else if (parNum == fittingStrategy.distortionCalibrationData.index_ga) {
   									par_ga = i;
   								}
   							}
   							if ((par_gh >= 0) && (par_ga >= 0)) { // both defined
   								// partialJacobian[par_gh][2*k  ] dPx/dGh
   								// partialJacobian[par_gh][2*k+1] dPy/dGh
   								// partialJacobian[par_gh][2*k  ] dPx/dGa
   								// partialJacobian[par_gh][2*k+1] dPy/dGa
   								// d3780:	public void updateGridToPointer(ImagePlus imp_grid, double[][] xyuv) {
   								// find average dX/dU, dY/dU, dX/dV, dY/dV 
   								
   								
   								PolynomialApproximation polynomialApproximation =new PolynomialApproximation(0);// no debug
   								GridImageParameters gip = fittingStrategy.distortionCalibrationData.gIP[numImage];
  								int np = gip.pixelsXY.length;
  								double wsx=0.0, wsy=0.0, ws_dpx_dgh= 0.0, ws_dpy_dgh= 0.0, ws_dpx_dga= 0.0, ws_dpy_dga= 0.0;
   								for (int k = 0; k < length; k+=1) {
   									double w = (weightFunction!=null)? weightFunction[start+k] : 1.0;
   									wsx +=        w;
   									ws_dpx_dgh += w * partialJacobian[par_gh][k];
   									ws_dpx_dga += w * partialJacobian[par_ga][k];
   									k++;
   									w = (weightFunction!=null)? weightFunction[start+k] : 1.0;
   									wsy +=        w;
   									ws_dpy_dgh += w * partialJacobian[par_gh][k];
   									ws_dpy_dga += w * partialJacobian[par_ga][k];
   								}
   								if ((wsx == 0.0) || (wsy == 0.0)) {
   									if (debugLevel>2) {
   										System.out.println("Not enough data for dpx/dgh, dpy/dgh, dpx/dga, dpy/dga for image #"+numImage);
   									}
   									continue;
   								}
   								ws_dpx_dgh /= wsx;
   								ws_dpx_dga /= wsx;
   								ws_dpy_dgh /= wsy;
   								ws_dpy_dga /= wsy;
   								
   								Matrix mXY_HA = new Matrix(new double[][] {{ws_dpx_dgh, ws_dpx_dga},{ws_dpy_dgh, ws_dpy_dga}});
  								
   								double [][][] data = new double[np][3][];
   								for (int indx = 0; indx < np; indx++) {
   									data[indx][0] = new double[2];
   									data[indx][1] = new double[2];
   									data[indx][2] = new double[1];
   									data[indx][0][0] = gip.pixelsUV[indx][0]; // U
   									data[indx][0][1] = gip.pixelsUV[indx][1]; // V
   									data[indx][1][0] = gip.pixelsXY[indx][0]; // pX
   									data[indx][1][1] = gip.pixelsXY[indx][1]; // pY
   									data[indx][2][0] = gip.pixelsMask[indx];  // weighth
   								}
   								double [][] coeff = polynomialApproximation.quadraticApproximation(
   										data,
   										true); // force linear
   								Matrix mXY_UV=new Matrix(new double[][] {{coeff[0][0],coeff[0][1]},{coeff[1][0],coeff[1][1]}});
   								if (!(new LUDecomposition(mXY_UV)).isNonsingular()){
   									if (debugLevel>2) {
   										System.out.println("Skipping singular matrix for image #"+numImage);
   									}
   									continue;
   								}
   								Matrix mUV_XY= mXY_UV.inverse();
   								Matrix mUV_HA = mUV_XY.times(mXY_HA);
   								dUV_image  [numImage] = mUV_HA.getArray();
   								dUV_weights[numImage] = wsx + wsy;
   							} else {
   								System.out.println ("Bug: ga/gh are not among the parameters, par_gh="+par_gh+", par_ga="+par_ga);
Andrey Filippov's avatar
Andrey Filippov committed
6117 6118
   							}
   						}
6119
   						
Andrey Filippov's avatar
Andrey Filippov committed
6120 6121 6122 6123 6124 6125 6126
   						synchronizedCombinePartialJacobians(
   								JtByJmod, //Transposed Jacobian multiplied by Jacobian
   								JtByDiff,
   								partialJacobian,
   								partialJtByDiff,
   								partialJtByJmod,
   								numPars	);
Andrey Filippov's avatar
Andrey Filippov committed
6127

Andrey Filippov's avatar
Andrey Filippov committed
6128 6129
   						final int numFinished=imageFinishedAtomic.getAndIncrement();
   						SwingUtilities.invokeLater(new Runnable() {
Andrey Filippov's avatar
Andrey Filippov committed
6130 6131
   							@Override
							public void run() {
Andrey Filippov's avatar
Andrey Filippov committed
6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164
   								// Here, we can safely update the GUI
   								// because we'll be called from the
   								// event dispatch thread
   								IJ.showProgress(progressValues[numFinished]);
   							}
   						});
   						if (stopRequested.get()==1){ // ASAP
   							interruptedAtomic.set(true);
   						}
   					}
   				}
   			};
   		}
   		startAndJoin(threads);
   		if (interruptedAtomic.get()) {
   			System.out.println("calculateJacobianArrays() aborted by user request");
   			return null;
   		}
   		if (debugLevel>3){
   			String msg="calculateJacobianArrays() ALL_trace=";
   			for (int ii=0;ii<numPars;ii++) msg+=IJ.d2s(JtByJmod[ii][ii],5);
   			System.out.println(msg);

   		}

   		for (int i=0;i<numPars;i++) { // subtract lambda*diagonal , fill the symmetrical half below the diagonal
   			for (int j=0;j<i;j++) JtByJmod[i][j]= JtByJmod[j][i]; // it is symmetrical matrix, just copy
   		}
   		LMAArrays lMAArrays = new LMAArrays();
   		lMAArrays.jTByJ=JtByJmod;
   		lMAArrays.jTByDiff=JtByDiff;
   		if (debugLevel>3){
   			String msg="calculateJacobianArrays() lMAArrays.jTByJ trace=";
6165
   			for (int ii=0;ii<numPars;ii++) msg+=IJ.d2s(lMAArrays.jTByJ[ii][ii],5)+" ";
Andrey Filippov's avatar
Andrey Filippov committed
6166 6167 6168
   			System.out.println(msg);

   		}
6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189
   		if (dTA_dUV != null) {
   			double [][] dUV_average = new double [2][2];
   			for (int i = 0; i < 2; i++) for (int j=0; j<2; j++) dUV_average[i][j] = 0.0;
   			double sw = 0.0;
   			for (int ni = 0; ni < dUV_weights.length; ni++) {
   				double w = dUV_weights[ni]; 
   				if (w > 0.0) {
   					for (int i = 0; i < 2; i++) for (int j=0; j<2; j++) {
   						dUV_average[i][j] += w *dUV_image[ni][i][j] ;
   					}
   					sw += w;
   				}
   			}
   			if (sw > 0) {
   				for (int i = 0; i < 2; i++) for (int j=0; j<2; j++) {
   					dUV_average[i][j] /= sw;
   				}
   				Matrix mdTA_dUV = (new Matrix(dUV_average)).inverse();
   				this.dTA_dUV = mdTA_dUV.getArray();
   			}
   		}
Andrey Filippov's avatar
Andrey Filippov committed
6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206
   		return lMAArrays;
	}

	public synchronized void synchronizedCombinePartialJacobians(
			double [][] JtByJmod, //Transposed Jacobian multiplied by Jacobian
			double []   JtByDiff,
			double [][] partialJacobian,
			double []   partialJtByDiff,
			double [][] partialJtByJmod,
			int numPars
	){
		for (int i=0;i<numPars;i++) if (partialJacobian[i]!=null){
			JtByDiff[i]+=partialJtByDiff[i];
			for (int j=i;j<numPars;j++) JtByJmod[i][j]+=partialJtByJmod[i][j];
		}
	}

Andrey Filippov's avatar
Andrey Filippov committed
6207 6208 6209



Andrey Filippov's avatar
Andrey Filippov committed
6210 6211 6212 6213 6214 6215 6216 6217 6218 6219
	public double [] solveLMA(
			LMAArrays lMAArrays,
			double lambda){
		double [][] JtByJmod= lMAArrays.jTByJ.clone();
		int numPars=JtByJmod.length;
		for (int i=0;i<numPars;i++){
			JtByJmod[i]=lMAArrays.jTByJ[i].clone();
   			JtByJmod[i][i]+=lambda*JtByJmod[i][i]; //Marquardt mod
		}
//	    M*Ma=Mb
6220 6221 6222 6223
		System.out.println("JtByJmod.length="+JtByJmod.length+" numPars="+numPars);
		if (numPars==0) {
			return null;
		}
Andrey Filippov's avatar
Andrey Filippov committed
6224 6225
	    Matrix M=new Matrix(JtByJmod);
//  public Matrix (double vals[], int m) {
Andrey Filippov's avatar
Andrey Filippov committed
6226

Andrey Filippov's avatar
Andrey Filippov committed
6227 6228 6229 6230 6231 6232
		if (this.debugLevel>2) {
//		if (this.debugLevel>1) {
			System.out.println("Jt*J -lambda* diag(Jt*J), lambda="+lambda+":");
			M.print(10, 5);
		}

6233
	    Matrix Mb=new Matrix(lMAArrays.jTByDiff,numPars); // single column {NaN,NaN}
Andrey Filippov's avatar
Andrey Filippov committed
6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252
	    if (!(new LUDecomposition(M)).isNonsingular()){
	    	double [][] arr=M.getArray();
			System.out.println("Singular Matrix "+arr.length+"x"+arr[0].length);
			// any rowsx off all 0.0?
			for (int n=0;n<arr.length;n++){
				boolean zeroRow=true;
				for (int i=0;i<arr[n].length;i++) if (arr[n][i]!=0.0){
					zeroRow=false;
					break;
				}
				if (zeroRow){
					System.out.println("Row of all zeros: "+n);
				}
			}
//			M.print(10, 5);
	    	return null;
	    }
	    Matrix Ma=M.solve(Mb); // singular
	    return Ma.getColumnPackedCopy();
Andrey Filippov's avatar
Andrey Filippov committed
6253

Andrey Filippov's avatar
Andrey Filippov committed
6254
	}
Andrey Filippov's avatar
Andrey Filippov committed
6255 6256


Andrey Filippov's avatar
Andrey Filippov committed
6257 6258 6259 6260 6261
	/**
	 * Calculates  next parameters vector, holds some arrays
	 * @param numSeries
	 * @return array of two booleans: { improved, finished}
	 */
6262 6263 6264
	public boolean [] stepLevenbergMarquardtFirst(
			int     numSeries,
			boolean calc_dUV){
Andrey Filippov's avatar
Andrey Filippov committed
6265
		double [] deltas=null;
6266
		if ((this.currentVector==null) || (this.currentVector.length==0)) { // length==0 was debugging
Andrey Filippov's avatar
Andrey Filippov committed
6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 6290
			int filter=this.filterForAll;
			if (this.askFilter) filter=selectFilter(filter);
			initFittingSeries(false,filter,numSeries); // first step in series
			this.currentRMS=-1;
			this.currentRMSPure=-1;
			this.currentfX=null; // invalidate
			this.jacobian=null;  // invalidate
			this.lMAArrays=null;
			lastImprovements[0]=-1.0;
			lastImprovements[1]=-1.0;
		}
		// calculate  this.currentfX, this.jacobian if needed
		if (this.debugLevel>2) {
			System.out.println("this.currentVector");
			for (int i=0;i<this.currentVector.length;i++){
				System.out.println(i+": "+ this.currentVector[i]);
			}
		}
		//    	if ((this.currentfX==null)|| ((this.jacobian==null) && !this.threadedLMA )) {
		if ((this.currentfX==null)|| (this.lMAArrays==null)) {
			if (this.updateStatus){
//				IJ.showStatus(this.seriesNumber+": "+"Step #"+this.iterationStepNumber+" RMS="+IJ.d2s(this.currentRMS,8)+ " ("+IJ.d2s(this.firstRMS,8)+")");
				IJ.showStatus(this.seriesNumber+": initial Jacobian matrix calculation. Points:"+this.Y.length+" Parameters:"+this.currentVector.length);
			}
6291
			if (this.debugLevel >1) {
Andrey Filippov's avatar
Andrey Filippov committed
6292 6293 6294 6295
				System.out.println(this.seriesNumber+": initial Jacobian matrix calculation. Points:"+this.Y.length+" Parameters:"+this.currentVector.length);
			}
    		if (this.threadedLMA) {
    			this.currentfX=new double[this.Y.length];
6296
   				this.dTA_dUV = 	calc_dUV ? (new double [2][2]): null;
Andrey Filippov's avatar
Andrey Filippov committed
6297 6298 6299
    			//    			deltas=solveLevenbergMarquardtThreaded(
    			this.lMAArrays=calculateJacobianArrays(
    					this.fittingStrategy.selectedImages(), // selected images to process
Andrey Filippov's avatar
Andrey Filippov committed
6300
    					this.Y,  // should be initialized
Andrey Filippov's avatar
Andrey Filippov committed
6301 6302 6303 6304 6305 6306
    					this.currentfX, // should be initialized to correct length, data is not needed
    					this.currentVector,  // parameters vector
    					this.imageStartIndex, // index of the first point of each image (including extra element in the end so n+1 is always valid)
    					this.targetXYZ, // this.targetXYZ
    					this.weightFunction, // may be null - make it twice smaller? - same for X and Y?
    					this.lensDistortionParameters,
6307
    					this.dTA_dUV,// final double [][][] dUV_average, // null or double [selectedImages.length][][] to return per-image {{dU/dAz,dU/dTl}{dV/dAz,dV/dTl}}
Andrey Filippov's avatar
Andrey Filippov committed
6308 6309 6310 6311 6312 6313 6314 6315 6316 6317 6318 6319
    					//    					this.lambda,
    					this.threadsMax,
    					this.updateStatus);
    			if (this.lMAArrays == null) {
    				return null ; // aborted
    			}
    		} else {
    			this.currentfX=calculateFxAndJacobian(this.currentVector, true); // is it always true here (this.jacobian==null)
    			this.lMAArrays=calculateJacobianArrays(this.currentfX);
//    			deltas=solveLevenbergMarquardt(this.currentfX,this.lambda);
    		}
    		// add termes that push selected extrinsic parameters towards average (global, per station, per tilt-station)
6320
    		this.currentRMSPure= calcErrorDiffY(this.currentfX) +0.0;
Andrey Filippov's avatar
Andrey Filippov committed
6321 6322 6323 6324 6325 6326 6327 6328 6329 6330 6331 6332 6333 6334 6335
    	   	if ((this.fittingStrategy.varianceModes!=null) && (this.fittingStrategy.varianceModes[numSeries]!=this.fittingStrategy.varianceModeDisabled)) {
    	   		this.fittingStrategy.addVarianceToLMA(
    	    			numSeries,
    	    			this.currentVector,
    	    			this.lMAArrays.jTByJ, // jacobian multiplied by Jacobian transposed (or null)
    	    			this.lMAArrays.jTByDiff);
    	   		this.currentRMS= calcErrorDiffY(
    	   				this.currentfX,
    	   				this.fittingStrategy.getVarianceError2(), //double [] extraWeightedErrors,
    	   				this.fittingStrategy.getWeights()); //double [] extraWeights);
    			if (this.updateStatus){
    				IJ.showStatus(this.seriesNumber+": initial RMS="+IJ.d2s(this.currentRMS,8)+
    						" ("+IJ.d2s(this.currentRMSPure,8)+")"+
    						". Calculating next Jacobian. Points:"+this.Y.length+" Parameters:"+this.currentVector.length);
    			}
6336
    			if ((this.debugLevel>0) && ((this.debugLevel>1) || ((System.nanoTime()-this.startTime)>10000000000.0))) {
Andrey Filippov's avatar
Andrey Filippov committed
6337 6338 6339 6340 6341 6342 6343 6344 6345 6346 6347 6348 6349 6350 6351 6352 6353 6354 6355 6356 6357 6358 6359 6360 6361 6362 6363 6364 6365 6366 6367 6368
    				System.out.println(this.seriesNumber+": initial RMS="+IJ.d2s(this.currentRMS,8)+
    						" ("+IJ.d2s(this.currentRMSPure,8)+")"+
    						". Calculating next Jacobian. Points:"+this.Y.length+" Parameters:"+this.currentVector.length);
    			}

    	   	} else {
        		this.currentRMS= this.currentRMSPure;
    			if (this.updateStatus){
    				IJ.showStatus(this.seriesNumber+": initial RMS="+IJ.d2s(this.currentRMS,8)+
    						". Calculating next Jacobian. Points:"+this.Y.length+" Parameters:"+this.currentVector.length);
    			}
    			if (this.debugLevel>1) {
    				System.out.println(this.seriesNumber+": initial RMS="+IJ.d2s(this.currentRMS,8)+
    						". Calculating next Jacobian. Points:"+this.Y.length+" Parameters:"+this.currentVector.length);
    			}
    	   	}
    	} else {
    		this.currentRMSPure= calcErrorDiffY(this.currentfX);
    	   	if ((this.fittingStrategy.varianceModes!=null) && (this.fittingStrategy.varianceModes[numSeries]!=this.fittingStrategy.varianceModeDisabled)) {
    	   		this.fittingStrategy.addVarianceToLMA(// recalculating as this may keep from nextVector (or just being restored)
    	    			numSeries,
    	    			this.currentVector,
    	    			null, //this.lMAArrays.jTByJ, // jacobian multiplied by Jacobian transposed (or null)
    	    			null); //this.lMAArrays.jTByDiff);

    	   		this.currentRMS= calcErrorDiffY(
    	   				this.currentfX,
    	   				this.fittingStrategy.getVarianceError2(), //double [] extraWeightedErrors,
    	   				this.fittingStrategy.getWeights()); //double [] extraWeights);
    	   	} else {
        		this.currentRMS= this.currentRMSPure;
    	   	}
Andrey Filippov's avatar
Andrey Filippov committed
6369

Andrey Filippov's avatar
Andrey Filippov committed
6370 6371 6372 6373 6374 6375 6376 6377
    	}
//		this.currentRMS= calcError(calcYminusFx(this.currentfX));
    	if (this.firstRMS<0) {
    		this.firstRMS=this.currentRMS;
    		this.firstRMSPure=this.currentRMSPure;
    	}
// calculate deltas
//    	double [] deltas=solveLevenbergMarquardt(this.currentfX,fittingStrategy.getLambda());
Andrey Filippov's avatar
Andrey Filippov committed
6378

Andrey Filippov's avatar
Andrey Filippov committed
6379
		deltas=solveLMA(this.lMAArrays,	this.lambda	);
Andrey Filippov's avatar
Andrey Filippov committed
6380

Andrey Filippov's avatar
Andrey Filippov committed
6381 6382 6383 6384 6385 6386 6387 6388 6389 6390 6391 6392
    	boolean matrixNonSingular=true;
    	if (deltas==null) {
    		deltas=new double[this.currentVector.length];
    		for (int i=0;i<deltas.length;i++) deltas[i]=0.0;
    		matrixNonSingular=false;
    	}
		if (this.debugLevel>2) {
			System.out.println("deltas");
			for (int i=0;i<deltas.length;i++){
				System.out.println(i+": "+ deltas[i]);
			}
		}
Andrey Filippov's avatar
Andrey Filippov committed
6393
// apply deltas
Andrey Filippov's avatar
Andrey Filippov committed
6394 6395
    	this.nextVector=this.currentVector.clone();
    	for (int i=0;i<this.nextVector.length;i++) this.nextVector[i]+=deltas[i];
Andrey Filippov's avatar
Andrey Filippov committed
6396
// another option - do not calculate J now, just fX. and late - calculate both if it was improvement
Andrey Filippov's avatar
Andrey Filippov committed
6397 6398 6399 6400 6401 6402 6403 6404 6405 6406 6407
//    	save current Jacobian
		if (this.debugLevel>2) {
			System.out.println("this.nextVector");
			for (int i=0;i<this.nextVector.length;i++){
				System.out.println(i+": "+ this.nextVector[i]);
			}
		}

//        this.savedJacobian=this.jacobian;
        this.savedLMAArrays=lMAArrays.clone();
        this.jacobian=null; // not needed, just to catch bugs
Andrey Filippov's avatar
Andrey Filippov committed
6408
// calculate next vector and Jacobian  (this.jacobian)
Andrey Filippov's avatar
Andrey Filippov committed
6409
//    	this.nextfX=calculateFxAndJacobian(this.nextVector,true); //=========== OLD
Andrey Filippov's avatar
Andrey Filippov committed
6410

Andrey Filippov's avatar
Andrey Filippov committed
6411 6412 6413 6414 6415
		if (this.threadedLMA) {
			this.nextfX=new double[this.Y.length];
			//    			deltas=solveLevenbergMarquardtThreaded(
			this.lMAArrays=calculateJacobianArrays(
					this.fittingStrategy.selectedImages(), // selected images to process
Andrey Filippov's avatar
Andrey Filippov committed
6416
					this.Y,  // should be initialized
Andrey Filippov's avatar
Andrey Filippov committed
6417 6418 6419 6420 6421 6422
					this.nextfX, // should be initialized to correct length, data is not needed
					this.nextVector,  // parameters vector
					this.imageStartIndex, // index of the first point of each image (including extra element in the end so n+1 is always valid)
					this.targetXYZ, // this.targetXYZ
					this.weightFunction, // may be null - make it twice smaller? - same for X and Y?
					this.lensDistortionParameters,
6423
					this.dTA_dUV,// final double [][][] dUV_average, // null or double [selectedImages.length][][] to return per-image {{dU/dAz,dU/dTl}{dV/dAz,dV/dTl}}
Andrey Filippov's avatar
Andrey Filippov committed
6424 6425 6426 6427 6428 6429 6430 6431 6432 6433 6434
					//    					this.lambda,
					this.threadsMax,
					this.updateStatus);
			if (this.lMAArrays == null) {
				return null ; // aborted
			}
		} else {
	    	this.nextfX=calculateFxAndJacobian(this.nextVector,true);
			this.lMAArrays=calculateJacobianArrays(this.nextfX);
		}
//		this.nextRMS=calcErrorDiffY(this.nextfX);
Andrey Filippov's avatar
Andrey Filippov committed
6435

Andrey Filippov's avatar
Andrey Filippov committed
6436 6437 6438 6439 6440 6441 6442 6443 6444 6445 6446 6447 6448 6449 6450 6451 6452 6453 6454 6455 6456 6457 6458 6459 6460 6461 6462 6463
		this.nextRMSPure= calcErrorDiffY(this.nextfX);
	   	if ((this.fittingStrategy.varianceModes!=null) && (this.fittingStrategy.varianceModes[numSeries]!=this.fittingStrategy.varianceModeDisabled)) {
	   		this.fittingStrategy.addVarianceToLMA(
	    			numSeries,
	    			this.nextVector,
	    			this.lMAArrays.jTByJ, // jacobian multiplied by Jacobian transposed (or null)
	    			this.lMAArrays.jTByDiff);
	   		this.nextRMS= calcErrorDiffY(
	   				this.nextfX,
	   				this.fittingStrategy.getVarianceError2(), //double [] extraWeightedErrors,
	   				this.fittingStrategy.getWeights()); //double [] extraWeights);
	   	} else {
	   		this.nextRMS= this.nextRMSPure;
	   	}

		this.lastImprovements[1]=this.lastImprovements[0];
		this.lastImprovements[0]=this.currentRMS-this.nextRMS;
		if (this.debugLevel>2) {
			System.out.println("stepLMA this.currentRMS="+this.currentRMS+
					", this.currentRMSPure="+this.currentRMSPure+
					", this.nextRMS="+this.nextRMS+
					", this.nextRMSPure="+this.nextRMSPure+
					", delta="+(this.currentRMS-this.nextRMS)+
					", deltaPure="+(this.currentRMSPure-this.nextRMSPure));
		}
		boolean [] status={matrixNonSingular && (this.nextRMS<=this.currentRMS),!matrixNonSingular};
		// additional test if "worse" but the difference is too small, it was be caused by computation error, like here:
		//stepLevenbergMarquardtAction() step=27, this.currentRMS=0.17068403807026408,   this.nextRMS=0.1706840380702647
Andrey Filippov's avatar
Andrey Filippov committed
6464

Andrey Filippov's avatar
Andrey Filippov committed
6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476 6477 6478 6479 6480 6481
		if (!status[0] && matrixNonSingular) {
			if (this.nextRMS<(this.currentRMS+this.currentRMS*this.thresholdFinish*0.01)) {
				this.nextRMS=this.currentRMS;
				this.nextRMSPure=this.currentRMSPure;
				status[0]=true;
				status[1]=true;
				this.lastImprovements[0]=0.0;
				if (this.debugLevel>1) {
					System.out.println("New RMS error is larger than the old one, but the difference is too small to be trusted ");
					System.out.println(
							"stepLMA this.currentRMS="+this.currentRMS+
							", this.currentRMSPure="+this.currentRMSPure+
							", this.nextRMS="+this.nextRMS+
							", this.nextRMSPure="+this.nextRMSPure+
							", delta="+(this.currentRMS-this.nextRMS)+
							", deltaPure="+(this.currentRMSPure-this.nextRMSPure));
				}
Andrey Filippov's avatar
Andrey Filippov committed
6482

Andrey Filippov's avatar
Andrey Filippov committed
6483 6484 6485 6486 6487 6488 6489 6490 6491 6492 6493
			}
		}
    	if (status[0] && matrixNonSingular) { //improved
    		status[1]=(this.iterationStepNumber>this.numIterations) || ( // done
    				(this.lastImprovements[0]>=0.0) &&
    				(this.lastImprovements[0]<this.thresholdFinish*this.currentRMS) &&
    				(this.lastImprovements[1]>=0.0) &&
    				(this.lastImprovements[1]<this.thresholdFinish*this.currentRMS));
    	} else if (matrixNonSingular){
//    		this.jacobian=this.savedJacobian;// restore saved Jacobian
    		this.lMAArrays=this.savedLMAArrays; // restore Jt*J and Jt*diff
Andrey Filippov's avatar
Andrey Filippov committed
6494

Andrey Filippov's avatar
Andrey Filippov committed
6495 6496 6497
    		status[1]=(this.iterationStepNumber>this.numIterations) || // failed
    		((this.lambda*this.lambdaStepUp)>this.maxLambda);
    	}
Andrey Filippov's avatar
Andrey Filippov committed
6498 6499
///this.currentRMS
//TODO: add other failures leading to result failure?
Andrey Filippov's avatar
Andrey Filippov committed
6500 6501 6502 6503 6504 6505
		if (this.debugLevel>2) {
			System.out.println("stepLevenbergMarquardtFirst("+numSeries+")=>"+status[0]+","+status[1]);
		}
		return status;
    }
    /**
Andrey Filippov's avatar
Andrey Filippov committed
6506
     * Apply fitting step
Andrey Filippov's avatar
Andrey Filippov committed
6507
     */
Andrey Filippov's avatar
Andrey Filippov committed
6508
    public void stepLevenbergMarquardtAction(){//
Andrey Filippov's avatar
Andrey Filippov committed
6509
    	this.iterationStepNumber++;
Andrey Filippov's avatar
Andrey Filippov committed
6510
// apply/revert,modify lambda
Andrey Filippov's avatar
Andrey Filippov committed
6511 6512 6513 6514 6515 6516 6517 6518 6519 6520 6521 6522 6523 6524 6525 6526 6527 6528 6529 6530 6531
		if (this.debugLevel>1) {
			System.out.println(
					"stepLevenbergMarquardtAction() step="+this.iterationStepNumber+
					", this.currentRMS="+this.currentRMS+
					", this.currentRMSPure="+this.currentRMSPure+
					", this.nextRMS="+this.nextRMS+
					", this.nextRMSPure="+this.nextRMSPure+
					" lambda="+this.lambda+" at "+IJ.d2s(0.000000001*(System.nanoTime()-this.startTime),3)+" sec");
		}
    	if (this.nextRMS<this.currentRMS) { //improved
    		this.lambda*=this.lambdaStepDown;
    		this.currentRMS=this.nextRMS;
    		this.currentRMSPure=this.nextRMSPure;
    		this.currentfX=this.nextfX;
    		this.currentVector=this.nextVector;
    	} else {
    		this.lambda*=this.lambdaStepUp;
//    		this.jacobian=this.savedJacobian;// restore saved Jacobian
    		this.lMAArrays=this.savedLMAArrays; // restore Jt*J and Jt*diff
    	}
    }
Andrey Filippov's avatar
Andrey Filippov committed
6532

Andrey Filippov's avatar
Andrey Filippov committed
6533 6534 6535 6536 6537 6538 6539 6540 6541 6542 6543 6544 6545 6546 6547 6548 6549 6550 6551
    /**
     * Dialog to select Levenberg-Marquardt algorithm and related parameters
     * @return true if OK, false if canceled
     */
    public boolean selectLMAParameters(){
    	int numSeries=fittingStrategy.getNumSeries();
	    GenericDialog gd = new GenericDialog("Levenberg-Marquardt algorithm parameters for cameras distortions/locations");
		gd.addNumericField("Iteration number to start (0.."+(numSeries-1)+")", this.seriesNumber, 0);
		gd.addNumericField("Initial LMA Lambda ",            this.lambda, 5);
		gd.addNumericField("Multiply lambda on success",     this.lambdaStepDown, 5);
		gd.addNumericField("Threshold RMS to exit LMA",      this.thresholdFinish, 7,9,"pix");
		gd.addNumericField("Multiply lambda on failure",     this.lambdaStepUp, 5);
		gd.addNumericField("Threshold lambda to fail",       this.maxLambda, 5);
		gd.addNumericField("Maximal number of iterations",   this.numIterations, 0);

		gd.addCheckbox("Dialog after each iteration step",   this.stopEachStep);
		gd.addCheckbox("Dialog after each iteration series", this.stopEachSeries);
		gd.addCheckbox("Dialog after each failure",          this.stopOnFailure);
		gd.addCheckbox("Ask for weight function filter",     this.askFilter);
Andrey Filippov's avatar
Andrey Filippov committed
6552

Andrey Filippov's avatar
Andrey Filippov committed
6553 6554 6555 6556 6557 6558 6559 6560 6561 6562 6563 6564 6565 6566 6567 6568 6569 6570 6571 6572 6573 6574 6575 6576 6577
		gd.addCheckbox("Show modified parameters",           this.showParams);
		gd.addCheckbox("Show debug images before correction",this.showThisImages);
		gd.addCheckbox("Show debug images after correction", this.showNextImages);
		gd.addNumericField("Maximal number of threads",   this.threadsMax, 0);
		gd.addCheckbox("Use memory-saving/multithreaded version", this.threadedLMA);
	    gd.showDialog();
	    if (gd.wasCanceled()) return false;
	    this.seriesNumber=     (int) gd.getNextNumber();
		this.lambda=                 gd.getNextNumber();
		this.lambdaStepDown=         gd.getNextNumber();
		this.thresholdFinish=        gd.getNextNumber();
		this.lambdaStepUp=           gd.getNextNumber();
		this.maxLambda=              gd.getNextNumber();
		this.numIterations=    (int) gd.getNextNumber();
		this.stopEachStep=           gd.getNextBoolean();
		this.stopEachSeries=         gd.getNextBoolean();
		this.stopOnFailure=          gd.getNextBoolean();
		this.askFilter=              gd.getNextBoolean();
		this.showParams=             gd.getNextBoolean();
		this.showThisImages=         gd.getNextBoolean();
		this.showNextImages=         gd.getNextBoolean();
		this.threadsMax=       (int) gd.getNextNumber();
		this.threadedLMA=            gd.getNextBoolean();
	    return true;
    }
Andrey Filippov's avatar
Andrey Filippov committed
6578 6579


Andrey Filippov's avatar
Andrey Filippov committed
6580 6581 6582 6583 6584 6585 6586
    public boolean dialogLMAStep(boolean [] state){
    	String [] states={
    			"Worse, increase lambda",
    			"Better, decrease lambda",
    			"Failed to fit",
    			"Fitting Successful"};
    	int iState=(state[0]?1:0)+(state[1]?2:0);
Andrey Filippov's avatar
Andrey Filippov committed
6587

Andrey Filippov's avatar
Andrey Filippov committed
6588
	    GenericDialog gd = new GenericDialog("Levenberg-Marquardt algorithm step");
6589
//    	String [][] parameterDescriptions=fittingStrategy.distortionCalibrationData.parameterDescriptions;
Andrey Filippov's avatar
Andrey Filippov committed
6590 6591
    	gd.addMessage("Current state="+states[iState]);
    	gd.addMessage("Iteration step="+this.iterationStepNumber);
Andrey Filippov's avatar
Andrey Filippov committed
6592

Andrey Filippov's avatar
Andrey Filippov committed
6593 6594 6595 6596 6597 6598 6599
    	gd.addMessage("Initial RMS="+IJ.d2s(this.firstRMS,6)+", Current RMS="+IJ.d2s(this.currentRMS,6)+", new RMS="+IJ.d2s(this.nextRMS,6));
    	gd.addMessage("Pure initial RMS="+IJ.d2s(this.firstRMSPure,6)+", Current RMS="+IJ.d2s(this.currentRMSPure,6)+", new RMS="+IJ.d2s(this.nextRMSPure,6));
    	if (this.showParams) {
    		for (int i=0;i<this.currentVector.length;i++){
    			int parNum=fittingStrategy.parameterMap[i][1];
    			int imgNum=fittingStrategy.parameterMap[i][0];
    			double delta= this.nextVector[i] - this.currentVector[i];
6600 6601 6602 6603 6604
//    			gd.addMessage(i+": "+parameterDescriptions[parNum][0]+
//    					"["+imgNum+"]("+parameterDescriptions[parNum][2]+") "+IJ.d2s(this.currentVector[i],3)+
//    					" + "+IJ.d2s(delta,3)+" = "+IJ.d2s(this.nextVector[i],3));
    			gd.addMessage(i+": "+fittingStrategy.distortionCalibrationData.descrField(parNum,0)+
    					"["+imgNum+"]("+fittingStrategy.distortionCalibrationData.descrField(parNum,2)+") "+IJ.d2s(this.currentVector[i],3)+
Andrey Filippov's avatar
Andrey Filippov committed
6605 6606 6607 6608 6609 6610 6611 6612 6613 6614 6615 6616 6617 6618 6619 6620 6621 6622 6623 6624 6625 6626 6627 6628 6629 6630 6631 6632 6633 6634 6635 6636 6637 6638 6639 6640 6641 6642 6643 6644
    					" + "+IJ.d2s(delta,3)+" = "+IJ.d2s(this.nextVector[i],3));
    		}
    	}
		gd.addNumericField("Lambda ",                        this.lambda, 5);
		gd.addNumericField("Multiply lambda on success",     this.lambdaStepDown, 5);
		gd.addNumericField("Threshold RMS to exit LMA",      this.thresholdFinish, 7,9,"pix");
		gd.addNumericField("Multiply lambda on failure",     this.lambdaStepUp, 5);
		gd.addNumericField("Threshold lambda to fail",       this.maxLambda, 5);
		gd.addNumericField("Maximal number of iterations",   this.numIterations, 0);

		gd.addCheckbox("Dialog after each iteration step",   this.stopEachStep);
		gd.addCheckbox("Dialog after each iteration series", this.stopEachSeries);
		gd.addCheckbox("Dialog after each failure",          this.stopOnFailure);
		gd.addCheckbox("Show modified parameters",           this.showParams);
		gd.addCheckbox("Show debug images before correction",this.showThisImages);
		gd.addCheckbox("Show debug images after correction", this.showNextImages);
		gd.addMessage("Done will save the current (not new!) state and exit, Continue will proceed according to LMA");
		gd.enableYesNoCancel("Continue", "Done");
		WindowTools.addScrollBars(gd);

	    gd.showDialog();
	    if (gd.wasCanceled()) {
	    	this.saveSeries=false;
	    	return false;
	    }
		this.lambda=                 gd.getNextNumber();
		this.lambdaStepDown=         gd.getNextNumber();
		this.thresholdFinish=        gd.getNextNumber();
		this.lambdaStepUp=           gd.getNextNumber();
		this.maxLambda=              gd.getNextNumber();
		this.numIterations=    (int) gd.getNextNumber();
		this.stopEachStep=           gd.getNextBoolean();
		this.stopEachSeries=         gd.getNextBoolean();
		this.stopOnFailure=          gd.getNextBoolean();
		this.showParams=             gd.getNextBoolean();
		this.showThisImages=         gd.getNextBoolean();
		this.showNextImages=         gd.getNextBoolean();
	    this.saveSeries=true;
	    return gd.wasOKed();
    }
Andrey Filippov's avatar
Andrey Filippov committed
6645

Andrey Filippov's avatar
Andrey Filippov committed
6646 6647 6648 6649 6650 6651 6652 6653 6654 6655 6656 6657 6658 6659 6660 6661 6662 6663 6664 6665 6666 6667
    public boolean modifyGrid(
    		DistortionCalibrationData distortionCalibrationData,
			int threadsMax,
			boolean updateStatus){
    	if (fittingStrategy==null) {
    		String msg="Fitting strategy does not exist, exiting";
    		IJ.showMessage("Error",msg);
    		throw new IllegalArgumentException (msg);
    	}
    	if (distortionCalibrationData.sensorMasks==null){
    		String msg="Sensor mask(s) are not defined";
    		IJ.showMessage("Error",msg);
    		throw new IllegalArgumentException (msg);
    	}
    	if (distortionCalibrationData.eyesisCameraParameters==null){
    		String msg="Eyesis camera parameters (and sensor dimensions) are not defined";
    		IJ.showMessage("Error",msg);
    		throw new IllegalArgumentException (msg);
    	}
//    	if (! selectGridEnhanceParameters()) return false;
//    	int series=refineParameters.showDialog("Select Grid Tuning Parameters", 0xdc0, fittingStrategy.getNumSeries());
//    	int series=refineParameters.showDialog("Select Grid Tuning Parameters", 0x31cc0, (this.seriesNumber>=0)?this.seriesNumber:0); // 0x1dco with show result, but we can not show it easily
Andrey Filippov's avatar
Andrey Filippov committed
6668
// todo - add and implement 0x10000 to show just one individual image
Andrey Filippov's avatar
Andrey Filippov committed
6669 6670 6671 6672 6673
//    	int series=refineParameters.showDialog("Select Grid Tuning Parameters", 0x21cc0, (this.seriesNumber>=0)?this.seriesNumber:0); // 0x1dco with show result, but we can not show it easily
    	int series=refineParameters.showDialog(
    			"Select Grid Tuning Parameters",
    			0x61000,
    			((this.seriesNumber>=0)?this.seriesNumber:0),
6674 6675
    			null, // averageRGB - only for target flat-field correction
    			false); // no difference for LWIR sensors?
Andrey Filippov's avatar
Andrey Filippov committed
6676 6677


Andrey Filippov's avatar
Andrey Filippov committed
6678 6679
    	if (series<0) return false;
    	this.seriesNumber=series;
Andrey Filippov's avatar
Andrey Filippov committed
6680

Andrey Filippov's avatar
Andrey Filippov committed
6681 6682 6683 6684 6685 6686 6687 6688 6689 6690 6691 6692 6693 6694 6695 6696 6697 6698 6699 6700 6701 6702 6703 6704 6705 6706 6707 6708 6709 6710 6711 6712 6713 6714 6715 6716 6717 6718 6719 6720 6721 6722 6723
		int filter=this.filterForTargetGeometry;
		if (this.askFilter) filter=selectFilter(filter);
    	initFittingSeries(true,filter,this.seriesNumber); // first step in series
//    	initFittingSeries(true,this.filterForTargetGeometry, this.seriesNumber); // first step in series
    	this.currentfX=calculateFxAndJacobian(this.currentVector, false);
    	//        	this.currentRMS= calcError(calcYminusFx(this.currentfX));
    	if (this.debugLevel>2) {
    		System.out.println("this.currentVector");
    		for (int i=0;i<this.currentVector.length;i++){
    			System.out.println(i+": "+ this.currentVector[i]);
    		}
    	}
    	if (this.showThisImages) showDiff (this.currentfX, "residual-series-"+this.seriesNumber);
    	if (this.refineParameters.resetVariations) {
    		this.patternParameters.resetStationZCorr();
    	}
    	double [][][] correctionCombo= calculateGridXYZCorr3D(
    			this.refineParameters.variationPenalty,
    			this.refineParameters.fixXY,
                this.refineParameters.useVariations?(this.fittingStrategy.zGroups[this.seriesNumber]):null, //stationGroups,
				this.refineParameters.grid3DCorrection,
				this.refineParameters.rotateCorrection,
				this.refineParameters.grid3DMaximalZCorr, //20.0,
				this.refineParameters.noFallBack,
				this.refineParameters.targetShowPerImage,
				threadsMax,
				updateStatus);
    	double [][] gridXYZCorr=correctionCombo[0];
		double [][] gridZCorr3d =correctionCombo[1];
		double [][] gridZCorr3dWeight =correctionCombo[2];
		String [] titles={"X-correction(mm)","Y-correction(mm)","Z-correction","Weight"};
    	String [] titlesStations=new String [2*gridZCorr3d.length];
    	for (int i=0;i<gridZCorr3d.length;i++){
    		titlesStations[i]="Z_"+i;
    		titlesStations[i+gridZCorr3d.length]="W_"+i;
    	}
    	if (this.refineParameters.targetShowThisCorrection) {
    		if (this.debugLevel>1){
    			double [][] debugData=new double [2*gridZCorr3d.length][];
    	    	for (int i=0;i<gridZCorr3d.length;i++){
    	    		debugData[i]=gridZCorr3d[i];
    	    		debugData[i+gridZCorr3d.length]=gridZCorr3dWeight[i];
    	    	}
6724
        		ShowDoubleFloatArrays.showArrays(debugData, getGridWidth(), getGridHeight(),  true, "Z corrections", titlesStations);
Andrey Filippov's avatar
Andrey Filippov committed
6725 6726 6727 6728
    		}
    	}


Andrey Filippov's avatar
Andrey Filippov committed
6729
// TODO: make configurable and optional
Andrey Filippov's avatar
Andrey Filippov committed
6730 6731 6732 6733 6734 6735 6736 6737
		shrinkExtrapolateGridCorrection(
				gridXYZCorr, // dx,dy,dz, mask >0
				gridZCorr3d,
				getGridWidth(),
				1, //preShrink,
				5, // expand,
				3.0, //  sigma,
				2.0); //double ksigma
Andrey Filippov's avatar
Andrey Filippov committed
6738

Andrey Filippov's avatar
Andrey Filippov committed
6739
    	if (this.refineParameters.targetShowThisCorrection) {
6740
    		ShowDoubleFloatArrays.showArrays(gridXYZCorr, getGridWidth(), getGridHeight(),  true, "Grid corrections", titles);
Andrey Filippov's avatar
Andrey Filippov committed
6741
    		if (this.debugLevel>1){
Andrey Filippov's avatar
Andrey Filippov committed
6742

Andrey Filippov's avatar
Andrey Filippov committed
6743 6744 6745 6746 6747 6748 6749 6750 6751 6752 6753 6754 6755 6756 6757 6758 6759 6760 6761 6762 6763 6764 6765 6766 6767 6768 6769
    		}
    	}
    	if (!this.refineParameters.targetApplyCorrection) return false;
    	patternParameters.applyGridCorrection(gridXYZCorr, this.refineParameters.targetCorrectionScale);
    	patternParameters.applyZGridCorrection(gridZCorr3d, this.refineParameters.targetCorrectionScale);
    	return true;
    }

    public boolean modifyGrid0(DistortionCalibrationData distortionCalibrationData){
    	if (fittingStrategy==null) {
    		String msg="Fitting strategy does not exist, exiting";
    		IJ.showMessage("Error",msg);
    		throw new IllegalArgumentException (msg);
    	}
    	if (distortionCalibrationData.sensorMasks==null){
    		String msg="Sensor mask(s) are not defined";
    		IJ.showMessage("Error",msg);
    		throw new IllegalArgumentException (msg);
    	}
    	if (distortionCalibrationData.eyesisCameraParameters==null){
    		String msg="Eyesis camera parameters (and sensor dimensions) are not defined";
    		IJ.showMessage("Error",msg);
    		throw new IllegalArgumentException (msg);
    	}
//    	if (! selectGridEnhanceParameters()) return false;
//    	int series=refineParameters.showDialog("Select Grid Tuning Parameters", 0xdc0, fittingStrategy.getNumSeries());
//    	int series=refineParameters.showDialog("Select Grid Tuning Parameters", 0x31cc0, (this.seriesNumber>=0)?this.seriesNumber:0); // 0x1dco with show result, but we can not show it easily
Andrey Filippov's avatar
Andrey Filippov committed
6770
// todo - add and implement 0x10000 to show just one individual image
Andrey Filippov's avatar
Andrey Filippov committed
6771 6772 6773 6774 6775
//    	int series=refineParameters.showDialog("Select Grid Tuning Parameters", 0x21cc0, (this.seriesNumber>=0)?this.seriesNumber:0); // 0x1dco with show result, but we can not show it easily
    	int series=refineParameters.showDialog(
    			"Select Grid Tuning Parameters",
    			0x61000,
    			((this.seriesNumber>=0)?this.seriesNumber:0),
6776 6777
    			null, // averageRGB - only for target flat-field correction
    			false); // no difference for LWIR?
Andrey Filippov's avatar
Andrey Filippov committed
6778 6779


Andrey Filippov's avatar
Andrey Filippov committed
6780 6781
    	if (series<0) return false;
    	this.seriesNumber=series;
Andrey Filippov's avatar
Andrey Filippov committed
6782 6783 6784



Andrey Filippov's avatar
Andrey Filippov committed
6785 6786 6787 6788 6789 6790 6791 6792 6793 6794 6795 6796 6797
		int filter=this.filterForTargetGeometry;
		if (this.askFilter) filter=selectFilter(filter);
    	initFittingSeries(true,filter,this.seriesNumber); // first step in series
//    	initFittingSeries(true,this.filterForTargetGeometry, this.seriesNumber); // first step in series
    	this.currentfX=calculateFxAndJacobian(this.currentVector, false);
    	//        	this.currentRMS= calcError(calcYminusFx(this.currentfX));
    	if (this.debugLevel>2) {
    		System.out.println("this.currentVector");
    		for (int i=0;i<this.currentVector.length;i++){
    			System.out.println(i+": "+ this.currentVector[i]);
    		}
    	}
    	if (this.showThisImages) showDiff (this.currentfX, "residual-series-"+this.seriesNumber);
Andrey Filippov's avatar
Andrey Filippov committed
6798

Andrey Filippov's avatar
Andrey Filippov committed
6799 6800 6801 6802 6803 6804 6805 6806
    	double [][] gridXYZCorr=null;
		gridXYZCorr=	calculateGridXYZCorr3D(
//				distortionCalibrationData,
				this.refineParameters.grid3DCorrection,
				this.refineParameters.rotateCorrection,
				this.refineParameters.grid3DMaximalZCorr, //20.0,
				this.refineParameters.targetShowPerImage);

Andrey Filippov's avatar
Andrey Filippov committed
6807
// TODO: make configurable and optional
Andrey Filippov's avatar
Andrey Filippov committed
6808 6809 6810 6811 6812 6813 6814 6815
		shrinkExtrapolateGridCorrection(
				gridXYZCorr, // dx,dy,dz, mask >0
				null,
				getGridWidth(),
				1, //preShrink,
				5, // expand,
				3.0, //  sigma,
				2.0); //double ksigma
Andrey Filippov's avatar
Andrey Filippov committed
6816

Andrey Filippov's avatar
Andrey Filippov committed
6817 6818
    	String [] titles={"X-correction(mm)","Y-correction(mm)","Z-correction","Weight"};
    	if (this.refineParameters.targetShowThisCorrection) {
6819
    		ShowDoubleFloatArrays.showArrays(gridXYZCorr, getGridWidth(), getGridHeight(),  true, "Grid corrections", titles);
Andrey Filippov's avatar
Andrey Filippov committed
6820 6821 6822 6823 6824 6825
    	}
    	if (!this.refineParameters.targetApplyCorrection) return false;
    	patternParameters.applyGridCorrection(gridXYZCorr, this.refineParameters.targetCorrectionScale);
    	return true;
    }

6826
//    public boolean modifyPixelCorrectionOld(DistortionCalibrationData distortionCalibrationData){ // old removed
Andrey Filippov's avatar
Andrey Filippov committed
6827

Andrey Filippov's avatar
Andrey Filippov committed
6828 6829 6830
    public void resetSensorCorrection(){
    	this.pixelCorrection=null;
    	this.pathNames=null;
Andrey Filippov's avatar
Andrey Filippov committed
6831
    }
Andrey Filippov's avatar
Andrey Filippov committed
6832 6833 6834 6835 6836 6837 6838 6839 6840 6841 6842 6843 6844 6845 6846 6847 6848 6849 6850 6851 6852 6853 6854 6855 6856 6857
    public void resetSensorCorrection(int sensorNum){
    	if ((this.pixelCorrection!=null) && (sensorNum<this.pixelCorrection.length) && (sensorNum>=0)) {
    		this.pixelCorrection[sensorNum]=null;
    		this.pathNames[sensorNum]=null;
    	}
    }
    public void initSensorCorrection(){
    	int numLayers=7;
    	int numChannels=this.fittingStrategy.distortionCalibrationData.getNumChannels(); // number of used channels
    	this.pixelCorrection=new double [numChannels][][];
    	this.pathNames=new String[numChannels];
    	double [][] masks=this.fittingStrategy.distortionCalibrationData.calculateSensorMasks();
    	for (int i=0;i<this.pixelCorrection.length;i++){
    		this.pixelCorrection[i]=new double [numLayers][];
    		this.pathNames[i]=null;
    		for (int n=0;n<numLayers;n++) this.pixelCorrection[i][n]=new double [masks[i].length];
    		for (int j=0;j<masks[i].length;j++) {
        		this.pixelCorrection[i][0][j]=0.0;
        		this.pixelCorrection[i][1][j]=0.0;
        		this.pixelCorrection[i][2][j]=masks[i][j];
    			this.pixelCorrection[i][3][j]=1.0;
    			this.pixelCorrection[i][4][j]=1.0;
    			this.pixelCorrection[i][5][j]=1.0;
    		}
    	}
    }
Andrey Filippov's avatar
Andrey Filippov committed
6858

6859 6860 6861 6862 6863 6864 6865 6866 6867 6868 6869 6870 6871 6872 6873 6874 6875 6876 6877 6878 6879
    public void initSensorCorrection(int sensorNum){
    	int numLayers=7;
    	if ((this.pixelCorrection!=null) && (sensorNum<this.pixelCorrection.length) && (sensorNum>=0)) {
    		this.pixelCorrection[sensorNum]=null;
    		this.pathNames[sensorNum]=null;
    	}
    	double [] mask = this.fittingStrategy.distortionCalibrationData.calculateSensorMasks(sensorNum);
    	this.pixelCorrection[sensorNum]=new double [numLayers][];
    	this.pathNames[sensorNum]=null;
    	for (int n=0;n<numLayers;n++) this.pixelCorrection[sensorNum][n]=new double [mask.length];
    	for (int j=0;j<mask.length;j++) {
    		this.pixelCorrection[sensorNum][0][j]=0.0;
    		this.pixelCorrection[sensorNum][1][j]=0.0;
    		this.pixelCorrection[sensorNum][2][j]=mask[j];
    		this.pixelCorrection[sensorNum][3][j]=1.0;
    		this.pixelCorrection[sensorNum][4][j]=1.0;
    		this.pixelCorrection[sensorNum][5][j]=1.0;
    	}
    }


Andrey Filippov's avatar
Andrey Filippov committed
6880 6881 6882 6883
    /*
     * Adds new correction to the current one with the result to the new one. If update, the old arrays are also modified/created
     */
    public boolean applySensorCorrection(
6884 6885 6886 6887
    		RefineParameters refineParameters,
//    		boolean update,
//    		boolean updateFlatField,
//    		double scale,
Andrey Filippov's avatar
Andrey Filippov committed
6888 6889 6890
    		double [][][] sensorXYCorr,
    		DistortionCalibrationData distortionCalibrationData){
		int numLayers=6;
6891 6892 6893 6894 6895 6896 6897
///		int decimate=distortionCalibrationData.eyesisCameraParameters.decimateMasks;
///		int width= distortionCalibrationData.eyesisCameraParameters.sensorWidth;
///		int height=distortionCalibrationData.eyesisCameraParameters.sensorHeight;
///    	if ((this.pixelCorrection!=null) && (this.pixelCorrectionDecimation!=decimate)){
///    		IJ.showMessage("Error","Can not apply correction as the current correction and the new one have different decimations");
///    		return false;
///    	}
6898 6899
//    	if ((this.pixelCorrection==null) && !update && !updateFlatField) return true;
//    	if (update){
6900 6901 6902
///    		this.pixelCorrectionDecimation=decimate;
///    		this.pixelCorrectionWidth=width;
///    		this.pixelCorrectionHeight=height;
6903
//    	}
Andrey Filippov's avatar
Andrey Filippov committed
6904
        if (this.pixelCorrection==null) {
6905
        	if (this.debugLevel>1) System.out.println("Initializing pixelCorrection array...");
Andrey Filippov's avatar
Andrey Filippov committed
6906 6907 6908 6909 6910 6911 6912
        	this.pixelCorrection=new double [sensorXYCorr.length][][];
        	this.pathNames=new String[sensorXYCorr.length];
        	for (int i=0;i<this.pixelCorrection.length;i++){
        		this.pixelCorrection[i]=null;
        		this.pathNames[i]=null;
        	}
        }
Andrey Filippov's avatar
Andrey Filippov committed
6913

Andrey Filippov's avatar
Andrey Filippov committed
6914 6915 6916 6917 6918 6919 6920 6921 6922 6923 6924 6925 6926 6927 6928 6929 6930 6931
        if (this.pixelCorrection.length<sensorXYCorr.length){ // OK to update even if !update
        	if (this.debugLevel>1) System.out.println("Increasing number of sensors in pixelCorrection array");
        	double [][][] tmp=new double[sensorXYCorr.length][][];
        	String [] tmpPaths=new String[sensorXYCorr.length];
        	for (int i=0;i<tmp.length;i++){
        		if (i<this.pixelCorrection.length){
        			tmp[i]=this.pixelCorrection[i];
        			tmpPaths[i]=this.pathNames[i];
        		}
        		else {
        			tmp[i]=null;
        			tmpPaths[i]=null;
        		}
        	}
        	this.pixelCorrection=tmp;
        	this.pathNames=tmpPaths;
        }
        for (int i=0;i<sensorXYCorr.length;i++) if (sensorXYCorr[i]!=null){
6932 6933
//			boolean small_sensor = fittingStrategy.distortionCalibrationData.isSmallSensor(i);
			boolean small_sensor = fittingStrategy.distortionCalibrationData.getSmallSensors()[i];
6934 6935 6936 6937 6938 6939
			RefineParameters rp = small_sensor ? refineParameters.refineParametersSmall : refineParameters;
    		boolean update =          rp.applyCorrection;
    		boolean updateFlatField = rp.applyFlatField;
    		double scale =            rp.correctionScale;


Andrey Filippov's avatar
Andrey Filippov committed
6940 6941 6942 6943
        	boolean in6=sensorXYCorr[i].length==6; // was - 7
        	int indxR=in6?3:4;
        	int indxG=in6?4:5;
        	int indxB=in6?5:6;
Andrey Filippov's avatar
Andrey Filippov committed
6944
        	double [] sensorMask=in6?((fittingStrategy.distortionCalibrationData.sensorMasks==null)?null:fittingStrategy.distortionCalibrationData.sensorMasks[i]):sensorXYCorr[i][2];
Andrey Filippov's avatar
Andrey Filippov committed
6945 6946 6947 6948 6949 6950 6951 6952 6953 6954 6955 6956 6957 6958 6959 6960 6961
        	if (this.pixelCorrection[i]==null) {
        		if (update || updateFlatField) {
        			this.pixelCorrection[i]=new double [numLayers][];
        			this.pixelCorrection[i][0]=sensorXYCorr[i][0];
        			this.pixelCorrection[i][1]=sensorXYCorr[i][1];
        			if (sensorMask!=null){
        				this.pixelCorrection[i][2]=sensorMask;
        			} else {
        				this.pixelCorrection[i][2]= new double[this.pixelCorrection[i][0].length];
    					for (int j=0;j<this.pixelCorrection[i][2].length;j++) this.pixelCorrection[i][2][j]=1.0;
        			}
        			if (sensorXYCorr[i].length>=7){
        				this.pixelCorrection[i][3]=sensorXYCorr[i][indxR];
        				this.pixelCorrection[i][4]=sensorXYCorr[i][indxG];
        				this.pixelCorrection[i][5]=sensorXYCorr[i][indxB];
        			} else {
        				for (int n=3;n<numLayers;n++){
6962 6963 6964 6965 6966 6967 6968 6969 6970
//        					this.pixelCorrection[i][n]=new double[this.pixelCorrection[0].length];
        					this.pixelCorrection[i][n]=new double[this.pixelCorrection[i][0].length]; // number of pixels
        					for (int j=0;j<this.pixelCorrection[i][0].length;j++) {
        						if ((i >= pixelCorrection.length) || (n >= pixelCorrection[i].length) || (j >= pixelCorrection[i][n].length)){
        							System.out.println("i="+i+", n="+n+", j="+j);
        							continue;
        						}
        						this.pixelCorrection[i][n][j]=1.0; // java.lang.ArrayIndexOutOfBoundsException: Index 6 out of bounds for length 6
        					}
Andrey Filippov's avatar
Andrey Filippov committed
6971 6972 6973 6974 6975 6976 6977 6978 6979 6980 6981 6982 6983 6984 6985 6986 6987
        				}

        			}
        		}
        	} else  {
        		for (int j=0;j<sensorXYCorr[i][0].length;j++){
        			// removed - now it is already done
///        			sensorXYCorr[i][0][j]=this.pixelCorrection[i][0][j]+scale*sensorXYCorr[i][0][j];
///        			sensorXYCorr[i][1][j]=this.pixelCorrection[i][1][j]+scale*sensorXYCorr[i][1][j];
        			if (scale==1.0) { // recovering from Double.NaN in old values - still do not know where it came from in the first place
        			} else {
        				if (!in6){
        					sensorXYCorr[i][2][j]=this.pixelCorrection[i][2][j]+scale*(sensorXYCorr[i][2][j]-this.pixelCorrection[i][2][j]);
        				}
            			sensorXYCorr[i][indxR][j]=this.pixelCorrection[i][3][j]+scale*(sensorXYCorr[i][indxR][j]-this.pixelCorrection[i][3][j]);
            			sensorXYCorr[i][indxG][j]=this.pixelCorrection[i][4][j]+scale*(sensorXYCorr[i][indxG][j]-this.pixelCorrection[i][4][j]);
            			sensorXYCorr[i][indxB][j]=this.pixelCorrection[i][5][j]+scale*(sensorXYCorr[i][indxB][j]-this.pixelCorrection[i][5][j]);
Andrey Filippov's avatar
Andrey Filippov committed
6988

Andrey Filippov's avatar
Andrey Filippov committed
6989 6990 6991 6992 6993 6994 6995 6996 6997 6998 6999 7000 7001 7002 7003 7004 7005
        			}
        		}
        		if (update){
        			this.pixelCorrection[i][0]=sensorXYCorr[i][0];
        			this.pixelCorrection[i][1]=sensorXYCorr[i][1];
        		}
        		if (updateFlatField){
        			if (!in6){
        				this.pixelCorrection[i][2]=sensorXYCorr[i][2];
        			}
        			this.pixelCorrection[i][3]=sensorXYCorr[i][indxR];
        			this.pixelCorrection[i][4]=sensorXYCorr[i][indxG];
        			this.pixelCorrection[i][5]=sensorXYCorr[i][indxB];
        		}
        	}
        }
        return true;
Andrey Filippov's avatar
Andrey Filippov committed
7006

Andrey Filippov's avatar
Andrey Filippov committed
7007 7008 7009 7010 7011 7012 7013 7014
    }
    public String getSensorPath(int numSensor){ //<0 - first available;
    	if ((this.pathNames == null) || (numSensor>=this.pathNames.length)) return null;
    	if (numSensor>=0) return this.pathNames[numSensor];
    	for (int i=0;i<this.pathNames.length;i++) if ((this.pathNames[i]!=null) && (this.pathNames[i].length()>0)) return this.pathNames[i];
    	return null;
    }
    public void saveDistortionAsImageStack(
7015 7016
    		DistortionCalibrationData distortionCalibrationData, // null OK
    		CamerasInterface camerasInterface, // to save channel map
Andrey Filippov's avatar
Andrey Filippov committed
7017 7018 7019 7020 7021 7022 7023 7024 7025 7026 7027 7028 7029
    		String title,
    		String path,
    		boolean emptyOK){
    	int indexPeriod=path.indexOf('.',path.lastIndexOf(Prefs.getFileSeparator()));
    	int indexSuffix=indexPeriod;
    	String digits="0123456789";
    	for (int i=1;i<=2;i++) if (digits.indexOf(path.charAt(indexSuffix-1))>=0) indexSuffix--; // remove 1 or 2 digits before period
    	boolean hadSuffix= (path.charAt(indexSuffix-1)=='-');
    	int numSubCameras=fittingStrategy.distortionCalibrationData.eyesisCameraParameters.eyesisSubCameras[0].length;
    	for (int chNum=0;chNum<numSubCameras;chNum++) if (emptyOK  || ((this.pixelCorrection!=null) && (chNum<this.pixelCorrection.length) && (this.pixelCorrection[chNum]!=null)))  {
    		String channelPath= (hadSuffix?path.substring(0,indexSuffix):(path.substring(0,indexPeriod)+"-"))+
    		String.format("%02d",chNum)+path.substring(indexPeriod);
    		saveDistortionAsImageStack(
7030
    				distortionCalibrationData,
Andrey Filippov's avatar
Andrey Filippov committed
7031 7032 7033 7034 7035 7036 7037
    				camerasInterface, // to save channel map
    				title,
    				channelPath,
    				chNum,
    				emptyOK);
    	}
    }
Andrey Filippov's avatar
Andrey Filippov committed
7038

Andrey Filippov's avatar
Andrey Filippov committed
7039
    public ImagePlus saveDistortionAsImageStack(
7040 7041
    		DistortionCalibrationData distortionCalibrationData, // null OK
    		CamerasInterface camerasInterface, // to save channel map
Andrey Filippov's avatar
Andrey Filippov committed
7042 7043 7044 7045 7046
    		String title,
    		String path,
    		int numSensor,
    		boolean emptyOK){
    	ImagePlus imp=getDistortionAsImageStack(
7047
    			distortionCalibrationData,
Andrey Filippov's avatar
Andrey Filippov committed
7048 7049 7050 7051 7052 7053 7054 7055 7056 7057 7058 7059 7060
    			camerasInterface, // to save channel map
    			title,
    			numSensor,
    			emptyOK);
    	if (imp==null) return null;
    	boolean realData= (this.pixelCorrection!=null) && (this.pixelCorrection[numSensor]!=null);
    	FileSaver fs=new FileSaver(imp);
    	String msg="Saving "+(realData?"":"EMPTY")+" sensor distortions to "+path;
    	if (updateStatus) IJ.showStatus(msg);
    	if (this.debugLevel>0) System.out.println(msg);
    	fs.saveAsTiffStack(path);
    	if (this.pathNames==null){
    		this.pathNames=new String[this.fittingStrategy.distortionCalibrationData.getNumChannels()];
Andrey Filippov's avatar
Andrey Filippov committed
7061
    		for (int i=0;i<this.pathNames.length;i++) this.pathNames[i]=null;
Andrey Filippov's avatar
Andrey Filippov committed
7062 7063 7064 7065 7066 7067
    	}
    	this.pathNames[numSensor]=path;
    	return imp;
    }

//  /    	int numChannels=this.fittingStrategy.distortionCalibrationData.getNumChannels(); // number of used channels
Andrey Filippov's avatar
Andrey Filippov committed
7068
// TODO: Currently saves data from Station 0
Andrey Filippov's avatar
Andrey Filippov committed
7069
    public ImagePlus getDistortionAsImageStack(
7070 7071
    		DistortionCalibrationData distortionCalibrationData, // null OK - will use old way from fittingStrategy
    		CamerasInterface camerasInterface, // to save channel map
Andrey Filippov's avatar
Andrey Filippov committed
7072 7073 7074
    		String title,
    		int numSensor,
    		boolean emptyOK){
7075 7076 7077
    	if (distortionCalibrationData == null) {
    		distortionCalibrationData = this.fittingStrategy.distortionCalibrationData;
    	}
Andrey Filippov's avatar
Andrey Filippov committed
7078 7079 7080 7081 7082 7083 7084 7085 7086 7087 7088 7089 7090 7091
    	int stationNumber=0;
    	String [] titles={"X-corr","Y-corr","mask","R-vign","G-vign","B-vign"};
    	double [][] pixelCorr=null;
    	if (!emptyOK &&((this.pixelCorrection==null) ||
    			(numSensor<0) ||
    		(numSensor>=this.pixelCorrection.length) ||
    		(this.pixelCorrection[numSensor]==null)))
    			{
    		String msg="Sensor correction data is not available";
    		IJ.showMessage("Error",msg);
    		throw new IllegalArgumentException (msg);
    	}
    	if ((this.pixelCorrection!=null) && (numSensor>=0) && (numSensor<this.pixelCorrection.length))
    		pixelCorr=this.pixelCorrection[numSensor];
7092 7093 7094 7095 7096 7097

    	int width =  distortionCalibrationData.eyesisCameraParameters.getSensorWidth(numSensor) /
    			distortionCalibrationData.eyesisCameraParameters.getDecimateMasks(numSensor);
    	int height = distortionCalibrationData.eyesisCameraParameters.getSensorHeight(numSensor) /
    			distortionCalibrationData.eyesisCameraParameters.getDecimateMasks(numSensor);

Andrey Filippov's avatar
Andrey Filippov committed
7098 7099
//    	int length=this.pixelCorrection[numSensor][0].length; // should be == width*height
    	int length=width*height;
Andrey Filippov's avatar
Andrey Filippov committed
7100

Andrey Filippov's avatar
Andrey Filippov committed
7101 7102 7103
    	float [][]pixels=new float [titles.length][length]; // dx, dy, sensor mask,v-r,v-g,v-b
    	// assuming all sensors have the same dimension
    	double [] mask=null;
7104 7105 7106 7107 7108 7109 7110 7111 7112
    	if (distortionCalibrationData.sensorMasks == null) {
        	if (this.debugLevel>0) {
        		System.out.println("sensorMasks are null, calculating");
        	}

    		distortionCalibrationData.calculateSensorMasks();
    	}
    	
    	if (distortionCalibrationData.sensorMasks.length<=numSensor) return null; // no data (make if distortionCalibrationData.sensorMasks==null
7113 7114 7115
    	if ((distortionCalibrationData.sensorMasks!=null) &&
    			(distortionCalibrationData.sensorMasks[numSensor]!=null)){
    		mask=distortionCalibrationData.sensorMasks[numSensor];
Andrey Filippov's avatar
Andrey Filippov committed
7116 7117 7118 7119 7120 7121 7122 7123 7124 7125
    	}

    	for (int index=0;index<length;index++){
    		if (pixelCorr==null){
        		pixels[0][index]=  0.0f;
        		pixels[1][index]=  0.0f;
        		for (int n=3;n<pixels.length;n++) pixels[n][index]= 1.0f; // normalize?
    		} else {
    			pixels[0][index]=  (float) pixelCorr[0][index];
    			pixels[1][index]=  (float) pixelCorr[1][index];
7126 7127 7128 7129 7130 7131 7132 7133 7134
        		for (int n=3;n<pixels.length;n++) {
        			if (pixelCorr[n] != null) {
        				if ((n>=pixels.length) || (index >= pixels[n].length) || (n>=pixelCorr.length) || (index >= pixelCorr[n].length)) {
        					System.out.println (" Bug: n="+n+", index="+index);
        					continue;
        				}
        				pixels[n][index]= (float) pixelCorr[n][index]; // java.lang.NullPointerException
        			}
        		}
Andrey Filippov's avatar
Andrey Filippov committed
7135 7136 7137
    		}
    		// get sensor mask here
    		pixels[2][index]=  (mask==null)? 1.0f:((float) mask[index]);
Andrey Filippov's avatar
Andrey Filippov committed
7138

Andrey Filippov's avatar
Andrey Filippov committed
7139 7140 7141 7142 7143 7144 7145
    	}
    	ImagePlus imp=null;
  		ImageStack stack=new ImageStack(width,height);
   		for (int n=0;n<pixels.length;n++)  stack.addSlice(titles[n],    pixels[n]);
   		imp = new ImagePlus(title, stack);
        // set properties sufficient to un-apply distortions to the image
   		// First - corrections
7146
    	EyesisSubCameraParameters subCam=distortionCalibrationData.eyesisCameraParameters.eyesisSubCameras[stationNumber][numSensor];
7147
    	subCam.updateCartesian(); // recalculate other parameters
7148
    	double entrancePupilForward=distortionCalibrationData.eyesisCameraParameters.entrancePupilForward[stationNumber];
Andrey Filippov's avatar
Andrey Filippov committed
7149 7150 7151 7152
    	imp.setProperty("VERSION",  "1.0");
    	imp.setProperty("comment_arrays",  "Array corrections from acquired image to radially distorted, in pixels");
    	imp.setProperty("arraysSet",  ""+(pixelCorr!=null)); // per-pixel arrays are not set, using 0.0
    	imp.setProperty("maskSet",     ""+(mask!=null)); // per-pixel masks is not set, using 1.0
7153 7154 7155
    	imp.setProperty("pixelCorrectionWidth",  ""+distortionCalibrationData.eyesisCameraParameters.getSensorWidth(numSensor)); // this.pixelCorrectionWidth);
    	imp.setProperty("pixelCorrectionHeight", ""+distortionCalibrationData.eyesisCameraParameters.getSensorHeight(numSensor));
    	imp.setProperty("pixelCorrectionDecimation", ""+distortionCalibrationData.eyesisCameraParameters.getDecimateMasks(numSensor));
Andrey Filippov's avatar
Andrey Filippov committed
7156 7157 7158 7159 7160 7161 7162
    	imp.setProperty("comment_decimation", "when decimation use integer divide to find the index, corection values are in non-decimated pixels");
    	imp.setProperty("distortion_formula",  "(normalized by distortionRadius in mm) Rdist/R=A8*R^7+A7*R^6+A6*R^5+A5*R^4+A*R^3+B*R^2+C*R+(1-A6-A7-A6-A5-A-B-C)");
    	imp.setProperty("distortionRadius", ""+subCam.distortionRadius);
    	imp.setProperty("distortionRadius_unuts", "mm");
    	imp.setProperty("focalLength", ""+subCam.focalLength);
    	imp.setProperty("focalLength_units", "mm");
    	imp.setProperty("pixelSize", ""+subCam.pixelSize);
7163
    	imp.setProperty("lineTime",  ""+subCam.lineTime);
Andrey Filippov's avatar
Andrey Filippov committed
7164 7165 7166 7167 7168 7169 7170 7171 7172 7173 7174 7175
    	imp.setProperty("pixelSize_units", "um");
    	imp.setProperty("distortionA8", ""+subCam.distortionA8);
    	imp.setProperty("distortionA7", ""+subCam.distortionA7);
    	imp.setProperty("distortionA6", ""+subCam.distortionA6);
    	imp.setProperty("distortionA5", ""+subCam.distortionA5);
    	imp.setProperty("distortionA", ""+subCam.distortionA);
    	imp.setProperty("distortionB", ""+subCam.distortionB);
    	imp.setProperty("distortionC", ""+subCam.distortionC);
    	imp.setProperty("comment_px0_py0", "lens center on the sensor, in pixels");
    	imp.setProperty("px0", ""+subCam.px0);
    	imp.setProperty("py0", ""+subCam.py0);
    	imp.setProperty("comment_azimuth", "lens center azimuth, CW from top, degrees");
7176 7177 7178 7179 7180 7181 7182 7183 7184 7185 7186 7187 7188 7189 7190 7191
    	imp.setProperty("height",  ""+subCam.height);
    	imp.setProperty("comment_elevation", "lens elevation from horizontal, positive - above horizon, degrees");
    	imp.setProperty("elevation",  ""+subCam.theta);
    	imp.setProperty("comment_roll", "lens rotation around the lens axis. Positive - CW looking to the target, degrees");
    	imp.setProperty("roll",  ""+subCam.psi);

    	imp.setProperty("comment_cartesian", "Use cartesian coordinates for the sensor in the camera CS (forward, right,aheading), instead of (radius, azimuth, heading)");
    	imp.setProperty("cartesian",  ""+subCam.cartesian);
// cartesian parameters
    	imp.setProperty("comment_forward", "lens forward (towards target) displacement in the camera CS");
    	imp.setProperty("forward",  ""+subCam.forward);
    	imp.setProperty("comment_right", "lens right (looking towards target) displacement in the camera CS");
    	imp.setProperty("right",  ""+subCam.right);
    	imp.setProperty("comment_aheading", "lens axis horizontal direction, degrees. Positive - CW from the target (looking from top)");
    	imp.setProperty("aheading",  ""+subCam.heading);
// cylindrical parameters
Andrey Filippov's avatar
Andrey Filippov committed
7192 7193 7194 7195 7196 7197 7198 7199 7200 7201
    	imp.setProperty("azimuth", ""+subCam.azimuth);
    	imp.setProperty("comment_radius", "lens center distance from the camera vertical axis, mm");
    	imp.setProperty("radius",  ""+subCam.radius);
    	imp.setProperty("comment_height", "lens center vertical position from the head center, mm");
    	imp.setProperty("comment_heading", "lens heading - added to azimuth");
    	imp.setProperty("heading",  ""+subCam.phi);

    	imp.setProperty("comment_channel", "number of the sensor (channel) in the camera");
    	imp.setProperty("channel",  ""+numSensor);
    	imp.setProperty("comment_subcamera", "number of the subcamera with individual IP, starting with 0");
7202 7203 7204 7205 7206 7207 7208 7209
    	if (camerasInterface != null) {
    		subCam.subcamera =   camerasInterface.getSubCamera(numSensor);
    		subCam.sensor_port = camerasInterface.getSensorPort(numSensor);
    		subCam.subchannel =  camerasInterface.getSubChannel(numSensor);
    	}

    	imp.setProperty("subcamera",  ""+subCam.subcamera);
		imp.setProperty("sensor_port",""+subCam.sensor_port);
Andrey Filippov's avatar
Andrey Filippov committed
7210

Andrey Filippov's avatar
Andrey Filippov committed
7211
    	imp.setProperty("comment_subchannel", "number of the sensor port on a subcamera (0..2)");
7212
    	imp.setProperty("subchannel",  ""+subCam.subchannel);
Andrey Filippov's avatar
Andrey Filippov committed
7213 7214
    	imp.setProperty("comment_entrancePupilForward",  "entrance pupil distance from the azimuth/radius/height, outwards in mm");
    	imp.setProperty("entrancePupilForward",  ""+entrancePupilForward); // currently global, decoders will use per-sensor
7215
       	imp.setProperty("comment_defects", "Sensor hot/cold pixels list as x:y:difference");
Andrey Filippov's avatar
Andrey Filippov committed
7216

7217 7218
       	imp.setProperty("comment_lensDistortionModel", "Integer specifying lens distrotion model (0 - radial)");
       	imp.setProperty("lensDistortionModel", ""+subCam.lensDistortionModel);
Andrey Filippov's avatar
Andrey Filippov committed
7219

7220 7221 7222 7223 7224 7225 7226 7227
		for (int i=0;i<subCam.r_xy.length;i++){
			imp.setProperty("r_xy_"+i+"_x",subCam.r_xy[i][0]+"");
			imp.setProperty("r_xy_"+i+"_y",subCam.r_xy[i][1]+"");
		}
		for (int i=0;i<subCam.r_od.length;i++){
			imp.setProperty("r_od_"+i+"_o",subCam.r_od[i][0]+"");
			imp.setProperty("r_od_"+i+"_d",subCam.r_od[i][1]+"");
		}
7228 7229 7230 7231 7232 7233 7234 7235 7236 7237
       	if (subCam.defectsXY!=null){
    		StringBuffer sb = new StringBuffer();
    		for (int i=0;i<subCam.defectsXY.length;i++){
    			if (sb.length()>0) sb.append(" ");
    			sb.append(subCam.defectsXY[i][0]+":"+subCam.defectsXY[i][1]+":"+subCam.defectsDiff[i]);
    		}
    		imp.setProperty("defects", sb.toString());
//       	} else {
//    		imp.setProperty("defects", null);
       	}
Andrey Filippov's avatar
Andrey Filippov committed
7238

Andrey Filippov's avatar
Andrey Filippov committed
7239 7240 7241 7242 7243
    	//camerasInterface, numSensor
    	(new JP46_Reader_camera(false)).encodeProperiesToInfo(imp);
    	imp.getProcessor().resetMinAndMax();
    	return imp;
    }
Andrey Filippov's avatar
Andrey Filippov committed
7244 7245


7246
    public void setDistortionFromImageStack(
7247 7248
    		DistortionCalibrationData distortionCalibrationData, // null OK
    		EyesisCameraParameters eyesisCameraParameters, // null OK
7249 7250 7251
    		String path,
    		boolean overwriteExtrinsic,
    		boolean overwriteDistortion){
Andrey Filippov's avatar
Andrey Filippov committed
7252
    	int indexPeriod=path.indexOf('.',path.lastIndexOf(Prefs.getFileSeparator()));
7253 7254 7255 7256 7257 7258 7259
    	if (eyesisCameraParameters == null) {
    		eyesisCameraParameters = fittingStrategy.distortionCalibrationData.eyesisCameraParameters;
    	}
    	if (distortionCalibrationData == null) {
    		distortionCalibrationData = fittingStrategy.distortionCalibrationData;
    	}
    	int numSubCameras=distortionCalibrationData.eyesisCameraParameters.eyesisSubCameras[0].length;
Andrey Filippov's avatar
Andrey Filippov committed
7260 7261 7262
    	for (int chNum=0;chNum<numSubCameras;chNum++){
    		String channelPath=path.substring(0,indexPeriod-2)+String.format("%02d",chNum)+path.substring(indexPeriod);
    		try { // disable here for now
7263 7264 7265 7266 7267 7268 7269
    			setDistortionFromImageStack(
    					distortionCalibrationData,
    					channelPath,
    					chNum,
    					false,
    					overwriteExtrinsic,
    					overwriteDistortion);
Andrey Filippov's avatar
Andrey Filippov committed
7270 7271 7272 7273 7274 7275
    		} catch (Exception e) {
    			System.out.println("setDistortionFromImageStack(): " + e.toString());
    			e.printStackTrace();
    		}
    	}
    }
Andrey Filippov's avatar
Andrey Filippov committed
7276

7277
    public void setDistortionFromImageStack(
7278
    		DistortionCalibrationData distortionCalibrationData,
7279 7280 7281 7282 7283
    		String path,
    		int numSensor,
    		boolean reportProblems,
    		boolean overwriteExtrinsic,
    		boolean overwriteDistortion){
7284 7285
    	Opener opener=new Opener();
    	ImagePlus imp=opener.openImage("", path);
Andrey Filippov's avatar
Andrey Filippov committed
7286 7287 7288 7289 7290 7291 7292
    	if (imp==null) {
    		if (!reportProblems) return;
    		String msg="Failed to read sensor calibration data file "+path;
    		IJ.showMessage("Error",msg);
    		System.out.println(msg);
    		throw new IllegalArgumentException (msg);
    	}
7293
    	if (this.debugLevel>0) System.out.println("Read "+path+" as a sensor calibration data");
Andrey Filippov's avatar
Andrey Filippov committed
7294
    	(new JP46_Reader_camera(false)).decodeProperiesFromInfo(imp);
7295 7296 7297 7298 7299
    	setDistortionFromImageStack(distortionCalibrationData,
    			imp,
    			numSensor,
    			overwriteExtrinsic,
    			overwriteDistortion);
Andrey Filippov's avatar
Andrey Filippov committed
7300 7301
    	this.pathNames[numSensor]=path;
    }
Andrey Filippov's avatar
Andrey Filippov committed
7302

Andrey Filippov's avatar
Andrey Filippov committed
7303
    //TODO: look more after testing. Currently all station parameters are set from the sensor images, may be minor differences
7304
    public void setDistortionFromImageStack(
7305
    		DistortionCalibrationData distortionCalibrationData,
7306 7307 7308 7309
    		ImagePlus imp,
    		int numSensor,
    		boolean overwriteExtrinsic,
    		boolean overwriteDistortion){
7310 7311 7312
    	if (distortionCalibrationData == null) {
    		distortionCalibrationData = this.fittingStrategy.distortionCalibrationData;
    	}
Andrey Filippov's avatar
Andrey Filippov committed
7313 7314 7315 7316 7317 7318 7319 7320 7321 7322 7323 7324 7325 7326 7327 7328 7329 7330 7331 7332 7333 7334 7335 7336 7337 7338 7339 7340 7341 7342 7343 7344 7345
//    	int corrX=0,corrY=1,
    	int corrMask=2;
    	if (numSensor<0) {
    		System.out.println("setDistortionFromImageStack(): Tried to read negative channel");
    		return;
    	}
//		System.out.println("setDistortionFromImageStack(): processing channel channel "+numSensor);
    	if (imp == null){
    		String msg="Distortions image is null";
    		IJ.showMessage("Error",msg);
    		throw new IllegalArgumentException (msg);
    	}
        String [] requiredProperties={
        		"pixelCorrectionWidth",
        		"pixelCorrectionHeight",
        		"pixelCorrectionDecimation",
        		"distortionRadius",
        		"focalLength",
        		"pixelSize",
//        		"distortionA8",
//        		"distortionA7",
//        		"distortionA6",
        		"distortionA5",
        		"distortionA",
        		"distortionB",
        		"distortionC",
        		"px0",
        		"py0"};
        for (int i=0; i<requiredProperties.length;i++) if (imp.getProperty(requiredProperties[i])==null){
    		String msg="Required property "+requiredProperties[i]+" is not defined in "+imp.getTitle();
    		IJ.showMessage("Error",msg);
    		throw new IllegalArgumentException (msg);
        }
Andrey Filippov's avatar
Andrey Filippov committed
7346

Andrey Filippov's avatar
Andrey Filippov committed
7347 7348 7349 7350 7351
    	if (imp.getStackSize()<3){
    		String msg="Expecting >=3 slices, got "+imp.getStackSize();
    		IJ.showMessage("Error",msg);
    		throw new IllegalArgumentException (msg);
    	}
Andrey Filippov's avatar
Andrey Filippov committed
7352

Andrey Filippov's avatar
Andrey Filippov committed
7353 7354 7355 7356 7357
		ImageStack stack = imp.getStack();
		float [][] pixels =new float[stack.getSize()][];
    	for (int i=0;i<pixels.length;i++) pixels[i]= (float[]) stack.getPixels(i+1);


7358
        int numSubCameras=distortionCalibrationData.eyesisCameraParameters.eyesisSubCameras[0].length;
Andrey Filippov's avatar
Andrey Filippov committed
7359 7360 7361 7362 7363 7364
        if (numSensor>=numSubCameras){
    		String msg="Loaded calibration channel number "+numSensor+"is higher than maximal in the system "+(numSubCameras-1);
    		IJ.showMessage("Error",msg);
    		throw new IllegalArgumentException (msg);
        }
//		System.out.println("setDistortionFromImageStack(): processing channel channel "+numSensor);
Andrey Filippov's avatar
Andrey Filippov committed
7365

Andrey Filippov's avatar
Andrey Filippov committed
7366
    	EyesisSubCameraParameters subCam;
7367 7368
    	EyesisCameraParameters cam=     distortionCalibrationData.eyesisCameraParameters;
        if ((distortionCalibrationData!=null) && (distortionCalibrationData.eyesisCameraParameters!=null)){
7369 7370 7371 7372
        	// Now it is the same
///    		distortionCalibrationData.eyesisCameraParameters.decimateMasks=this.pixelCorrectionDecimation;
///    		distortionCalibrationData.eyesisCameraParameters.sensorWidth=  this.pixelCorrectionWidth;
///    		distortionCalibrationData.eyesisCameraParameters.sensorHeight=this.pixelCorrectionHeight;
Andrey Filippov's avatar
Andrey Filippov committed
7373
        }
7374 7375
        for (int stationNumber=0; stationNumber < distortionCalibrationData.eyesisCameraParameters.numStations; stationNumber++){
        	subCam=distortionCalibrationData.eyesisCameraParameters.eyesisSubCameras[stationNumber][numSensor];
7376 7377 7378
        	distortionCalibrationData.eyesisCameraParameters.setSensorWidth(  numSensor, Integer.parseInt ((String) imp.getProperty("pixelCorrectionWidth")));
        	distortionCalibrationData.eyesisCameraParameters.setSensorHeight( numSensor, Integer.parseInt ((String) imp.getProperty("pixelCorrectionHeight")));
        	distortionCalibrationData.eyesisCameraParameters.setDecimateMasks(numSensor, Integer.parseInt ((String) imp.getProperty("pixelCorrectionDecimation")));
Andrey Filippov's avatar
Andrey Filippov committed
7379 7380 7381 7382

        	subCam.distortionRadius=        Double.parseDouble((String) imp.getProperty("distortionRadius"));
        	subCam.focalLength=             Double.parseDouble((String) imp.getProperty("focalLength"));
        	subCam.pixelSize=               Double.parseDouble((String) imp.getProperty("pixelSize"));
7383 7384 7385 7386 7387 7388
        	if (imp.getProperty("lineTime") != null) {
            	subCam.pixelSize=               Double.parseDouble((String) imp.getProperty("lineTime"));
        	} else { // fix older saved files
        		if (subCam.pixelSize < 5.0) {
        			subCam.pixelSize=3.638E-5;
	        	} else if (distortionCalibrationData.eyesisCameraParameters.getSensorWidth(numSensor) == 640){ // Boson
7389
	        		subCam.lineTime = 3.2552e-05; // 2.7778e-05; // 12um pixel, Boson
7390 7391 7392 7393
	        	} else {
	        		subCam.lineTime = 7.8e-05; // 12um pixel, Lepton (may7 be wrong)
	        	}
        	}
Andrey Filippov's avatar
Andrey Filippov committed
7394 7395 7396 7397 7398 7399 7400 7401 7402 7403 7404 7405 7406 7407 7408 7409 7410 7411 7412 7413 7414 7415
        	if (imp.getProperty("distortionA8")!=null) {
        		subCam.distortionA8=            Double.parseDouble((String) imp.getProperty("distortionA8"));
        	} else subCam.distortionA8=0.0;
        	if (imp.getProperty("distortionA7")!=null) {
        		subCam.distortionA7=            Double.parseDouble((String) imp.getProperty("distortionA7"));
        	} else subCam.distortionA7=0.0;
        	if (imp.getProperty("distortionA6")!=null) {
        		subCam.distortionA6=            Double.parseDouble((String) imp.getProperty("distortionA6"));
        	} else subCam.distortionA6=0.0;
        	subCam.distortionA5=            Double.parseDouble((String) imp.getProperty("distortionA5"));
        	subCam.distortionA=             Double.parseDouble((String) imp.getProperty("distortionA"));
        	subCam.distortionB=             Double.parseDouble((String) imp.getProperty("distortionB"));
        	subCam.distortionC=             Double.parseDouble((String) imp.getProperty("distortionC"));
        	subCam.px0=                     Double.parseDouble((String) imp.getProperty("px0"));
        	subCam.py0=                     Double.parseDouble((String) imp.getProperty("py0"));
        	if (imp.getProperty("azimuth")  !=null) subCam.azimuth= Double.parseDouble((String) imp.getProperty("azimuth"));
        	if (imp.getProperty("radius")   !=null) subCam.radius=  Double.parseDouble((String) imp.getProperty("radius"));
        	if (imp.getProperty("height")   !=null) subCam.height=  Double.parseDouble((String) imp.getProperty("height"));
        	if (imp.getProperty("entrancePupilForward")!=null) cam.entrancePupilForward[stationNumber]= Double.parseDouble((String) imp.getProperty("entrancePupilForward"));
        	if (imp.getProperty("heading")  !=null) subCam.phi=     Double.parseDouble((String) imp.getProperty("heading"));
        	if (imp.getProperty("elevation")!=null) subCam.theta=   Double.parseDouble((String) imp.getProperty("elevation"));
        	if (imp.getProperty("roll")!=null) subCam.psi=          Double.parseDouble((String) imp.getProperty("roll"));
Andrey Filippov's avatar
Andrey Filippov committed
7416

7417 7418 7419
        	if (imp.getProperty("forward")  !=null) subCam.forward=  Double.parseDouble((String) imp.getProperty("forward"));
        	if (imp.getProperty("right")    !=null) subCam.right=    Double.parseDouble((String) imp.getProperty("right"));
        	if (imp.getProperty("aheading") !=null) subCam.heading= Double.parseDouble((String) imp.getProperty("aheading"));
Andrey Filippov's avatar
Andrey Filippov committed
7420

7421 7422 7423 7424 7425 7426
        	if (imp.getProperty("cartesian") !=null) {
        		subCam.cartesian= Boolean.parseBoolean((String) imp.getProperty("cartesian"));
        		subCam.updateCartesian(); // recalculate other parameters (they may or may nort be provided
        	} else {
        		subCam.cartesian = false;
        	}
Andrey Filippov's avatar
Andrey Filippov committed
7427 7428

        	// Update intrinsic image parameters
Andrey Filippov's avatar
Andrey Filippov committed
7429 7430
        	this.lensDistortionParameters.pixelSize=subCam.pixelSize;
        	this.lensDistortionParameters.distortionRadius=subCam.distortionRadius;
7431 7432 7433 7434 7435 7436 7437 7438 7439 7440 7441 7442 7443 7444 7445
        	if (imp.getProperty("defects")!=null) {
        		String sDefects=(String) imp.getProperty("defects");
        		String [] asDefects=sDefects.trim().split(" ");
        		subCam.defectsXY=new int [asDefects.length][2];
        		subCam.defectsDiff=new double [asDefects.length];
        		for (int i=0;i<asDefects.length;i++) {
        			String [] stDefect=asDefects[i].split(":");
        			subCam.defectsXY[i][0]=Integer.parseInt(stDefect[0]);
        			subCam.defectsXY[i][1]=Integer.parseInt(stDefect[1]);
        			subCam.defectsDiff[i]=Double.parseDouble(stDefect[2]);
        		}
        	} else {
        		subCam.defectsXY=null;
        		subCam.defectsDiff=null;
        	}
7446
 // non-radial
7447
        	if (imp.getProperty("lensDistortionModel")  !=null) subCam.lensDistortionModel= Integer.parseInt((String) imp.getProperty("lensDistortionModel"));
7448 7449 7450 7451 7452 7453 7454 7455 7456
        	subCam.setDefaultNonRadial();
			for (int i=0;i<subCam.r_xy.length;i++) {
				if (imp.getProperty("r_xy_"+i+"_x")  !=null) subCam.r_xy[i][0]= Double.parseDouble((String) imp.getProperty("r_xy_"+i+"_x"));
				if (imp.getProperty("r_xy_"+i+"_y")  !=null) subCam.r_xy[i][1]= Double.parseDouble((String) imp.getProperty("r_xy_"+i+"_y"));
			}
			for (int i=0;i<subCam.r_od.length;i++) {
				if (imp.getProperty("r_od_"+i+"_o")  !=null) subCam.r_od[i][0]= Double.parseDouble((String) imp.getProperty("r_od_"+i+"_o"));
				if (imp.getProperty("r_od_"+i+"_d")  !=null) subCam.r_od[i][1]= Double.parseDouble((String) imp.getProperty("r_od_"+i+"_d"));
			}
7457 7458 7459
			if (imp.getProperty("subcamera")   !=null) subCam.subcamera=   Integer.parseInt((String) imp.getProperty("subcamera"));
			if (imp.getProperty("sensor_port") !=null) subCam.sensor_port= Integer.parseInt((String) imp.getProperty("sensor_port"));
			if (imp.getProperty("subchannel")  !=null) subCam.subchannel=   Integer.parseInt((String) imp.getProperty("subchannel"));
Andrey Filippov's avatar
Andrey Filippov committed
7460
        }
7461 7462 7463 7464 7465


        for (int imgNum=0;imgNum < distortionCalibrationData.getNumImages();imgNum++){
        	int imageSubCam=  distortionCalibrationData.getImageSubcamera(imgNum);
        	int stationNumber=distortionCalibrationData.getImageStation(imgNum);
Andrey Filippov's avatar
Andrey Filippov committed
7466 7467
        	if (imageSubCam==numSensor){
        		// vector from the data we just set
7468 7469 7470
        		double [] parVector=           distortionCalibrationData.eyesisCameraParameters.getParametersVector(stationNumber,imageSubCam);
        		if       (overwriteExtrinsic)  distortionCalibrationData.setSubcameraParameters(parVector,imgNum);
        		else  if (overwriteDistortion) distortionCalibrationData.setIntrinsicParameters(parVector,imgNum);
Andrey Filippov's avatar
Andrey Filippov committed
7471 7472
        	}
        }
Andrey Filippov's avatar
Andrey Filippov committed
7473

Andrey Filippov's avatar
Andrey Filippov committed
7474 7475 7476 7477 7478 7479 7480 7481 7482 7483 7484 7485 7486 7487 7488 7489 7490 7491 7492 7493 7494 7495 7496 7497 7498 7499 7500 7501 7502 7503 7504 7505 7506 7507 7508
        // now read the calibration data and mask
    	if (this.pixelCorrection==null) {
    		this.pixelCorrection=new double [numSubCameras][][];
    		this.pathNames=new String [numSubCameras];
    		for (int i=0;i<this.pixelCorrection.length;i++){
    			this.pixelCorrection[i]=null;
    			this.pathNames[i]=null;
    		}
    	}
        if (numSensor>=this.pixelCorrection.length){ // increase number of elements
        	double [][][] tmp=this.pixelCorrection.clone();
        	String [] tmpPaths=this.pathNames.clone();
        	this.pixelCorrection=new double[numSensor+1][][];
        	this.pathNames=new String[numSensor+1];
        	for (int i=0;i<this.pixelCorrection.length;i++)
        		if (i<tmp.length){
        			this.pixelCorrection[i]=tmp[i];
        			this.pathNames[i]=tmpPaths[i];
        		}else {
        			this.pixelCorrection[i]=null;
        			this.pathNames[i]=null;
        		}
        }
        int numLayers=6; //corr-x, corr-y,mask, ff-R, ff-G, ff-b
        if (numLayers<pixels.length) numLayers=pixels.length; // for the future?
//        this.pixelCorrection[numSensor]=new double [pixels.length] [pixels[0].length];
        this.pixelCorrection[numSensor]=new double [numLayers][pixels[0].length];
        for (int i= 0;i<this.pixelCorrection[numSensor][0].length;i++){
        	for (int n=0;n<pixels.length;n++)	this.pixelCorrection[numSensor][n][i]=pixels[n][i]; // mask will go to two places
        }
        if (pixels.length<numLayers){
            for (int i= 0;i<this.pixelCorrection[numSensor][0].length;i++){
            	for (int n=pixels.length;n<numLayers;n++)	this.pixelCorrection[numSensor][n][i]=1.0; // default ff if no data is available
            }
        }
Andrey Filippov's avatar
Andrey Filippov committed
7509
        // now mask
Andrey Filippov's avatar
Andrey Filippov committed
7510 7511 7512 7513 7514 7515 7516
        boolean defined=false;
		for (int i=0;i<pixels[2].length;i++) if ((pixels[2][i]!=0.0) && (pixels[2][i]!=1.0)){
			defined=true;
			break;
		}
//    	System.out.println("setDistortionFromImageStack(): defined="+defined );
		if (defined) {
7517 7518 7519 7520 7521
	        if (distortionCalibrationData.sensorMasks==null) {
	        	distortionCalibrationData.sensorMasks=new double [numSubCameras][];
	        	for (int i=0;i<distortionCalibrationData.sensorMasks.length;i++)
	        		distortionCalibrationData.sensorMasks[i]=null;
//	        	System.out.println("setDistortionFromImageStack(): created distortionCalibrationData.sensorMasks["+numSubCameras+"] of null-s" );
Andrey Filippov's avatar
Andrey Filippov committed
7522
	        }
7523 7524 7525 7526 7527 7528
	        if (numSensor>=distortionCalibrationData.sensorMasks.length){ // increase number of elements
	        	double [][] tmp=distortionCalibrationData.sensorMasks;
	        	distortionCalibrationData.sensorMasks=new double[numSensor+1][];
	        	for (int i=0;i<distortionCalibrationData.sensorMasks.length;i++)
	        		if (i<tmp.length)distortionCalibrationData.sensorMasks[i]=tmp[i];
	        		else distortionCalibrationData.sensorMasks[i]=null;
Andrey Filippov's avatar
Andrey Filippov committed
7529
	        }
7530 7531 7532
	        if (distortionCalibrationData.sensorMasks[numSensor]==null){
	        	distortionCalibrationData.sensorMasks[numSensor]=new double[pixels[corrMask].length];
//	        	System.out.println("setDistortionFromImageStack(): created distortionCalibrationData.sensorMasks["+numSensor+"] of ["+pixels[corrMask].length+"]" );
Andrey Filippov's avatar
Andrey Filippov committed
7533
	        }
7534 7535
	        for (int i= 0;i<distortionCalibrationData.sensorMasks[numSensor].length;i++) // null pointer
	        	distortionCalibrationData.sensorMasks[numSensor][i]=pixels[corrMask][i];
Andrey Filippov's avatar
Andrey Filippov committed
7536 7537 7538 7539
		}
    }
    /**
     * Accumulate per-sensor grid R,G,B intensities using current sensor flat-field values
Andrey Filippov's avatar
Andrey Filippov committed
7540
     * @param serNumber - fitting series number to select images (-1 - all enabled)
Andrey Filippov's avatar
Andrey Filippov committed
7541 7542 7543 7544 7545 7546
     * @param sensorMasks "pessimistic" masks to use only center (low-vignetting) part of each sensor (at least on the first runs?)
     * @param minContrast - minimal contrast to consider a node
     * @param threshold - not yet used - disregard grid nodes with low data - in the end
     * @param interpolate - interpolate sensor data
     * @param maskThresholdOcclusion suspect occlusion only if grid is missing in the area where sensor mask is above this threshold
     * @param expandOcclusion - shrink defined grid on image by this steps - to handle occlusion by rollers
Andrey Filippov's avatar
Andrey Filippov committed
7547
     * @param fadeOcclusion - fade shrank occlusion border
Andrey Filippov's avatar
Andrey Filippov committed
7548 7549 7550
     * @param ignoreSensorFlatField - ignorfe previously calculated sensors flat-field calibration
     * @return
     */
Andrey Filippov's avatar
Andrey Filippov committed
7551

Andrey Filippov's avatar
Andrey Filippov committed
7552 7553 7554
    public double [][][][] calculateGridFlatField(
    		int serNumber,
    		double [][] sensorMasks,
7555 7556
    		RefineParameters refineParameters){
   // TODO: add standard weight function used elsewhere.
Andrey Filippov's avatar
Andrey Filippov committed
7557 7558 7559 7560 7561 7562 7563 7564 7565 7566 7567 7568 7569 7570 7571 7572
    	int indexContrast=2;
    	boolean [] selectedImages=fittingStrategy.selectedImages(serNumber); // negative series number OK - will select all enabled
    	int gridHeight=this.patternParameters.gridGeometry.length;
    	int gridWidth=this.patternParameters.gridGeometry[0].length;

    	int maxChannel=0;
    	int numStations=this.patternParameters.getNumStations();
       	for (int numImg=0;numImg<fittingStrategy.distortionCalibrationData.gIP.length;numImg++) if (selectedImages[numImg]){
    		if (fittingStrategy.distortionCalibrationData.gIP[numImg].channel>maxChannel) maxChannel=fittingStrategy.distortionCalibrationData.gIP[numImg].channel;
    	}

    	double [][][][] sensorGrids=new double [numStations][maxChannel+1][][]; //{alpha, red,green, blue}
    	for (int ns=0;ns<sensorGrids.length;ns++) for (int n=0;n<sensorGrids[ns].length;n++) sensorGrids[ns][n]=null;
    	// For each sensor separately accumulate grid intensity using current sensor flat field calibration
    	for (int numImg=0;numImg<fittingStrategy.distortionCalibrationData.gIP.length;numImg++) if (selectedImages[numImg]) {
    		int channel=fittingStrategy.distortionCalibrationData.gIP[numImg].channel;
7573 7574
//    		boolean small_sensor = fittingStrategy.distortionCalibrationData.isSmallSensor(channel);
			boolean small_sensor = fittingStrategy.distortionCalibrationData.getSmallSensors()[channel];
7575 7576 7577 7578 7579 7580 7581 7582 7583
    		RefineParameters rp = small_sensor ? refineParameters.refineParametersSmall : refineParameters;
    		double minContrast = rp.flatFieldMinimalContrast;
//    		double threshold = rp.flatFieldMinimalContrast;
    		boolean interpolate = rp.flatFieldUseInterpolate;
    		double maskThresholdOcclusion = rp.flatFieldMaskThresholdOcclusion;
    		int expandOcclusion = rp.flatFieldShrinkOcclusion;
    		double fadeOcclusion = rp.flatFieldFadeOcclusion;
    		boolean ignoreSensorFlatField = rp.flatFieldIgnoreSensorFlatField;

Andrey Filippov's avatar
Andrey Filippov committed
7584 7585 7586 7587 7588 7589 7590 7591 7592 7593 7594 7595 7596 7597 7598 7599 7600 7601 7602 7603 7604 7605 7606 7607 7608 7609 7610
    		int station=fittingStrategy.distortionCalibrationData.gIP[numImg].getStationNumber();
    		if (sensorMasks[channel]==null) continue;
    		if (sensorGrids[station][channel]==null){ // null pointer
    			sensorGrids[station][channel]=new double [4][gridHeight*gridWidth]; //{alpha, red,green, blue}
    			for (int c=0;c<sensorGrids[station][channel].length;c++){
    				for (int i=0;i<sensorGrids[station][channel][0].length;i++) sensorGrids[station][channel][c][i]=0.0;
    			}
    		}
    		double [][] pixelsXY=fittingStrategy.distortionCalibrationData.gIP[numImg].pixelsXY;
    		if ((pixelsXY.length<1) || (pixelsXY[0].length<6)){
    			if (this.debugLevel>0) System.out.println("No flat-field data in image #"+numImg+
    					" - "+fittingStrategy.distortionCalibrationData.gIP[numImg].path+
    					" pixelsXY.length="+pixelsXY.length+
    					" pixelsXY[0].length="+((pixelsXY.length==0)?"nan": pixelsXY[0].length));
    			continue;
    		}
    		int [][]    pixelsUV=fittingStrategy.distortionCalibrationData.gIP[numImg].pixelsUV;
    		double [] defaultVector={0.0, 0.0, 0.0, 1.0, 1.0, 1.0};
    		// detect if there is any occlusion (i.e. by goniometer rollers)
    		boolean [] bMask=new boolean [gridHeight*gridWidth];
    		double [] mask=new double[bMask.length];
    		for (int i=0;i<bMask.length;i++){
    			bMask[i]=false;
    			mask[i]=0.0;
    		}
    		for (int i=0;i<pixelsXY.length;i++){
    			double [] xyzmrgb=patternParameters.getXYZM(
Andrey Filippov's avatar
Andrey Filippov committed
7611
    					pixelsUV[i][0],
Andrey Filippov's avatar
Andrey Filippov committed
7612 7613 7614 7615 7616 7617 7618
    					pixelsUV[i][1],
    					false,
    					station);
    			if (xyzmrgb!=null){
    	   			int index=patternParameters.getGridIndex(pixelsUV[i][0], pixelsUV[i][1]);
    	   			bMask[index]=(pixelsXY[i][indexContrast]>=minContrast);
    	   			mask[index]=interpolateMask (
7619
    	   					channel,
Andrey Filippov's avatar
Andrey Filippov committed
7620
        					sensorMasks[channel],
Andrey Filippov's avatar
Andrey Filippov committed
7621
        					pixelsXY[i][0],
Andrey Filippov's avatar
Andrey Filippov committed
7622 7623 7624 7625 7626 7627 7628 7629 7630 7631 7632 7633 7634 7635 7636 7637 7638 7639 7640 7641 7642 7643 7644 7645 7646 7647 7648 7649
        					pixelsXY[i][1]);
    			}
    		}
    		boolean [] occlusionMask=new boolean[bMask.length];
    		for (int i=0;i<occlusionMask.length;i++){
    			occlusionMask[i]=false;
    		}
    		boolean occlusion=false;
    		for (int i=1;i<(gridHeight-1);i++){
    			for (int j=1;j<(gridWidth-1);j++){
    				int index=i*gridWidth+j;
    				if (bMask[index]){
    					if ((   !bMask[(i-1)*gridWidth+j] ||
    							!bMask[(i+1)*gridWidth+j] ||
    							!bMask[i*    gridWidth+j-1] ||
    							!bMask[i*    gridWidth+j+1]) &&
    							(mask[index]>=maskThresholdOcclusion)
    					){
    						occlusionMask[index]=true;
    						occlusion=true;
    					}
    				}
    			}
    		}
    		if (occlusion){
    			for (int n=0;n<expandOcclusion;n++){ // expand
    				boolean [] bMaskPrevious=occlusionMask.clone();
    				for (int i=1;i<(gridHeight-1);i++){
Andrey Filippov's avatar
Andrey Filippov committed
7650
    					for (int j=1;j<(gridWidth-1);j++){
Andrey Filippov's avatar
Andrey Filippov committed
7651 7652 7653 7654 7655 7656 7657 7658 7659 7660 7661 7662 7663 7664 7665 7666 7667 7668 7669 7670 7671 7672 7673 7674 7675 7676 7677 7678 7679 7680
    						if (!occlusionMask[i*gridHeight+j]){
    							if (
    									bMaskPrevious[(i-1)*gridWidth+j] ||
    									bMaskPrevious[(i+1)*gridWidth+j] ||
    									bMaskPrevious[i*    gridWidth+j-1] ||
    									bMaskPrevious[i*    gridWidth+j+1]){
    								occlusionMask[i*gridWidth+j]=true;
    							}
    						}
    					}
    				}
    			}
        		double [] maskNonOccluded=new double [occlusionMask.length];
        		for (int i=0;i<maskNonOccluded.length;i++) maskNonOccluded[i]=occlusionMask[i]?0.0:1.0;
        		if (fadeOcclusion>0.0){
        			(new DoubleGaussianBlur() ).blurDouble(
        					maskNonOccluded,
        					gridWidth,
        					gridHeight,
        					fadeOcclusion,
        					fadeOcclusion,
        					0.01);
        		}
        		if (fadeOcclusion>=0.0 )for (int i=0;i<mask.length;i++){
    				double d=2.0*(maskNonOccluded[i]-0.5);
    				mask[i]*=(!occlusionMask[i] && (d>0))?(d*d):0.0;
    			}
    		}
    		for (int i=0;i<pixelsXY.length;i++){
    			double [] xyzmrgb=patternParameters.getXYZM(
Andrey Filippov's avatar
Andrey Filippov committed
7681
    					pixelsUV[i][0],
Andrey Filippov's avatar
Andrey Filippov committed
7682 7683 7684 7685 7686 7687 7688 7689
    					pixelsUV[i][1],
    					false,
    					station);
    			if (xyzmrgb==null) continue; // out of grid
    			double [] vector=ignoreSensorFlatField?defaultVector:
    				((interpolate)?
    					interpolateCorrectionVector (
    							channel,
Andrey Filippov's avatar
Andrey Filippov committed
7690
    							pixelsXY[i][0],
Andrey Filippov's avatar
Andrey Filippov committed
7691 7692 7693
    							pixelsXY[i][1]):
 						getCorrectionVector (
 								channel,
Andrey Filippov's avatar
Andrey Filippov committed
7694
 								pixelsXY[i][0],
Andrey Filippov's avatar
Andrey Filippov committed
7695 7696 7697
 								pixelsXY[i][1]))	;
    			int index=patternParameters.getGridIndex(pixelsUV[i][0], pixelsUV[i][1]);
    			double weight=mask[index];
Andrey Filippov's avatar
Andrey Filippov committed
7698

Andrey Filippov's avatar
Andrey Filippov committed
7699 7700 7701 7702 7703 7704 7705 7706
    			sensorGrids[station][channel][0][index]+=weight;
    			for (int c=0;c<3;c++)if (vector[c+3]>0.0){
    				sensorGrids[station][channel][c+1][index]+=weight*pixelsXY[i][c+3]/vector[c+3];
    			}
    		}
    	}
    	for (int station=0;station<sensorGrids.length;station++){
    		for (int channel=0;channel<sensorGrids[station].length; channel++) if (sensorGrids[station][channel]!=null){
7707 7708
//        		boolean small_sensor = fittingStrategy.distortionCalibrationData.isSmallSensor(channel);
				boolean small_sensor = fittingStrategy.distortionCalibrationData.getSmallSensors()[channel];
7709 7710
        		RefineParameters rp = small_sensor ? refineParameters.refineParametersSmall : refineParameters;
        		double threshold = rp.flatFieldMinimalContrast;
Andrey Filippov's avatar
Andrey Filippov committed
7711 7712 7713 7714 7715 7716 7717 7718 7719 7720 7721 7722 7723 7724 7725
    			if (this.pixelCorrection[channel]==null) {
    				sensorGrids[station][channel]=null;
    			} else {
    				for (int i=0;i<sensorGrids[station][channel][0].length;i++){
    					if (sensorGrids[station][channel][0][i]<threshold) {
    						for (int j=0;j<sensorGrids[station][channel].length;j++) sensorGrids[station][channel][j][i]=0.0;
    					} else {
    						for (int j=1;j<sensorGrids[station][channel].length;j++) sensorGrids[station][channel][j][i]/=sensorGrids[station][channel][0][i];
    					}
    				}
    			}
    		}
    	}
    	return sensorGrids;
    }
Andrey Filippov's avatar
Andrey Filippov committed
7726

Andrey Filippov's avatar
Andrey Filippov committed
7727 7728 7729 7730
    public double [] getCorrectionVector(
			int chnNum,
			double px,
			double py){
7731 7732 7733
		int sensorCorrWidth= getSensorCorrWidth(chnNum);
		int indexXY=((int) Math.floor(px/getDecimateMasks(chnNum))) +
		((int) Math.floor(py/getDecimateMasks(chnNum)))*sensorCorrWidth;
Andrey Filippov's avatar
Andrey Filippov committed
7734 7735 7736 7737
		double []vector=new double[this.pixelCorrection[chnNum].length];
		for (int i=0;i<vector.length;i++) vector[i]=this.pixelCorrection[chnNum][i][indexXY];
        return vector;
    }
Andrey Filippov's avatar
Andrey Filippov committed
7738

Andrey Filippov's avatar
Andrey Filippov committed
7739 7740 7741 7742 7743 7744 7745 7746 7747 7748 7749
    /**
     * Calculate color flat-field data for the pattern grid, calculate pattern grid mask (alpha)
     * @param referenceStation - station number for unity target brightness
     * @param flatFields partial, per-station, per-sensor pattern flat-field data
     * @param shrinkForMatching shrink pattern mask for calculating pattern average (removing unreliable borders)
     * @param resetMask reset pattern mask to default before (re)-calculating mask
     * @param maxDiffNeighb maximal relative difference between neghbor nodes (ignoring off-grid)
     * @param shrinkMask shrink result mask
     * @param fadeMask smooth fade the alpha on the pattern edge, keep zeros zeros
     * @return {alpha, r,g,b,number of images used} for each view group separately
     */
Andrey Filippov's avatar
Andrey Filippov committed
7750

Andrey Filippov's avatar
Andrey Filippov committed
7751
    public double [][][][] combineGridFlatField(
7752
//    		RefineParameters refineParameters,
Andrey Filippov's avatar
Andrey Filippov committed
7753 7754 7755 7756
    		int referenceStation,
    		double [][][][] flatFields,
    		double shrinkForMatching,
    		boolean resetMask,
7757
    		double maxDiffNeighb,  // maximal allowed relative difference between neighbor nodes (relative), 0 - do not  filter any
Andrey Filippov's avatar
Andrey Filippov committed
7758 7759
    		int shrinkMask, // shrink result mask
    		double fadeMask
Andrey Filippov's avatar
Andrey Filippov committed
7760
    		){
7761 7762 7763 7764 7765 7766 7767 7768
    	// So far all parameters common for large/small sensors!
//    	boolean resetMask = refineParameters.flatFieldResetMask;                // common for all sensors!
//    	int referenceStation = refineParameters.flatFieldReferenceStation;      // common for all sensors!
//    	double shrinkForMatching = refineParameters.flatFieldShrinkForMatching; // common for all sensors!
//    	double maxDiffNeighb  = refineParameters.flatFieldMaxRelDiff;           // common for all sensors!
//		int shrinkMask  = refineParameters.flatFieldShrinkMask;                 // common for all sensors!
//		double fadeMask  = refineParameters.flatFieldFadeBorder;                // common for all sensors!

Andrey Filippov's avatar
Andrey Filippov committed
7769 7770 7771 7772 7773 7774 7775 7776 7777 7778 7779 7780 7781 7782 7783 7784 7785 7786 7787 7788 7789 7790 7791 7792 7793 7794 7795 7796
    	int maskIndex=3;
    	if (resetMask) patternParameters.calculateGridGeometryAndPhotometric(false);
    	double [][][] gridGeometry= patternParameters.getGeometry();
    	int [] viewMap=	patternParameters.getViewMap();

    	int gridHeight=gridGeometry.length;
    	int gridWidth=gridGeometry[0].length;
    	int numStations=patternParameters.getNumStations();
    	int numViews=patternParameters.getNumViews();
    	double [][][][] viewPatterns=new double [numStations][numViews][][];
		double [][][] gridMask= new double[numStations][numViews][gridWidth*gridHeight];
		double [][] scaleIndividual=new double[flatFields[referenceStation].length][3]; // scale individual sensor patters before averaging
    	for (int station=0;station<numStations;station++){
    		for (int numView=0;numView<numViews;numView++){
    			viewPatterns[station][numView]=null;
//    			double [] gridMask= new double[gridWidth*gridHeight];
    			for (int v=0;v<gridHeight;v++) for (int u=0;u<gridWidth;u++) gridMask[station][numView][u+v*gridWidth]=(gridGeometry[v][u]!=null)?gridGeometry[v][u][maskIndex]:0.0;
    			if (shrinkForMatching>0){
    				(new DoubleGaussianBlur() ).blurDouble(gridMask[station][numView], gridWidth, gridHeight, shrinkForMatching, shrinkForMatching, 0.01);
    				for (int i=0;i<gridMask[station][numView].length;i++){
    					double d=2.0*(gridMask[station][numView][i]-0.5);
    					gridMask[station][numView][i]=(d>0)?(d*d):(0.0);
    				}
    			}
    			for (int v=0;v<gridHeight;v++) for (int u=0;u<gridWidth;u++){
    				if ((gridGeometry[v][u]==null) || (gridGeometry[v][u][maskIndex]<=0.0)) gridMask[station][numView][u+v*gridWidth]=0.0;
    			}
    			if (this.debugLevel>2){
7797
    				ShowDoubleFloatArrays.showArrays(gridMask[station][numView], gridWidth, gridHeight,   "MATCH_MASK"+numView);
Andrey Filippov's avatar
Andrey Filippov committed
7798 7799 7800 7801 7802 7803 7804 7805 7806 7807 7808 7809 7810 7811 7812 7813 7814 7815 7816 7817 7818 7819 7820 7821 7822 7823 7824 7825 7826 7827 7828 7829 7830 7831 7832 7833 7834 7835 7836 7837 7838 7839 7840 7841 7842 7843 7844
    			}
//    			double [][] scaleIndividual=new double[flatFields[station].length][3]; // scale individual sensor patters before averaging
    			//    		for (int numSensor=0;numSensor<flatFields.length; numSensor++ ) if (flatFields[numSensor]!=null){
    			// process only sensors from the same view of the target (i.e. 0 - eyesis head, 1 - eyesis bottom)
    			if (station==referenceStation) {
    				int numUsedSensors=0;
    				for (int numSensor=0;numSensor<flatFields[station].length; numSensor++ ) if ((flatFields[station][numSensor]!=null) && (viewMap[numSensor]==numView)){
    					numUsedSensors++;
    					double [] weightedSums={0.0,0.0,0.0};
    					double sumWeights=0;
    					for (int i=0;i<flatFields[station][numSensor][0].length;i++){
    						if ((gridMask[station][numView][i]>0.0) && (flatFields[station][numSensor][0][i]>1.0)){ // more than one overlapping image
    							double weight=flatFields[station][numSensor][0][i]*gridMask[station][numView][i];
    							sumWeights+=weight;
    							for (int c=0;c<weightedSums.length;c++) weightedSums[c]+=weight*flatFields[station][numSensor][c+1][i];

    						}
    					}
    					for (int c=0;c<weightedSums.length;c++){
    						scaleIndividual[numSensor][c]=patternParameters.averageRGB[c]*sumWeights/weightedSums[c];
    						if (this.debugLevel>2){
    							System.out.println("combineGridFlatField(): scaleIndividual["+numSensor+"]["+c+"]="+scaleIndividual[numSensor][c]);
    						}
    					}

    				}
    				if (numUsedSensors==0){
    					System.out.println("No data for target view #"+numView+" reference station ="+referenceStation);
    					continue;
    				}
    			}

    		}
    	}
    	for (int station=0;station<numStations;station++){
    		for (int numView=0;numView<numViews;numView++){
    			//    		double [][] combinedPattern=new double [5][gridWidth*gridHeight];
    			viewPatterns[station][numView]=new double [5][gridWidth*gridHeight];
    			double [][] combinedPattern=viewPatterns[station][numView];
    			for (int i=0;i<combinedPattern[0].length;i++){
    				double sumWeights=0;
    				double [] weightedSums={0.0,0.0,0.0};
    				for (int numSensor=0;numSensor<flatFields[station].length; numSensor++ ) if ((flatFields[station][numSensor]!=null) && (viewMap[numSensor]==numView)){
    					double weight=flatFields[station][numSensor][0][i];
    					sumWeights+=weight;
    					for (int c=0;c<weightedSums.length;c++) weightedSums[c]+=weight*flatFields[station][numSensor][c+1][i]*scaleIndividual[numSensor][c];
    				}
Andrey Filippov's avatar
Andrey Filippov committed
7845
    				combinedPattern[4][i]=sumWeights; // just for debugging - no, actually used? - number of images used for this grid node
Andrey Filippov's avatar
Andrey Filippov committed
7846 7847 7848 7849 7850 7851 7852 7853 7854 7855 7856 7857
    				for (int c=0;c<weightedSums.length;c++){
    					combinedPattern[c+1][i]=(sumWeights>0.0)?(weightedSums[c]/sumWeights):0.0;
    				}

    			}
    			/*
    		}
    	}
    	for (int station=0;station<viewPatterns.length;station++){
    		for (int numView=0;numView<viewPatterns[station].length;numView++){

    			double [][] combinedPattern=viewPatterns[station][numView];
Andrey Filippov's avatar
Andrey Filippov committed
7858
    	*/
Andrey Filippov's avatar
Andrey Filippov committed
7859 7860 7861 7862 7863 7864 7865 7866 7867 7868 7869 7870 7871 7872 7873 7874 7875 7876 7877 7878 7879 7880 7881 7882 7883 7884 7885 7886 7887 7888
    			//    	double [] gridMask[station][numView]= new double[gridWidth*gridHeight];
    			// calculate final mask
    			for (int v=0;v<gridHeight;v++) for (int u=0;u<gridWidth;u++) gridMask[station][numView][u+v*gridWidth]=(gridGeometry[v][u]!=null)?gridGeometry[v][u][maskIndex]:0.0;
    			if (maxDiffNeighb>0.0) { // throw away bad (having sharp gradients) nodes
    				int expWidth=gridWidth+2;
    				int expHeight=gridHeight+2;
    				double [] expandedGrid=new double [expWidth*expHeight];
    				boolean [] enabled=new boolean[expandedGrid.length];
    				for (int v=0;v<expHeight;v++) for (int u=0;u<expWidth;u++){
    					int index=u+expWidth*v;
    					if ((u==0) || (v==0) || (u==(expWidth-1)) || (v==(expHeight-1))){
    						expandedGrid[index]=0.0;
    						enabled[index]=false;
    					} else {
    						int indexSrc=(u-1)+gridWidth*(v-1);
    						expandedGrid[index]=(combinedPattern[1][indexSrc]+combinedPattern[2][indexSrc]+combinedPattern[3][indexSrc])/3.0; // average value;
    						enabled[index]=gridMask[station][numView][indexSrc]>0.0;
    					}
    				}
    				boolean [] badNodes=enabled.clone();
    				int [] dirs={
    						-expWidth-1,-expWidth,-expWidth+1,  1,
    						expWidth+1, expWidth, expWidth-1, -1};
    				int numBadOnTheBorder=1; // just to make while(true) happy
    				int minNeighb=3; // remove nodes with less than 3 neighbors
    				while (numBadOnTheBorder>0){
    					// build/update badNodes array
    					numBadOnTheBorder=0;
    					int numBad=0;
    					double [] diffs = new double [8];
Andrey Filippov's avatar
Andrey Filippov committed
7889
    					int [] indices=new int [8];
Andrey Filippov's avatar
Andrey Filippov committed
7890 7891 7892 7893 7894 7895 7896 7897 7898 7899 7900 7901 7902 7903 7904 7905 7906 7907 7908 7909 7910 7911 7912 7913 7914 7915 7916 7917 7918 7919 7920 7921 7922 7923 7924 7925 7926 7927 7928 7929 7930 7931 7932 7933 7934 7935 7936 7937 7938 7939 7940 7941 7942 7943 7944 7945 7946 7947 7948 7949 7950 7951 7952 7953 7954 7955 7956 7957 7958 7959 7960 7961 7962 7963 7964 7965 7966 7967 7968 7969 7970 7971 7972 7973 7974 7975 7976
    					for (int i=0;i<8;i++) {
    						diffs[i]=  -1.0; // diff==0 on isolated pair?
    						indices[i]=-1;
    					}
    					for (int index=0;index<badNodes.length;index++) if (badNodes[index]){
    						int numNeighb=0;
    						double maxDiff=0.0;
    						for (int dir=0;dir<dirs.length;dir++) {
    							int index1=index+dirs[dir];
    							if (enabled[index1]) {
    								numNeighb++;
    								double d=2.0*Math.abs((expandedGrid[index1]-expandedGrid[index])/(expandedGrid[index]+expandedGrid[index1]));
    								if (maxDiff<d) maxDiff=d;
    							}
    						}
    						if ((maxDiff<((maxDiffNeighb*numNeighb)/minNeighb)) && (numNeighb>=minNeighb)){ //more neighbors - more likely to keep
    							badNodes[index]=false; // rehabilitate node
    						} else {
    							numBad++;
    							if (numNeighb<8) { // do nothing if bad node is inside - it may be removed in the next passes
    								numBadOnTheBorder++;
    								if (maxDiff>diffs[numNeighb]){
    									diffs[numNeighb]=maxDiff;
    									indices[numNeighb]=index;
    								}
    							}
    						}
    					}
    					if (this.debugLevel>1) System.out.println("combineGridFlatField(): "+numBad+" bad nodes, "+numBadOnTheBorder+" of them on the border");
    					if (numBadOnTheBorder==0) break; // nothing to remove - break from the while(true) loop
    					// find bad node with least enabled neighbors - there will be one at least
    					for (int n=0;n<8;n++){
    						if (indices[n]>=0){
    							enabled[indices[n]]=false;   // disable this node
    							badNodes[indices[n]]=false;  // and remove from bad nodes (it is dead now)
    							// Any orphans around (were not bad, but now have to few neighbors)
    							for (int dir=0;dir<dirs.length;dir++) {
    								int index1=indices[n]+dirs[dir];
    								if (enabled[index1]) {
    									badNodes[index1]=true;
    								}
    							}
    							break;
    						}
    					}
    				}
    				// shrink enabled cells by shrinkMask
    				for (int n=0;n<shrinkMask;n++){
    					for (int i=0;i<badNodes.length;i++) badNodes[i]=false;
    					for (int v=1;v<(expHeight-1);v++) for (int u=1;u<(expWidth-1);u++){
    						int index=u+expWidth*v;
    						badNodes[index]=!enabled[index+1] || !enabled[index-1] || !enabled[index+expWidth] || !enabled[index-expWidth];
    					}
    					for (int i=0;i<badNodes.length;i++) if (badNodes[i]) enabled[i]=false;
    				}
    				// copy back to the gridMask[station][numView]
    				for (int v=1;v<(expHeight-1);v++) for (int u=1;u<(expWidth-1);u++){
    					int index=u+expWidth*v;
    					int indexSrc=(u-1)+gridWidth*(v-1);
    					if (!enabled[index]) gridMask[station][numView][indexSrc]=0.0;
    				}
    				for (int i=0;i<gridMask[station][numView].length;i++) if (gridMask[station][numView][i]==0.0){
    					combinedPattern[1][i]=0.0;
    					combinedPattern[2][i]=0.0;
    					combinedPattern[3][i]=0.0;
    				}

    			}
    			// fade mask on the borders, keep zeros - zeros
    			if (fadeMask>0.0){
    				double [] gridMask1=gridMask[station][numView].clone();
    				(new DoubleGaussianBlur() ).blurDouble(gridMask[station][numView], gridWidth, gridHeight, fadeMask, fadeMask, 0.01);
    				for (int i=0;i<gridMask[station][numView].length;i++){
    					double d=2.0*(gridMask[station][numView][i]-0.5);
    					gridMask[station][numView][i]=(gridMask1[i]>0)?((d>0)?(d*d):(0.0)):0.0;
    					if (combinedPattern[4][i]==0.0) gridMask[station][numView][i]=0.0; // how can it be zero combinedPattern[4][i] with non-zero gridMask[i]?
    				}
    			}
        		combinedPattern[0]=gridMask[station][numView];
    		}
    	}
    	return viewPatterns;
    }
    /**
     * Applies calculated [][] pattern alpha, r,g,b to the current grid geometry
     * @param patternFlatField
     */
Andrey Filippov's avatar
Andrey Filippov committed
7977
    public void applyGridFlatField(
Andrey Filippov's avatar
Andrey Filippov committed
7978 7979 7980
    		double [][][][] patternFlatField // {alpha, red,green,blue, number of images used}[pixel_index] for each view of the pattern
    ){
    	for (int station=0;station<patternParameters.getNumStations();station++){
Andrey Filippov's avatar
Andrey Filippov committed
7981
    		for (int nView=0;nView<patternParameters.getNumViews();nView++)
Andrey Filippov's avatar
Andrey Filippov committed
7982 7983 7984 7985 7986 7987 7988 7989
    			if ((patternFlatField[station]!=null) && (patternFlatField[station][nView]!=null)) {
    				double [][] photometrics=patternParameters.getPhotometricByView(station,nView);
    				photometrics[0]=patternFlatField[station][nView][1].clone(); // red
    				photometrics[1]=patternFlatField[station][nView][2].clone(); // green
    				photometrics[2]=patternFlatField[station][nView][3].clone(); // blue
    				photometrics[3]=patternFlatField[station][nView][0].clone(); // alpha
    			}
    	}
Andrey Filippov's avatar
Andrey Filippov committed
7990
    	/*
Andrey Filippov's avatar
Andrey Filippov committed
7991 7992 7993 7994 7995 7996 7997 7998 7999 8000 8001 8002 8003 8004 8005 8006 8007 8008 8009 8010 8011 8012 8013 8014 8015 8016 8017 8018 8019 8020
    	double [][][] gridGeometry= patternParameters.getGeometry();
    	int gridHeight=gridGeometry.length;
    	int gridWidth=gridGeometry[0].length;
    	for (int v=0;v<gridHeight;v++) for (int u=0;u<gridWidth;u++) {
    		int index=u+v*gridWidth;
    		gridGeometry[v][u][3]=patternFlatField[0][index];
    		gridGeometry[v][u][4]=patternFlatField[1][index];
    		gridGeometry[v][u][5]=patternFlatField[2][index];
    		gridGeometry[v][u][6]=patternFlatField[3][index];
    	}
    	 */
    }
    /**
     * Remove areas on the target flat-field data with specular reflections of the lamps by matching different views
     * @param highPassSigma - subtract weighted average of the difference with this
     * @param thershold mismatch causing 50% drop of the weight function
     * @param numIterations number of iterations of comparing to the weighted/masked average
     * @param apply apply changes
     * @param debugShowMode 0 - do not show debug images, 1 show only during last iteration, 2 - show always
     */
    public void removeSpecular (
    		boolean positiveDiffOnly,
    		double highPassSigma,
    		double lowPassSigma,
    		double thershold,
    		int numIterations,
    		boolean apply,
    		int debugShowMode){ // 0 - none, 1 - last iteration, 2 - all iterations
    	int debugThreshold=1;
    	int length=0;
Andrey Filippov's avatar
Andrey Filippov committed
8021

Andrey Filippov's avatar
Andrey Filippov committed
8022 8023 8024 8025 8026 8027 8028 8029
    	double [][][] weights=new double [patternParameters.getNumStations()][patternParameters.getNumViews()][];
		double [][][][] photometrics=new double [patternParameters.getNumStations()][patternParameters.getNumViews()][][];
		double [][][][] highPassDiff=new double [patternParameters.getNumStations()][patternParameters.getNumViews()][][];
		double [][][][] lowPassDiff=new double [patternParameters.getNumStations()][patternParameters.getNumViews()][][];

		int width=  patternParameters.gridGeometry[0].length;
		int height= patternParameters.gridGeometry.length;
    	for (int station=0;station<patternParameters.getNumStations();station++){
Andrey Filippov's avatar
Andrey Filippov committed
8030
    		for (int nView=0;nView<patternParameters.getNumViews();nView++) {
Andrey Filippov's avatar
Andrey Filippov committed
8031 8032 8033 8034 8035 8036 8037 8038 8039 8040 8041 8042 8043 8044 8045 8046 8047 8048 8049 8050 8051 8052 8053 8054 8055 8056 8057 8058 8059 8060 8061 8062 8063 8064 8065 8066 8067 8068 8069 8070 8071 8072 8073 8074 8075 8076 8077 8078 8079 8080 8081
    			photometrics[station][nView]=patternParameters.getPhotometricByView(station,nView);
    			if (photometrics[station][nView]!=null){
    				length=photometrics[0][0][3].length; // should all be the same length (or null)
    				weights[station][nView]=new double [length];
    				for (int nPix=0;nPix<length;nPix++) weights[station][nView][nPix]=(photometrics[station][nView][3][nPix]>0.0)?1.0:0.0;
    			} else {
    				weights[station][nView]=null;
    			}
    		}
    	}
    	double threshold23=9.0*thershold*thershold;
    	for (int nIter=0;nIter<numIterations;nIter++){
    		boolean showDebug=(debugShowMode>1) || ((debugShowMode>0) && (nIter== (numIterations-1)));
        	// Calculate weighted average among different stations/views.
    		double [][] average=new double [4][length];
    		for (int nPix=0;nPix<length;nPix++){
    			double w0=0.0;
    	    	for (int station=0;station<patternParameters.getNumStations();station++){
    	    		for (int nView=0;nView<patternParameters.getNumViews();nView++) {
    	    			if (photometrics[station][nView]!=null){
    	    				double w=weights[station][nView][nPix]*photometrics[station][nView][3][nPix];
    	    				average[0][nPix]+=w*photometrics[station][nView][0][nPix];
    	    				average[1][nPix]+=w*photometrics[station][nView][1][nPix];
    	    				average[2][nPix]+=w*photometrics[station][nView][2][nPix];
    	    				w0+=w;
    	    			}
    	    		}
    	    	}
    	    	double k= (w0>0.0)?(1.0/w0):0.0;
    	    	average[0][nPix]*=k;
    	    	average[1][nPix]*=k;
    	    	average[2][nPix]*=k;
    	    	average[3][nPix]=w0/(patternParameters.getNumStations()*patternParameters.getNumViews());
    		}
    		double [][][][] diffFromAverage=new double [photometrics.length][photometrics[0].length][4][length];
        	// Scale each station/view for best fit
	    	for (int station=0;station<patternParameters.getNumStations();station++){
	    		for (int nView=0;nView<patternParameters.getNumViews();nView++) {
	    			double scale=0.0;
	    			if (photometrics[station][nView]!=null){
	    				double [] weightsHighLowPass=new double[length];
	    				double sf2=0.0,sfg=0.0;
	    				for (int nPix=0;nPix<length;nPix++){
    	    				double w=weights[station][nView][nPix]*photometrics[station][nView][3][nPix];
    	    				weightsHighLowPass[nPix]=w;
    	    				sf2+=w*(photometrics[station][nView][0][nPix]*photometrics[station][nView][0][nPix]+
    	    						photometrics[station][nView][1][nPix]*photometrics[station][nView][1][nPix]+
    	    						photometrics[station][nView][2][nPix]*photometrics[station][nView][2][nPix]);
    	    				sfg+=w*(photometrics[station][nView][0][nPix]*average[0][nPix]+
    	    						photometrics[station][nView][1][nPix]*average[1][nPix]+
    	    						photometrics[station][nView][2][nPix]*average[2][nPix]);
Andrey Filippov's avatar
Andrey Filippov committed
8082

Andrey Filippov's avatar
Andrey Filippov committed
8083 8084 8085 8086 8087 8088 8089 8090 8091 8092 8093 8094 8095 8096 8097 8098 8099 8100 8101 8102 8103 8104 8105 8106 8107 8108
	    				}
	    				scale=sfg/sf2;
	    				if ((this.debugLevel>=debugThreshold) && showDebug){
	    					System.out.println("removeSpecular(), pass"+nIter+" scale["+station+"]["+nView+"]="+scale);
	    				}
//	    				Calculate difference from average
	    				for (int nPix=0;nPix<length;nPix++){
	    					if (photometrics[station][nView][3][nPix]>0.0){
	    						for (int c=0;c<3;c++){
	    							double d=scale*photometrics[station][nView][c][nPix]-average[c][nPix];
	    							diffFromAverage[station][nView][c][nPix]=d;
	    						}
	    					}
	    				}
	    				if (highPassSigma>0.0){
	    					double [] weightsHighPass=weightsHighLowPass.clone();
	    					(new DoubleGaussianBlur()).blurDouble(
	    							weightsHighPass,
	    							width,
	    							height,
	    							highPassSigma,
	    							highPassSigma,
	    							0.01);
	    					highPassDiff[station][nView]=new double [3][];
	    					for (int c=0;c<3;c++){
	    	    				highPassDiff[station][nView][c]=diffFromAverage[station][nView][c].clone(); // deep
Andrey Filippov's avatar
Andrey Filippov committed
8109

Andrey Filippov's avatar
Andrey Filippov committed
8110 8111
	    						for (int nPix=0;nPix<length;nPix++){
	    							highPassDiff[station][nView][c][nPix]*=weightsHighLowPass[nPix];
Andrey Filippov's avatar
Andrey Filippov committed
8112
	    						}
Andrey Filippov's avatar
Andrey Filippov committed
8113 8114 8115 8116 8117 8118 8119 8120 8121 8122 8123
		    					(new DoubleGaussianBlur()).blurDouble(
		    							highPassDiff[station][nView][c],
		    							width,
		    							height,
		    							highPassSigma,
		    							highPassSigma,
		    							0.01);
	    						for (int nPix=0;nPix<length;nPix++){
	    							highPassDiff[station][nView][c][nPix]=
	    								diffFromAverage[station][nView][c][nPix]-
	    								((weightsHighPass[nPix]>0)?(highPassDiff[station][nView][c][nPix]/weightsHighPass[nPix]):0.0);
Andrey Filippov's avatar
Andrey Filippov committed
8124
	    						}
Andrey Filippov's avatar
Andrey Filippov committed
8125 8126 8127 8128
	    					}
	    				} else {
    	    				highPassDiff[station][nView]=diffFromAverage[station][nView].clone(); // shallow
	    				}
Andrey Filippov's avatar
Andrey Filippov committed
8129

Andrey Filippov's avatar
Andrey Filippov committed
8130 8131 8132 8133 8134 8135 8136 8137 8138 8139 8140 8141 8142 8143
	    				if (lowPassSigma>0.0){
	    					double [] weightsLowPass=weightsHighLowPass.clone();
	    					(new DoubleGaussianBlur()).blurDouble(
	    							weightsLowPass,
	    							width,
	    							height,
	    							lowPassSigma,
	    							lowPassSigma,
	    							0.01);
	    					lowPassDiff[station][nView]=new double [3][];
	    					for (int c=0;c<3;c++){
	    						lowPassDiff[station][nView][c]=highPassDiff[station][nView][c].clone();
	    						for (int nPix=0;nPix<length;nPix++){
	    							lowPassDiff[station][nView][c][nPix]*=weightsHighLowPass[nPix];
Andrey Filippov's avatar
Andrey Filippov committed
8144
	    						}
Andrey Filippov's avatar
Andrey Filippov committed
8145 8146 8147 8148 8149 8150 8151 8152 8153 8154
		    					(new DoubleGaussianBlur()).blurDouble(
		    							lowPassDiff[station][nView][c],
		    							width,
		    							height,
		    							lowPassSigma,
		    							lowPassSigma,
		    							0.01);
	    						for (int nPix=0;nPix<length;nPix++){
	    							lowPassDiff[station][nView][c][nPix]=
	    								(weightsLowPass[nPix]>0)?(lowPassDiff[station][nView][c][nPix]/weightsLowPass[nPix]):0.0;
Andrey Filippov's avatar
Andrey Filippov committed
8155
	    						}
Andrey Filippov's avatar
Andrey Filippov committed
8156 8157 8158 8159 8160
	    					}
	    				} else {
    	    				lowPassDiff[station][nView]=highPassDiff[station][nView].clone(); // shallow
    					}

Andrey Filippov's avatar
Andrey Filippov committed
8161 8162 8163


// TODO: display, calculate new weight from filtered difference.
Andrey Filippov's avatar
Andrey Filippov committed
8164 8165 8166 8167 8168 8169 8170 8171 8172 8173 8174 8175 8176 8177 8178
// Calculate new weight
	    				for (int nPix=0;nPix<length;nPix++){
	    					if (photometrics[station][nView][3][nPix]>0.0){
	    						double e2=0.0;
	    						for (int c=0;c<3;c++){
	    							double d=lowPassDiff[station][nView][c][nPix];
//	    							double d=scale*photometrics[station][nView][c][nPix]-average[c][nPix];
//	    							diffFromAverage[station][nView][c][nPix]=d;
	    							if (!positiveDiffOnly || (d>0)) e2+=d*d;
	    						}
	    						weights[station][nView][nPix]=1.0/(e2/threshold23+1.0);
	    					} else {
	    						weights[station][nView][nPix]=0.0;
	    					}
	    				}
Andrey Filippov's avatar
Andrey Filippov committed
8179

Andrey Filippov's avatar
Andrey Filippov committed
8180 8181 8182 8183 8184 8185 8186 8187 8188 8189 8190 8191 8192 8193 8194
	    			}
	    		}
	    	}
	    	if ((this.debugLevel>=debugThreshold) && showDebug) {
	    		String [] titles = new String [weights.length*weights[0].length];
	    		double [][] debugData= new double [weights.length*weights[0].length][];
	        	for (int station=0;station<patternParameters.getNumStations();station++){
	        		for (int nView=0;nView<patternParameters.getNumViews();nView++) {
	        			int n=station*weights[0].length+nView;
	        			titles[n]="S"+station+" V"+nView;
	        			if (photometrics[station][nView]!=null){
	        				debugData[n]=weights[station][nView];
	        			}
	        		}
	        	}
8195
	        	ShowDoubleFloatArrays.showArrays(
Andrey Filippov's avatar
Andrey Filippov committed
8196 8197 8198 8199 8200 8201 8202 8203 8204 8205 8206 8207 8208 8209 8210 8211 8212
	        			debugData,
	        			width,
	        			height,
	        			true,
	        			"GridWeights"+nIter,
	        			titles);
	        	double [][] debugDiffGreen= new double [weights.length*weights[0].length][];
	        	double [][] debugHighpassDiffGreen= new double [weights.length*weights[0].length][];
	        	double [][] debugLowpassDiffGreen= new double [weights.length*weights[0].length][];
	        	for (int station=0;station<patternParameters.getNumStations();station++){
	        		for (int nView=0;nView<patternParameters.getNumViews();nView++) {
	        			int n=station*weights[0].length+nView;
	        			debugDiffGreen[n]=diffFromAverage[station][nView][1];
	        			debugHighpassDiffGreen[n]=highPassDiff[station][nView][1];
	        			debugLowpassDiffGreen[n]=lowPassDiff[station][nView][1];
	        		}
	        	}
8213
	        	if (this.debugLevel>=(debugThreshold+1)) ShowDoubleFloatArrays.showArrays(
Andrey Filippov's avatar
Andrey Filippov committed
8214 8215 8216 8217 8218 8219
	        			debugDiffGreen,
	        			width,
	        			height,
	        			true,
	        			"DiffGreen"+nIter,
	        			titles);
8220
	        	if (this.debugLevel>=(debugThreshold+1)) ShowDoubleFloatArrays.showArrays(
Andrey Filippov's avatar
Andrey Filippov committed
8221 8222 8223 8224 8225 8226
	        			debugHighpassDiffGreen,
	        			width,
	        			height,
	        			true,
	        			"HighpassGreen"+nIter,
	        			titles);
Andrey Filippov's avatar
Andrey Filippov committed
8227

8228
	        	ShowDoubleFloatArrays.showArrays(
Andrey Filippov's avatar
Andrey Filippov committed
8229 8230 8231 8232 8233 8234
	        			debugLowpassDiffGreen,
	        			width,
	        			height,
	        			true,
	        			"LowpassGreen"+nIter,
	        			titles);
Andrey Filippov's avatar
Andrey Filippov committed
8235

Andrey Filippov's avatar
Andrey Filippov committed
8236
	        	String [] averageTitles={"Red","Green","Blue","Weight"};
8237
	        	ShowDoubleFloatArrays.showArrays(
Andrey Filippov's avatar
Andrey Filippov committed
8238 8239 8240 8241 8242 8243
	        			average,
	        			width,
	        			height,
	        			true,
	        			"Average-"+nIter,
	        			averageTitles);
Andrey Filippov's avatar
Andrey Filippov committed
8244

Andrey Filippov's avatar
Andrey Filippov committed
8245 8246 8247 8248 8249 8250 8251 8252 8253 8254 8255 8256
	    	}
    	} // for (int nIter=0;nIter<numIterations;nIter++){
    	// Apply new weights
    	if (apply) {
    		for (int station=0;station<patternParameters.getNumStations();station++){
    			for (int nView=0;nView<patternParameters.getNumViews();nView++) {
    				if (photometrics[station][nView]!=null){
    					for (int nPix=0;nPix<length;nPix++) photometrics[station][nView][3][nPix]*=weights[station][nView][nPix];
    				}
    			}
    		}
    	}
Andrey Filippov's avatar
Andrey Filippov committed
8257

Andrey Filippov's avatar
Andrey Filippov committed
8258 8259 8260
    }

    /**
Andrey Filippov's avatar
Andrey Filippov committed
8261
     *
Andrey Filippov's avatar
Andrey Filippov committed
8262
     * @param shrink sensor mask by this amount (sensor, non-decimated pixels)
Andrey Filippov's avatar
Andrey Filippov committed
8263 8264 8265
     * @param radius radial mask - zero if farther than radius, 0.5*(cos(pi*r/radius)+1.0) if less
     * @param minimalAlpha - zero mask below this threshold
     * @return returns arrray with the same size as sensorMask that corresponds to low-vignetting areas of the sensor/lens
Andrey Filippov's avatar
Andrey Filippov committed
8266 8267
     */
    // Using station 0 - should be not much difference
8268
    // older version with one type of sensors
Andrey Filippov's avatar
Andrey Filippov committed
8269 8270 8271 8272 8273 8274 8275 8276 8277 8278
    public double [][] nonVignettedMasks(
    		double shrink,
    		double radius,
    		double minimalAlpha){
    	if (this.pixelCorrection==null){
    		initSensorCorrection();
    	}
    	double [][]masks=new double [this.pixelCorrection.length][];
    	int maskIndex=2;
    	for (int numSensor=0;numSensor<masks.length;numSensor++){
8279 8280
//    		boolean small_sensor = fittingStrategy.distortionCalibrationData.isSmallSensor(numSensor);
			boolean small_sensor = fittingStrategy.distortionCalibrationData.getSmallSensors()[numSensor];
8281 8282 8283 8284 8285 8286 8287 8288 8289 8290 8291 8292 8293 8294 8295 8296 8297 8298 8299 8300 8301 8302 8303 8304 8305 8306 8307 8308
    		RefineParameters rp = small_sensor ? refineParameters.refineParametersSmall : refineParameters;

    		if (this.pixelCorrection[numSensor]==null) masks[numSensor] = null;
    		else {
    			masks[numSensor] = fittingStrategy.distortionCalibrationData.nonVignettedMask(
    					this.pixelCorrection[numSensor][maskIndex],
    					getSensorWidth(numSensor), // this.pixelCorrectionWidth,
    					getSensorHeight(numSensor), // this.pixelCorrectionHeight,
    					fittingStrategy.distortionCalibrationData.eyesisCameraParameters.eyesisSubCameras[0][numSensor].px0,     // lens center X (sensor, non-decimated pix)
    					fittingStrategy.distortionCalibrationData.eyesisCameraParameters.eyesisSubCameras[0][numSensor].py0,     // lens center Y (sensor, non-decimated pix)
    					shrink,
    					radius,
    					minimalAlpha);
    			//    			System.out.println("nonVignettedMasks(), masks["+numSensor+"].length="+masks[numSensor].length);
    		}
    	}
    	return masks;
    }

// modified for multiple types of sensors:
    public double [][] nonVignettedMasks(
    		RefineParameters refineParameters){
    	if (this.pixelCorrection==null){
    		initSensorCorrection();
    	}
    	double [][]masks=new double [this.pixelCorrection.length][];
    	int maskIndex=2;
    	for (int numSensor=0;numSensor<masks.length;numSensor++){
8309 8310
//				boolean small_sensor = fittingStrategy.distortionCalibrationData.isSmallSensor(numSensor);
				boolean small_sensor = fittingStrategy.distortionCalibrationData.getSmallSensors()[numSensor];
8311 8312 8313 8314 8315 8316
				RefineParameters rp = small_sensor ? refineParameters.refineParametersSmall : refineParameters;

    		double shrink = rp.flatFieldShrink;
    		double radius = rp.flatFieldNonVignettedRadius;
    		double minimalAlpha=rp.flatFieldMinimalAlpha;

Andrey Filippov's avatar
Andrey Filippov committed
8317 8318 8319 8320
    		if (this.pixelCorrection[numSensor]==null) masks[numSensor] = null;
    		else {
    			masks[numSensor] = fittingStrategy.distortionCalibrationData.nonVignettedMask(
    					this.pixelCorrection[numSensor][maskIndex],
8321 8322
    					getSensorWidth(numSensor), // this.pixelCorrectionWidth,
    					getSensorHeight(numSensor), // this.pixelCorrectionHeight,
Andrey Filippov's avatar
Andrey Filippov committed
8323 8324 8325 8326 8327 8328 8329 8330 8331
    	        		fittingStrategy.distortionCalibrationData.eyesisCameraParameters.eyesisSubCameras[0][numSensor].px0,     // lens center X (sensor, non-decimated pix)
    	        		fittingStrategy.distortionCalibrationData.eyesisCameraParameters.eyesisSubCameras[0][numSensor].py0,     // lens center Y (sensor, non-decimated pix)
    	        		shrink,
    	        		radius,
    	        		minimalAlpha);
//    			System.out.println("nonVignettedMasks(), masks["+numSensor+"].length="+masks[numSensor].length);
    		}
    	}
    	return masks;
Andrey Filippov's avatar
Andrey Filippov committed
8332 8333
    }

8334 8335 8336



8337 8338 8339 8340
    // Use series0 to find grid mismatch (and set it correctly). Uses that pattern in the world coordinate system is
    // approximately in XY plane, so by freezing all other parameters but GXY0 and GXY1 it is possible to find
    // the pattern grid match.
    public int [] findImageGridOffset(
8341 8342 8343
    		int     num_img,
    		int     ser_num, // number of series to reprogram (< 0 - from the last one)
    		boolean adjust_attitude, // true for eo, false for lwir (uses exact attitude from eo)
8344
    		boolean even,
8345 8346 8347 8348 8349 8350 8351 8352 8353 8354 8355 8356 8357
    		PatternParameters patternParameters,
    		double [] stats) { // result quality, null OK
    	if (ser_num < 0) {
    		ser_num = fittingStrategy.parameterMode.length + ser_num; // use from the last one
    	}
		if (this.debugLevel > 0) {
			System.out.println("Will use/modify fitting series "+ser_num+" to adjust image "+num_img);
			if (adjust_attitude) {
				System.out.println("Will adjust GXYZ0, GXYZ1, goniometerHorizontal, and goniometerAxial");
			} else {
				System.out.println("Will adjust only GXYZ0 and GXYZ1.");
			}
		}
8358

8359 8360 8361 8362 8363 8364 8365 8366 8367 8368 8369 8370 8371 8372 8373 8374 8375 8376
    	int was_seriesNumber = seriesNumber;
		// set series ser_num (was 0) to this set images
		DistortionCalibrationData dcd = fittingStrategy.distortionCalibrationData;
		int par_index_goniometerHorizontal = dcd.getParameterIndexByName("goniometerHorizontal");
		int par_index_goniometerAxial =      dcd.getParameterIndexByName("goniometerAxial");
		int par_index_GXYZ0 =                dcd.getParameterIndexByName("GXYZ0");
		int par_index_GXYZ1 =                dcd.getParameterIndexByName("GXYZ1");
		for (int i = 0; i < fittingStrategy.parameterMode[ser_num].length; i++) {
			 fittingStrategy.parameterMode[ser_num][i] = FittingStrategy.modeFixed; // 0
		}
		fittingStrategy.parameterMode[ser_num][par_index_GXYZ0] =                    FittingStrategy.modeIndividual; // 3
		fittingStrategy.parameterMode[ser_num][par_index_GXYZ1] =                    FittingStrategy.modeIndividual; // 3
		if (adjust_attitude) {
			fittingStrategy.parameterMode[ser_num][par_index_goniometerHorizontal] = FittingStrategy.modeIndividual; // 3
			fittingStrategy.parameterMode[ser_num][par_index_goniometerAxial] =      FittingStrategy.modeIndividual; // 3
		}

		boolean [] selection = fittingStrategy.selectAllImages(ser_num); // enable all images in series 0
8377 8378
		for (int i=0;i<selection.length;i++) selection[i]=false;
		selection[num_img]=true;
8379 8380 8381
		fittingStrategy.setImageSelection(ser_num,selection);
		seriesNumber=   ser_num; // start from 0;
		initFittingSeries(false, filterForAll,ser_num); // will set this.currentVector, will build parameter map too
8382
		//this.stopAfterThis[numSeries]
8383
		fittingStrategy.stopAfterThis[ser_num]=true;
8384 8385
		stopEachStep=      false;
		stopEachSeries=    false; // will not ask for confirmation after done
8386
		lambda =           fittingStrategy.lambdas[ser_num];
8387 8388 8389 8390 8391 8392 8393 8394 8395
		boolean   LMA_OK = false;
		try {
			LMA_OK = 	LevenbergMarquardt (false, true); //  skip dialog, dry run (no updates)
		} catch (Exception e) {
			// LMA failed - e.g. not enough points (Singular Matrix)
		}
		if (!LMA_OK) {
			return null; // LMA did not converge
		}
8396

8397 8398 8399 8400 8401 8402 8403
//		DistortionCalibrationData dcd = this.fittingStrategy.distortionCalibrationData;
// find indices of GXYZ0 and GXYZ1 in the vector
		int index_GXYZ0 = this.fittingStrategy.reverseParameterMap[num_img][par_index_GXYZ0];
		int index_GXYZ1 = this.fittingStrategy.reverseParameterMap[num_img][par_index_GXYZ1];

		double [] new_XY = {this.currentVector[index_GXYZ0],this.currentVector[index_GXYZ1]};
//		DistortionCalibrationData dcd = this.fittingStrategy.distortionCalibrationData;
8404 8405 8406 8407 8408 8409 8410
//		int num_set = dcd.gIP[num_img].getSetNumber();
		double [] 	ref_XYZ = dcd.getXYZ(num_img);
		double []   diff_XY = {
				new_XY[0] -ref_XYZ[0],
				new_XY[1] -ref_XYZ[1]};

//save safe settings to run LMA manually (or save what was set)
8411 8412
		seriesNumber=      was_seriesNumber; // start from 0;
		initFittingSeries  (false,filterForAll,seriesNumber); // will set this.currentVector
8413 8414
		stopEachSeries=    true; // will not ask for confirmation after done
		stopOnFailure=     true;
8415 8416
		lambda=            fittingStrategy.lambdas[seriesNumber];
		double [] errs = new double[2];
8417 8418 8419 8420 8421

		int [] grid_offset = dcd.suggestOffset (
        		num_img,
        		diff_XY, // This XYZ minus reference XYZ  z is not used, may be just[2]
        		even,
8422 8423 8424 8425 8426 8427 8428
        		patternParameters,
        		errs);
		if (stats != null) {
			stats[0] = this.currentRMS;
			stats[1] = errs[0]; // dU
			stats[2] = errs[1]; // dV
		}
8429
		return grid_offset;
8430
    }
Andrey Filippov's avatar
Andrey Filippov committed
8431

8432 8433 8434 8435
    public boolean adjustAttitudeAfterOffset(
    		int     num_img,
    		int     ser_num, // number of series to reprogram
    		PatternParameters patternParameters) {
8436 8437 8438 8439 8440 8441 8442 8443 8444 8445 8446
    	int [] num_imgs = {num_img};
    	return  adjustAttitudeAfterOffset(
        		num_imgs,
        		ser_num, // number of series to reprogram
        		patternParameters);
    }

    public boolean adjustAttitudeAfterOffset(
    		int  []   num_imgs,
    		int     ser_num, // number of series to reprogram
    		PatternParameters patternParameters) {
8447 8448 8449 8450
    	if (ser_num < 0) {
    		ser_num = fittingStrategy.parameterMode.length + ser_num; // use from the last one
    	}
		if (this.debugLevel > 0) {
8451 8452 8453 8454 8455
			System.out.print("Will use/modify fitting series "+ser_num+" for to adjust  az, tilt of images: ");
			for (int num_img: num_imgs) {
				System.out.print(" "+num_img);
			}
			System.out.println();
8456 8457 8458 8459 8460 8461 8462 8463 8464 8465 8466 8467 8468 8469
			System.out.println("Will adjust goniometerHorizontal, and goniometerAxial");
		}
    	int was_seriesNumber = seriesNumber;
		// set series ser_num (was 0) to this set images
		DistortionCalibrationData dcd = fittingStrategy.distortionCalibrationData;
		int par_index_goniometerHorizontal = dcd.getParameterIndexByName("goniometerHorizontal");
		int par_index_goniometerAxial =      dcd.getParameterIndexByName("goniometerAxial");
		for (int i = 0; i < fittingStrategy.parameterMode[ser_num].length; i++) {
			 fittingStrategy.parameterMode[ser_num][i] = FittingStrategy.modeFixed; // 0
		}
		fittingStrategy.parameterMode[ser_num][par_index_goniometerHorizontal] = FittingStrategy.modeIndividual; // 3
		fittingStrategy.parameterMode[ser_num][par_index_goniometerAxial] =      FittingStrategy.modeIndividual; // 3
		boolean [] selection = fittingStrategy.selectAllImages(ser_num); // enable all images in series 0
		for (int i=0;i<selection.length;i++) selection[i]=false;
8470 8471 8472
		for (int num_img:num_imgs) {
			selection[num_img]=true;
		}
8473 8474 8475 8476 8477 8478 8479 8480 8481 8482 8483 8484 8485 8486 8487 8488 8489 8490 8491 8492 8493 8494 8495
		fittingStrategy.setImageSelection(ser_num,selection);
		seriesNumber=   ser_num; // start from 0;
		initFittingSeries(false, filterForAll,ser_num); // will set this.currentVector, will build parameter map too
		fittingStrategy.stopAfterThis[ser_num]=true;
		stopEachStep=      false;
		stopEachSeries=    false; // will not ask for confirmation after done
		lambda =           fittingStrategy.lambdas[ser_num];
		boolean   LMA_OK = false;
		try {
			LMA_OK = 	LevenbergMarquardt (false, false); // true); //  skip dialog, dry run (no updates)
		} catch (Exception e) {
			// LMA failed - e.g. not enough points (Singular Matrix)
		}
		if (!LMA_OK) {
			return false; // LMA did not converge
		}
//save safe settings to run LMA manually (or save what was set)
		seriesNumber=      was_seriesNumber; // start from 0;
		initFittingSeries  (false,filterForAll,seriesNumber); // will set this.currentVector
		stopEachSeries=    true; // will not ask for confirmation after done
		stopOnFailure=     true;
		lambda=            fittingStrategy.lambdas[seriesNumber];
		return true;
8496 8497
    }

8498
    
8499 8500 8501
    public boolean LevenbergMarquardt(
    		boolean openDialog,
    		boolean dry_run){ // do not save results
8502 8503 8504 8505 8506 8507 8508 8509 8510 8511
    	return LevenbergMarquardt(
        		openDialog,
        		dry_run,
        		false);
    }

    public boolean LevenbergMarquardt(
    		boolean openDialog,
    		boolean dry_run,  // do not save results
    		boolean calc_dUV){
Andrey Filippov's avatar
Andrey Filippov committed
8512 8513 8514 8515 8516
    	if (this.fittingStrategy==null) {
        		String msg="Fitting strategy does not exist, exiting";
        		IJ.showMessage("Error",msg);
        		throw new IllegalArgumentException (msg);
    	}
Andrey Filippov's avatar
Andrey Filippov committed
8517
//    	fittingStrategy.distortionCalibrationData.readAllGrids();
Andrey Filippov's avatar
Andrey Filippov committed
8518 8519 8520 8521 8522 8523 8524 8525 8526
    	if (openDialog && !selectLMAParameters()) return false;
    	this.startTime=System.nanoTime();
//    	while (this.seriesNumber<fittingStrategy.getNumSeries()){ // TODO: Add "stop" tag to series
    	this.firstRMS=-1; //undefined
    	this.fittingStrategy.invalidateSelectedImages(this.seriesNumber); // undo any filters, only user selection of the  images will be in effect
    	while (this.fittingStrategy.isSeriesValid(this.seriesNumber)){ // TODO: Add "stop" tag to series
    		this.currentVector=null; // invalidate for the new series
    		boolean wasLastSeries=false;
    		while (true) { // loop for the same series
Andrey Filippov's avatar
Andrey Filippov committed
8527

8528
    			boolean [] state=stepLevenbergMarquardtFirst(this.seriesNumber, calc_dUV);
Andrey Filippov's avatar
Andrey Filippov committed
8529 8530 8531 8532 8533 8534 8535 8536
    			if (!this.fittingStrategy.isSeriesValid(this.seriesNumber)){
    				System.out.println("Series "+this.seriesNumber+" is invalid when weight function filters are applied (probably removed some images)");
    				return false;
    			}
    			if (state==null) {
    				String msg="Calculation aborted by user request";
    				IJ.showMessage(msg);
    				System.out.println(msg);
Andrey Filippov's avatar
Andrey Filippov committed
8537
    				return false;
Andrey Filippov's avatar
Andrey Filippov committed
8538
    			}
Andrey Filippov's avatar
Andrey Filippov committed
8539

Andrey Filippov's avatar
Andrey Filippov committed
8540 8541 8542 8543 8544 8545 8546 8547 8548 8549 8550 8551
    			if (this.debugLevel>1) System.out.println(this.seriesNumber+":"+this.iterationStepNumber+": stepLevenbergMarquardtFirst("+this.seriesNumber+")==>"+state[1]+":"+state[0]);
				boolean cont=true;
				// Make it success if this.currentRMS<this.firstRMS even if LMA failed to converge
				if (state[1] && !state[0] && (this.firstRMS>this.currentRMS)){
					if (this.debugLevel>1) System.out.println("LMA failed to converge, but RMS improved from the initial value ("+this.currentRMS+" < "+this.firstRMS+")");
					state[0]=true;
				}
    			if (
    					(this.stopRequested.get()>0) || // graceful stop requested
    					(this.stopEachStep) ||
    					(this.stopEachSeries && state[1]) ||
    					(this.stopOnFailure && state[1] && !state[0])){
Andrey Filippov's avatar
Andrey Filippov committed
8552

Andrey Filippov's avatar
Andrey Filippov committed
8553 8554 8555 8556 8557 8558 8559 8560 8561 8562 8563 8564 8565 8566 8567
    				if (this.debugLevel>0){
    					if (this.stopRequested.get()>0) System.out.println("User requested stop");
    					System.out.println("LevenbergMarquardt(): series:step ="+this.seriesNumber+":"+this.iterationStepNumber+
    						", RMS="+IJ.d2s(this.currentRMS,8)+
    						" ("+IJ.d2s(this.firstRMS,8)+") "+
    						", RMSPure="+IJ.d2s(this.currentRMSPure,8)+
    						" ("+IJ.d2s(this.firstRMSPure,8)+
    						") at "+ IJ.d2s(0.000000001*(System.nanoTime()-this.startTime),3));
    				}
    				long startDialogTime=System.nanoTime();
    				cont=dialogLMAStep(state);
    				this.stopRequested.set(0); // Will not stop each run
    				this.startTime+=(System.nanoTime()-startDialogTime); // do not count time used by the User.
    				if (this.showThisImages) showDiff (this.currentfX, "fit-"+this.iterationStepNumber);
    				if (this.showNextImages) showDiff (this.nextfX,    "fit-"+(this.iterationStepNumber+1));
8568 8569
    			} else if (this.debugLevel>1){
					System.out.println("==> LevenbergMarquardt(): before action series:step ="+this.seriesNumber+":"+this.iterationStepNumber+
8570 8571 8572 8573 8574
    						", RMS="+IJ.d2s(this.currentRMS,8)+
    						" ("+IJ.d2s(this.firstRMS,8)+") "+
    						", RMSPure="+IJ.d2s(this.currentRMSPure,8)+
    						" ("+IJ.d2s(this.firstRMSPure,8)+
    						") at "+ IJ.d2s(0.000000001*(System.nanoTime()-this.startTime),3));
Andrey Filippov's avatar
Andrey Filippov committed
8575 8576 8577 8578 8579 8580 8581 8582 8583 8584 8585
    			}
				stepLevenbergMarquardtAction(); // apply step - in any case?
				if (this.updateStatus){
   	   				IJ.showStatus(this.seriesNumber+": "+"Step #"+this.iterationStepNumber+
   	   						" RMS="+IJ.d2s(this.currentRMS,8)+
   	   						" ("+IJ.d2s(this.firstRMS,8)+")"+
   	   						" RMSPure="+IJ.d2s(this.currentRMSPure,8)+
   	   						" ("+IJ.d2s(this.firstRMSPure,8)+")"+
   	   						" ");
//   	   				showStatus(this.seriesNumber+": "+"Step #"+this.iterationStepNumber+" RMS="+IJ.d2s(this.currentRMS,8)+ " ("+IJ.d2s(this.firstRMS,8)+")",0);
				}
8586 8587 8588 8589 8590 8591 8592 8593
				if ((this.debugLevel>0) && ((this.debugLevel>1) || ((System.nanoTime()-this.startTime)>10000000000.0))){ // > 10 sec
					System.out.println("--> LevenbergMarquardt(): series:step ="+this.seriesNumber+":"+this.iterationStepNumber+
							", RMS="+IJ.d2s(this.currentRMS,8)+
							" ("+IJ.d2s(this.firstRMS,8)+") "+
							", RMSPure="+IJ.d2s(this.currentRMSPure,8)+
							" ("+IJ.d2s(this.firstRMSPure,8)+
							") at "+ IJ.d2s(0.000000001*(System.nanoTime()-this.startTime),3));
				}
Andrey Filippov's avatar
Andrey Filippov committed
8594
				if (!cont){
8595
					if (this.saveSeries && !dry_run) {
Andrey Filippov's avatar
Andrey Filippov committed
8596 8597 8598 8599
						saveFittingSeries(); // will save series even if it ended in failure, vector will be only updated
						updateCameraParametersFromCalculated(true); // update camera parameters from all (even disabled) images
						updateCameraParametersFromCalculated(false); // update camera parameters from enabled only images (may overwrite some of the above)
					}
Andrey Filippov's avatar
Andrey Filippov committed
8600
					// if RMS was decreased. this.saveSeries==false after dialogLMAStep(state) only if "cancel" was pressed
Andrey Filippov's avatar
Andrey Filippov committed
8601 8602
					return this.saveSeries; // TODO: Maybe change result?
				}
Andrey Filippov's avatar
Andrey Filippov committed
8603
//stepLevenbergMarquardtAction();
Andrey Filippov's avatar
Andrey Filippov committed
8604 8605
    			if (state[1]) {
    				if (!state[0]) return false; // sequence failed
8606 8607 8608 8609 8610 8611 8612 8613 8614
    				if (dry_run) {
    					wasLastSeries= true; // always just one series
    				} else {
    					saveFittingSeries();
    					updateCameraParametersFromCalculated(true); // update camera parameters from all (even disabled) images
    					updateCameraParametersFromCalculated(false); // update camera parameters from enabled only images (may overwrite some of the above)
    					wasLastSeries=this.fittingStrategy.isLastSeries(this.seriesNumber);
    					this.seriesNumber++;
    				}
Andrey Filippov's avatar
Andrey Filippov committed
8615 8616 8617 8618 8619
    				break; // while (true), proceed to the next series
    			}
    		}
//    		if (this.fittingStrategy.isLastSeries(this.seriesNumber)) break;
    		if (wasLastSeries) break;
Andrey Filippov's avatar
Andrey Filippov committed
8620
//    		this.seriesNumber++;
Andrey Filippov's avatar
Andrey Filippov committed
8621 8622 8623 8624 8625 8626 8627 8628
    	} // while (this.fittingStrategy.isSeriesValid(this.seriesNumber)){ // TODO: Add "stop" tag to series
		if (this.debugLevel>0) System.out.println("LevenbergMarquardt(): series="+this.seriesNumber+
				", RMS="+this.currentRMS+
				" ("+this.firstRMS+") "+
				", RMSPure="+this.currentRMSPure+
				" ("+this.firstRMSPure+
				") at "+ IJ.d2s(0.000000001*(System.nanoTime()-this.startTime),3));
    	return true; // all series done
Andrey Filippov's avatar
Andrey Filippov committed
8629

Andrey Filippov's avatar
Andrey Filippov committed
8630
    }
Andrey Filippov's avatar
Andrey Filippov committed
8631 8632


Andrey Filippov's avatar
Andrey Filippov committed
8633 8634 8635 8636 8637 8638 8639 8640 8641 8642 8643 8644 8645 8646 8647 8648 8649 8650 8651 8652 8653
    /**
     * Show debug image (see showDiff (int imgNumber, double [] fX, String title ) above)
     * for each image used in the current fitting series
     * @param fX - calculated data for all images (use with this.Y)
     * @param title - Image title
     */
    	public void showDiff (double [] fX, String title ){
    		boolean [] selectedImages=fittingStrategy.selectedImages();
    		for (int imgNum=0;imgNum<selectedImages.length;imgNum++) if (selectedImages[imgNum]) {
    			showDiff (imgNum, fX, title+"-"+imgNum);
    		}
    	}

	/**
	 * Shows a 7-slice image for provided f(X) array (this.Y is also used):
	 * 1 - distance   - sqrt (dx^2+dy^2)
	 * 2 - difference for pixel-X
	 * 3 - difference for pixel-Y
	 * 4 - calculated pixel-X
	 * 5 - calculated pixel-Y
	 * 6 - measured   pixel-X
Andrey Filippov's avatar
Andrey Filippov committed
8654
	 * 7 - measured   pixel-Y
Andrey Filippov's avatar
Andrey Filippov committed
8655 8656 8657 8658 8659 8660 8661 8662 8663 8664 8665 8666 8667 8668 8669 8670 8671 8672 8673 8674
	 * @param imgNumber - number of image
	 * @param fX - calculated data for all images (use with this.Y)
	 * @param title - Image title
	 */

	public void showDiff (int imgNumber, double [] fX, String title ){
		String [] titles={"distance","diff-X","diff-Y","f(x)-X","f(x)-Y","y-X","y-Y"};
		double [] diff=calcYminusFx(fX);
// find data range for the selected image
		int index=0;
		int numImg=fittingStrategy.distortionCalibrationData.getNumImages();
		boolean [] selectedImages=fittingStrategy.selectedImages();
		for (int imgNum=0;(imgNum<imgNumber) && (imgNum<numImg) ;imgNum++) if (selectedImages[imgNum])
			index+=fittingStrategy.distortionCalibrationData.gIP[imgNum].pixelsUV.length;
		int width=getGridWidth();
		if (this.debugLevel>1) {
			System.out.println("showDiff("+imgNumber+",...): fX.length="+fX.length+" this image index="+index);
		}
		double [][] imgData=new double[7][getGridHeight() * width];
		for (int i=0;i<imgData.length;i++) for (int j=0;j<imgData[i].length;j++)imgData[i][j]=0.0;
Andrey Filippov's avatar
Andrey Filippov committed
8675

Andrey Filippov's avatar
Andrey Filippov committed
8676 8677 8678 8679 8680 8681 8682 8683 8684 8685 8686 8687
		for (int i=0;i<fittingStrategy.distortionCalibrationData.gIP[imgNumber].pixelsUV.length;i++){
			int u=fittingStrategy.distortionCalibrationData.gIP[imgNumber].pixelsUV[i][0]+patternParameters.U0;
			int v=fittingStrategy.distortionCalibrationData.gIP[imgNumber].pixelsUV[i][1]+patternParameters.V0;
			int vu=u+width*v;
			imgData[0][vu]=   Math.sqrt(diff[2*(index+i)]*diff[2*(index+i)] + diff[2*(index+i)+1]*diff[2*(index+i)+1]);
			imgData[1][vu]=   diff[2*(index+i)]; // out of bound 1410
			imgData[2][vu]=   diff[2*(index+i)+1];
			imgData[3][vu]=     fX[2*(index+i)];
			imgData[4][vu]=     fX[2*(index+i)+1];
			imgData[5][vu]= this.Y[2*(index+i)];
			imgData[6][vu]= this.Y[2*(index+i)+1];
		}
8688
		ShowDoubleFloatArrays.showArrays(imgData, width, getGridHeight(),  true, title, titles);
Andrey Filippov's avatar
Andrey Filippov committed
8689 8690 8691 8692 8693 8694
	}
	/**
	 * Calculates corrections to X and Y coordinates of the grid nodes
	 * @param variationPenalty - cost of different Z for different stations
	 * @param fixXY - if true, do not adjust X,Y - only Z
	 * @param stationGroupsIn - consider some stations have the same pattern - assign them the same number. Negative - do not process the station
Andrey Filippov's avatar
Andrey Filippov committed
8695
	 * @param grid3DCorrection - if true - calculate 3d correction, false - slow 3d (2d perpendicular to view)
Andrey Filippov's avatar
Andrey Filippov committed
8696 8697 8698 8699 8700 8701 8702 8703 8704 8705 8706 8707 8708 8709 8710 8711 8712 8713 8714 8715 8716 8717 8718 8719 8720 8721 8722 8723 8724 8725 8726 8727 8728 8729 8730 8731 8732 8733 8734 8735 8736 8737 8738 8739 8740 8741 8742 8743 8744 8745 8746 8747 8748 8749 8750 8751 8752 8753 8754 8755
	 * @param maxZCorr - maximal allowed correction in Z-direction (if wants more, will fall back to 2-d correction (perpendicular to the view)
	 * @param showIndividual - show individual images
	 * @return  combination of 3 arrays: 1 (original) - first index - 0 - correction x (mm), 1 - correction y(mm), 2 - correction z(mm)  3 - weight (number of images used)
	 * 2 - gridZCorr3d - per station differential Z correction
	 * 3 - gridZCorr3dWeight - per station weight of Z-corrections
	 */

	public double [][][] calculateGridXYZCorr3D(
			double variationPenalty,
            boolean fixXY,
            int [] stationGroupsIn,
			boolean grid3DCorrection,
			boolean rotateCorrection,
			double maxZCorr,
			boolean noFallBack,
			boolean showIndividual,
			int threadsMax,
			boolean updateStatus
			){
		int debugThreshold=2;
		// Normalize stationGroups
		int numStations=fittingStrategy.distortionCalibrationData.getNumStations();
		int [] stationGroups=new int [numStations];
		int [] stationGroupsTmp=(stationGroupsIn==null)?(new int [0]):stationGroupsIn.clone();
		for (int i=0;i<numStations;i++) stationGroups[i]=-1;
		int numberOfZGroups=0;
		for (int i=0;i<stationGroupsTmp.length;i++) if (stationGroupsTmp[i]>=0){
			for (int j=i;j<stationGroupsTmp.length;j++) if (stationGroupsTmp[j]==stationGroupsTmp[i]){
				stationGroups[j]=numberOfZGroups;
				if (j>i) stationGroupsTmp[j]=-1;
			}
			numberOfZGroups++;
		}
		if (numberOfZGroups==0) {
			System.out.println ("calculateGridXYZCorr3D(), no groups defined - using a single group for all stations");
			numberOfZGroups=1;
			for (int i=0;i<numStations;i++) stationGroups[i]=0;
		}
		if (this.debugLevel>1) {
			System.out.println ("calculateGridXYZCorr3D(), groups: "+numberOfZGroups);
			for (int i=0;i<stationGroups.length;i++) if (stationGroups[i]>=0){
				System.out.println ("  station "+i+": group "+stationGroups[i]);
			}
		}

		int width=getGridWidth();
		int height=getGridHeight();
		boolean [] selectedImages=fittingStrategy.selectedImages();
		double [][] cameraXYZ=new double [selectedImages.length][];

		double [][][] gridCorr2d=calculateGridXYZCorr2D(
				width,
				height,
				stationGroups,
				selectedImages,
				cameraXYZ,
				this.lensDistortionParameters,
				showIndividual,
				threadsMax,
				updateStatus);
Andrey Filippov's avatar
Andrey Filippov committed
8756 8757


Andrey Filippov's avatar
Andrey Filippov committed
8758 8759
		IJ.showStatus("Calculating pattern 3d correction...");
// now using gridCorr2d[imgNum], cameraXYZ[imgNum] and patternParameters.gridGeometry[v][u] find the 3d correction     public double [][][] gridGeometry=null; // [v][u]{x,y,z,"alpha"} alpha=0 - no ghrid, 1 - grid
Andrey Filippov's avatar
Andrey Filippov committed
8760
		double [][] gridCorr3d=  new double [4][width*height];
Andrey Filippov's avatar
Andrey Filippov committed
8761 8762 8763 8764 8765 8766 8767 8768 8769 8770 8771 8772 8773 8774 8775 8776 8777 8778 8779 8780 8781 8782 8783 8784 8785
		double [][] gridZCorr3d =new double [numStations][width*height];
		double [][] gridZCorr3dWeight =new double [numStations][width*height];
		for (int n=0;n<gridCorr3d.length;n++) for (int i=0;i<gridCorr3d[0].length;i++) gridCorr3d[n][i]=0.0;
		for (int n=0;n<gridZCorr3d.length;n++) for (int i=0;i<gridZCorr3d[0].length;i++){
			gridZCorr3d[n][i]=0.0;
			gridZCorr3dWeight[n][i]=0.0;
		}
		double Cx,Cy,Cz,Cxy,Cxz,Cyz;
		double [] V= new double[3];
		double [] V2= new double[3];
		int debugIndex=(height/2)*width+ (width/2);
		int debugIndex1=(height/2)*width+ (width/4);
		double [] alphaStation=new double [numStations];
		int zIndex=fixXY?0:2;
		int numVariables=numberOfZGroups+zIndex;
		double [][] aM=new double [numVariables][numVariables];
		double [][] aB=new double [numVariables][1];
		double []   zPerStation= new double [numStations];

		for (int v=0;v<height;v++) for (int u=0;u<width; u++){
			int index=u+v*width;
			boolean thisDebug=(this.debugLevel>debugThreshold) && ((index==debugIndex) || (index==debugIndex1));
			if (thisDebug) System.out.println("calculateGridXYZCorr3D() debug("+this.debugLevel+"): index="+index+" v="+v+" u="+u);
			for (int i=0;i<numVariables;i++){
				aB[i][0]=0.0;
Andrey Filippov's avatar
Andrey Filippov committed
8786
				for (int j=0;j<numVariables;j++) aM[i][j]=0.0;
Andrey Filippov's avatar
Andrey Filippov committed
8787 8788 8789 8790 8791 8792 8793 8794 8795 8796 8797 8798 8799 8800 8801 8802 8803 8804 8805 8806 8807
			}
			for (int i=0;i<numStations;i++) alphaStation[i]=0.0;
			double alpha=0.0;
			boolean fallBack2D=true;
			if (grid3DCorrection) {
				for (int imgNum=0;imgNum<selectedImages.length;imgNum++) {
					int station=fittingStrategy.distortionCalibrationData.gIP[imgNum].getStationNumber(); // number of sub-camera
					int zGroup=stationGroups[station];
					if ((gridCorr2d[imgNum]!=null)  && (gridCorr2d[imgNum][3][index]>0.0) && (zGroup>=0)) {
						zPerStation[station]=gridCorr2d[imgNum][2][index]; // should all be the same for the same station
						// calculate unity vector from the camera lens to the grid point
						double absV=0.0;
						for (int i=0;i<V.length;i++){
							V[i]=patternParameters.gridGeometry[v][u][i]+gridCorr2d[imgNum][i][index]-cameraXYZ[imgNum][i]; // corrected value, including zCorr
							absV+=V[i]*V[i];
						}
						absV=Math.sqrt(absV);
						if (absV>0) for (int i=0;i<V.length;i++) V[i]/=absV;
						for (int i=0;i<V.length;i++) V2[i]=V[i]*V[i];
						if (thisDebug) System.out.println(" imgNum="+imgNum+" V[0]="+IJ.d2s(V[0],4)+" V[1]="+IJ.d2s(V[1],4)+" V[2]="+IJ.d2s(V[2],4)+
								" V2[0]="+IJ.d2s(V2[0],4)+" V2[1]="+IJ.d2s(V2[1],4)+" V2[2]="+IJ.d2s(V2[2],4));
Andrey Filippov's avatar
Andrey Filippov committed
8808 8809
						// When performin 3-d correction (X,Y,Z) the result point has to have minimal weighted sum of squared distances to all rays
// when summing for different stations, multiply W by sign(image belongs to station)
Andrey Filippov's avatar
Andrey Filippov committed
8810 8811 8812 8813 8814 8815 8816 8817 8818 8819 8820 8821 8822 8823 8824 8825 8826
/*
Px, Py - calculated correction for individual image
V={Vx,Vy,Vz} unity vector from the camera lens center to the {Px,Py,0}
A - vector from the {Px,Py,0} to {X,Y,Z} = {X-Px,Y-Py,Z}
Projection of A on V will have length of A(.)V, Vector B=V*(A(.)V)
Vector D=A-B = A - V*(A(.)V)
D2=D(.)D= A(.)A - 2* (A(.)V ) * (A(.)V ) + (A(.)V ) * (A(.)V ) = A(.)A -  (A(.)V ) * (A(.)V )
D2=A(.)A -  (A(.)V )^2

A(.)A=(X-Px)^2 + (Y-Py)^2 + Z^2 =X^2 -2*X*Px +Px^2 +Y^2 -2*Y*Py +Py^2 +Z^2
A(.)A=X^2 -2*X*Px +Px^2 +Y^2 -2*Y*Py +Py^2 +Z^2
A(.)V=      (X-Px)*Vx + (Y-Py)*Vy + Z*Vz
(A(.)V)^2= ((X-Px)*Vx + (Y-Py)*Vy + Z*Vz)^2 = ((X-Px)*Vx)^2 + ((Y-Py)*Vy)^2 + (Z*Vz)^2 + 2*((X-Px)*Vx)*((Y-Py)*Vy)+ 2*((X-Px)*Vx)*(Z*Vz)+2*((Y-Py)*Vy)*(Z*Vz)
(A(.)V)^2= X^2*Vx^2 +Px^2*Vx^2 - 2*X*Px*Vx^2 +Y^2*Vy^2+Py^2*Vy^2-2*Y*Py*Vy^2 +Z^2*Vz^2 +2*X*Y*Vx*Vy +2*Px*Py*Vx*Vy - 2*X*Py*Vx*Vy - 2*Y*Px*Vx*Vy +2*X*Z*Vx*Vz - 2*Z*Px*Vx*Vz +2*Y*Z*Vy*Vz -2*z*Py*Vy*Vz

D2=
  +X^2 - X^2*Vx^2
Andrey Filippov's avatar
Andrey Filippov committed
8827
  +Y^2 - Y^2*Vy^2
Andrey Filippov's avatar
Andrey Filippov committed
8828 8829 8830 8831 8832 8833 8834 8835 8836 8837 8838 8839 8840 8841 8842 8843 8844 8845
  +Z^2 - Z^2*Vz^2
-2*X*Y* Vx*Vy
-2*X*Z* Vx*Vz
-2*Y*Z* Vy*Vz
-2*X*Px +2*X*Px*Vx^2+ 2*X*Py*Vx*Vy
-2*Y*Py +2*Y*Py*Vy^2+ 2*Y*Px*Vx*Vy
+2*Z*Px*Vx*Vz   +2*Z*Py*Vy*Vz
+Px^2  +Py^2 -Px^2*Vx^2   -Py^2*Vy^2    -2*Px*Py*Vx*Vy

0= dD2/dX/2= X*(1-Vx^2) - Y* Vx*Vy - Z* Vx*Vz -Px + Px*Vx^2  + Py*Vx*Vy
0= dD2/dY/2= Y*(1-Vy^2) - X* Vx*Vy - Z* Vy*Vz -Py + Py*Vy^2  + Px*Vx*Vy
0= dD2/dZ/2= Z*(1-Vz^2) - X* Vx*Vz - Y* Vy*Vz     + Px*Vx*Vz + Py*Vy*Vz


 X*(Vx^2-1) + Y* (Vx*Vy)  + Z* (Vx*Vz)   =  Px * (Vx^2-1)  + Py* (Vx*Vy)
 X*(Vx*Vy)  + Y* (Vy^2-1) + Z* (Vy*Vz)   =  Px * (Vx*Vy)   + Py * (Vy^2-1)
 X*(Vx*Vz)  + Y* (Vy*Vz)  + Z* (Vz^2-1)  =  Px * (Vx*Vz)   + Py* (Vy*Vz)

Andrey Filippov's avatar
Andrey Filippov committed
8846

Andrey Filippov's avatar
Andrey Filippov committed
8847
 */
Andrey Filippov's avatar
Andrey Filippov committed
8848

Andrey Filippov's avatar
Andrey Filippov committed
8849 8850 8851
//   | sum(Wi*Cxi),  sum(Wi*Cxyi), sum(Wi*Cxzi) |
//M= | sum(Wi*Cxyi), sum(Wi*Cyi ), sum(Wi*Cyzi) |
//   | sum(Wi*Cxzi), sum(Wi*Cyzi), sum(Wi*Czi ) |
Andrey Filippov's avatar
Andrey Filippov committed
8852

Andrey Filippov's avatar
Andrey Filippov committed
8853 8854 8855
//   | sum(Wi*(P0xi*Cxi + P0yi*Cxyi + P0zi*Cxzi)) |
//B= | sum(Wi*(P0yi*Cyi + P0xi*Cyxi + P0zi*Cyzi)) |
//   | sum(Wi*(P0zi*Czi + P0yi*Czyi + P0xi*Czxi)) |
Andrey Filippov's avatar
Andrey Filippov committed
8856
/*
Andrey Filippov's avatar
Andrey Filippov committed
8857 8858 8859 8860 8861 8862 8863 8864 8865 8866 8867 8868 8869 8870 8871 8872 8873 8874 8875 8876 8877 8878 8879 8880 8881 8882 8883 8884 8885 8886 8887 8888 8889 8890 8891 8892 8893 8894 8895 8896 8897 8898 8899 8900 8901 8902 8903 8904 8905 8906 8907 8908 8909 8910 8911 8912 8913 8914 8915 8916 8917 8918 8919 8920 8921 8922 8923 8924 8925 8926 8927 8928 8929 8930 8931 8932 8933 8934 8935 8936
	X*(Vxi^2-1) + Y*(Vxi*Vyi) + Z*(Vxi*Vzi) = P0xi*(Vxi^2-1) +P0yi*(Vxi*Vyi) + P0zi*(Vxi*Vzi)
	X*(Vxi*Vyi) + Y*(Vyi^2-1) + Z*(Vyi*Vzi) = P0xi*(Vxi*Vyi) +P0yi*(Vyi^2-1) + P0zi*(Vyi*Vzi)
	X*(Vxi*Vzi) + Y*(Vxi*Vyi) + Z*(Vzi^2-1) = P0xi*(Vxi*Vzi) +P0yi*(Vxi*Vyi) + P0zi*(Vzi^2-1)

	X*Cx  + Y*Cxy + Z*Cxz = P0xi*Cx  +P0yi*Cxy + P0zi*Cxz
	X*Cxy + Y*Cy  + Z*Cyz = P0xi*Cxy +P0yi*Cy  + P0zi*Cyz
	X*Cxz + Y*Cyz + Z*Cz  = P0xi*Cxz +P0yi*Cyz + P0zi*Cz
	P0zi==0.0, so - now we'll use P0zi - difference from this station to average

	X*Cx  + Y*Cxy + Z*Cxz = P0xi*Cx  +P0yi*Cxy
	X*Cxy + Y*Cy  + Z*Cyz = P0xi*Cxy +P0yi*Cy
	X*Cxz + Y*Cyz + Z*Cz  = P0xi*Cxz +P0yi*Cyz

*/
						Cx=V2[0]-1.0;
						Cy=V2[1]-1.0;
						Cz=V2[2]-1.0;
						Cxy= V[0]*V[1];
						Cxz= V[0]*V[2];
						Cyz= V[1]*V[2];
						if (thisDebug) System.out.println(" Cx="+IJ.d2s(Cx,6)+" Cy="+IJ.d2s(Cy,6)+" Cz="+IJ.d2s(Cz,6)+
								" Cxy="+IJ.d2s(Cxy,6)+" Cxz="+IJ.d2s(Cxz,6)+" Cyz="+IJ.d2s(Cyz,6));


						double W=gridCorr2d[imgNum][3][index];
						double Px=gridCorr2d[imgNum][0][index];
						double Py=gridCorr2d[imgNum][1][index];
						double Pz=gridCorr2d[imgNum][2][index];
						alpha+=W;
						alphaStation[station]+=W;
						if (thisDebug) System.out.println(imgNum+": Px="+IJ.d2s(Px,6)+" Py="+IJ.d2s(Py,6)+" W="+IJ.d2s(W,6));
						if (zIndex>0){ // X,Y correction is enabled, not only Z
							aM[0][0]+=W*Cx;
							aM[0][1]+=W*Cxy;
							aM[1][1]+=W*Cy;
							aM[0][2+zGroup]+=W*Cxz;
							aM[1][2+zGroup]+=W*Cyz;
							aB[0][0]+=W*(Px*Cx  + Py*Cxy + Pz*Cxz);
							aB[1][0]+=W*(Px*Cxy + Py*Cy  + Pz*Cyz);
						}
						aM[zIndex+zGroup][zIndex+zGroup]+=W*(Cz-variationPenalty); // -1>>Cz<0
						aB[zIndex+zGroup][0]+=W*(Px*Cxz + Py*Cyz + Pz*Cz);
					}
				}
				if (zIndex>0){// X,Y correction is enabled, not only Z
					aM[1][0]+=aM[0][1]; // why "+=" - just "="
					for (int zGroup=0;zGroup<numberOfZGroups;zGroup++){
						aM[zIndex+zGroup][0]+=aM[0][zIndex+zGroup];
						aM[zIndex+zGroup][1]+=aM[1][zIndex+zGroup];
					}
				}
				Matrix M=new Matrix(aM);
				Matrix B=new Matrix(aB);
				if (thisDebug) {
					System.out.println(" M:");
					M.print(8, 6);
					System.out.println(" B:");
					B.print(8, 6);
				}

				//			boolean fallBack2D=true;
				if ((new LUDecomposition(M)).isNonsingular()){
					double [] dXYZ=M.solve(B).getRowPackedCopy();
//// Now save per station group (with weights)
					if (zIndex>0){// X,Y correction is enabled, not only Z
						for (int i=0;i<2;i++) gridCorr3d[i][index]=dXYZ[i];
					}
					double zAverage=0.0;
					double sumW=0;
					for (int station=0;station<numStations;station++){
						double w=alphaStation[station];
						sumW+=w;
						gridZCorr3dWeight[station][index]=w;
						int zGroup=stationGroups[station];
						zAverage+=w*dXYZ[zIndex+zGroup];
					}
					if (sumW>0.0) {
						zAverage/=sumW;
						gridCorr3d[2][index]=zAverage; // weighted average of grid Z correction (from current pattern Z)
						gridCorr3d[3][index]=alpha; // same as sumW?
Andrey Filippov's avatar
Andrey Filippov committed
8937
// second pass - calculate per-station Z corrections - referenced to existent current values
Andrey Filippov's avatar
Andrey Filippov committed
8938 8939 8940 8941 8942 8943 8944 8945
//zPerStation[station]
						for (int station=0;station<numStations;station++){
							int zGroup=stationGroups[station];
//							gridZCorr3d[station][index]=dXYZ[zIndex+zGroup]-zPerStation[station]; // differential from the current pattern geometry
							gridZCorr3d[station][index]=dXYZ[zIndex+zGroup]-zAverage; // differential from the current pattern geometry
						}
					}
					fallBack2D=false; //TODO:  make sure delta Z (Math.abs(gridCorr3d[2][index])) is not too big!!
Andrey Filippov's avatar
Andrey Filippov committed
8946

Andrey Filippov's avatar
Andrey Filippov committed
8947 8948 8949 8950 8951 8952 8953 8954 8955 8956 8957 8958 8959 8960 8961 8962 8963 8964 8965 8966 8967 8968 8969 8970 8971 8972 8973
					if (Math.abs(gridCorr3d[2][index])>maxZCorr) {
						fallBack2D=true; // temporary limit
					}
					if (thisDebug) System.out.println(" dX="+IJ.d2s(gridCorr3d[0][index],6)+" dY="+IJ.d2s(gridCorr3d[1][index],6)+" dZ="+IJ.d2s(gridCorr3d[2][index],6));
				}
			}
			if(fallBack2D && !(grid3DCorrection && noFallBack)) { // make a 2d averaging of weighted dx, dy correction - separately for each station group
				double [] gridZcorrPerGroup=      new double [numberOfZGroups];
				double [] gridZcorrAddPerGroup=      new double [numberOfZGroups];
				double [] gridZcorrWeightPerGroup=new double [numberOfZGroups];
				for (int i=0;i<numberOfZGroups;i++){
					gridZcorrPerGroup[i]=0.0;
					gridZcorrWeightPerGroup[i]=0.0;
					gridZcorrAddPerGroup[i]=0.0;
				}
				for (int imgNum=0;imgNum<selectedImages.length;imgNum++) {
					int station=fittingStrategy.distortionCalibrationData.gIP[imgNum].getStationNumber(); // number of sub-camera
					int zGroup=stationGroups[station];
					if ((gridCorr2d[imgNum]!=null)  && (gridCorr2d[imgNum][3][index]>0.0) && (zGroup>=0)) {
						double w=gridCorr2d[imgNum][3][index];
						double z=gridCorr2d[imgNum][2][index]; // difference from average Z
						gridZcorrPerGroup[zGroup]+=w*z;
						gridZcorrWeightPerGroup[zGroup]+=w;
					}
				}
				for (int i=0;i<numberOfZGroups;i++) if (gridZcorrWeightPerGroup[i]>0.0) gridZcorrPerGroup[i]/=gridZcorrWeightPerGroup[i];
				for (int i=0;i<gridCorr3d.length;i++) gridCorr3d[i][index]=0.0;
Andrey Filippov's avatar
Andrey Filippov committed
8974

Andrey Filippov's avatar
Andrey Filippov committed
8975 8976 8977 8978 8979 8980 8981 8982 8983 8984 8985 8986 8987 8988 8989 8990 8991 8992 8993 8994 8995
				double s=0;
				for (int imgNum=0;imgNum<selectedImages.length;imgNum++) {
					int station=fittingStrategy.distortionCalibrationData.gIP[imgNum].getStationNumber(); // number of sub-camera
					int zGroup=stationGroups[station];
					if ((gridCorr2d[imgNum]!=null)  && (gridCorr2d[imgNum][3][index]>0.0) && (zGroup>=0)) {
						double z=patternParameters.gridGeometry[v][u][2]+gridZcorrPerGroup[zGroup];
						double [] cv={
								patternParameters.gridGeometry[v][u][0]-cameraXYZ[imgNum][0],
								patternParameters.gridGeometry[v][u][1]-cameraXYZ[imgNum][1],
								z-cameraXYZ[imgNum][2]};
						double cv2=cv[0]*cv[0]+cv[1]*cv[1]+cv[2]*cv[2];
						double acv=Math.sqrt(cv2);
						for (int i=0;i<3;i++)cv[i]/=acv; // make unity vector;
						// intersection of the corrected view ray with the average taget plane
						double [] dXYplane0={-gridZcorrPerGroup[zGroup]/cv[2]*cv[0],-gridZcorrPerGroup[zGroup]/cv[2]*cv[1]};
						double [] modCorrXY={gridCorr2d[imgNum][0][index]+dXYplane0[0], gridCorr2d[imgNum][1][index]+dXYplane0[1]};
						double kv=(modCorrXY[0]*cv[0]+modCorrXY[1]*cv[1])/cv2;
						double w=gridCorr2d[imgNum][3][index];
						gridCorr3d[0][index]+=w*(gridCorr2d[imgNum][0][index]-cv[0]*kv);
						gridCorr3d[1][index]+=w*(gridCorr2d[imgNum][1][index]-cv[1]*kv);
						gridZcorrAddPerGroup[zGroup]+=w*(                            -cv[2]*kv);
Andrey Filippov's avatar
Andrey Filippov committed
8996
// not finished per station/per group 2d correction, will just use corerction average
Andrey Filippov's avatar
Andrey Filippov committed
8997 8998 8999 9000 9001 9002 9003 9004 9005 9006 9007 9008 9009 9010 9011 9012 9013 9014 9015 9016 9017 9018 9019 9020 9021 9022 9023 9024 9025 9026 9027 9028 9029 9030 9031 9032 9033 9034 9035 9036 9037
						gridCorr3d[2][index]+=w*(                            -cv[2]*kv);
						s+=w;
					}
				}
				for (int i=0;i<numberOfZGroups;i++) if (gridZcorrWeightPerGroup[i]>0.0) gridZcorrAddPerGroup[i]/=gridZcorrWeightPerGroup[i];
				for (int station=0;station<numStations;station++){
					int zGroup=stationGroups[station];
					gridZCorr3d[station][index]=gridZcorrAddPerGroup[zGroup]; // differential from the current pattern geometry
				}
				if (s>0){
					gridCorr3d[0][index]/=s;
					gridCorr3d[1][index]/=s;
					gridCorr3d[2][index]/=s;
				} else {
					gridCorr3d[0][index]=0.0;
					gridCorr3d[1][index]=0.0;
					gridCorr3d[2][index]=0.0;
				}
				gridCorr3d[3][index]=s;
				if (thisDebug) System.out.println(" Using 2d averaging: dX="+IJ.d2s(gridCorr3d[0][index],6)+
						" dY="+IJ.d2s(gridCorr3d[1][index],6)+" dZ="+IJ.d2s(gridCorr3d[2][index],6));
			}
		}
		// Make average correction zero is it needed?
		// create "reliable" mask for averaging/tilting - disregard the outmost grid pixels
		boolean [] reliable=new boolean [width*height];
		double wThreshold=0.0;
		for (int v=0;v<height;v++) for (int u=0;u<width;u++){
			int index=u+v*width;
			reliable[index]=false;
			if ((v>0) && (u>0) && (v<(height-1)) && (u<(width-1)) &&
					(gridCorr3d[3][index]>wThreshold) &&
					(gridCorr3d[3][index-1]>wThreshold) &&
					(gridCorr3d[3][index+1]>wThreshold) &&
					(gridCorr3d[3][index-width]>wThreshold) &&
					(gridCorr3d[3][index+width]>wThreshold) ){
				reliable[index]=true;
			}

		}
		double corrAverage;
Andrey Filippov's avatar
Andrey Filippov committed
9038
		for (int c=0;c<3;c++){
Andrey Filippov's avatar
Andrey Filippov committed
9039 9040 9041 9042 9043 9044 9045 9046 9047 9048 9049 9050 9051 9052 9053 9054 9055 9056 9057 9058 9059 9060 9061 9062 9063 9064 9065 9066 9067 9068 9069 9070 9071 9072 9073 9074 9075 9076 9077 9078 9079 9080 9081 9082 9083 9084 9085 9086 9087 9088 9089 9090 9091
			corrAverage=0.0;
			double s=0.0;
			for (int i=0;i<gridCorr3d[0].length;i++) if (reliable[i]) {
				corrAverage+=gridCorr3d[c][i]*gridCorr3d[3][i];
				s+=gridCorr3d[3][i];
			}
			corrAverage/=s;
			//			System.out.println("zCorrAverage["+c+"="+corrAverage);
			for (int i=0;i<gridCorr3d[c].length;i++) gridCorr3d[c][i]-=corrAverage;
		}
		// for Z correction compensate for x/y tilts
		String [] titles={"X-correction(mm)","Y-correction(mm)","Z-correction","Weight"};
		if (rotateCorrection) {
			double SX=0.0,SX2=0.0,SZ=0.0,SXY=0.0,SXZ=0.0,S0=0.0,SY=0.0,SY2=0.0,SYZ=0.0;
			double [][] gridGeom=new double [3][gridCorr3d[0].length];
			for (int c=0;c<gridGeom.length;c++) for (int i=0;i<gridGeom[c].length;i++)gridGeom[c][i]=0.0;

			for (int v=0;v<height;v++) for (int u=0;u<width; u++){
				int index=u+v*width;
				double W=gridCorr3d[3][index];
				gridGeom[0][index]=patternParameters.gridGeometry[v][u][0];
				gridGeom[1][index]=patternParameters.gridGeometry[v][u][1];
				gridGeom[2][index]=W;
				if ((reliable[index]) && (W>0.0)){
					S0+=W;
					SX+=  W*patternParameters.gridGeometry[v][u][0];
					SX2+= W*patternParameters.gridGeometry[v][u][0]*patternParameters.gridGeometry[v][u][0];
					SY+=  W*patternParameters.gridGeometry[v][u][1];
					SY2+= W*patternParameters.gridGeometry[v][u][1]*patternParameters.gridGeometry[v][u][1];
					SXY+= W*patternParameters.gridGeometry[v][u][0]*patternParameters.gridGeometry[v][u][1];
					SZ+=  W*gridCorr3d[2][index];
					SXZ+= W*gridCorr3d[2][index]*patternParameters.gridGeometry[v][u][0];
					SYZ+= W*gridCorr3d[2][index]*patternParameters.gridGeometry[v][u][1];
				}
			}
			double [][] aM1= {
					{SX2, SXY, SX},
					{SXY, SY2, SY},
					{SX,  SY,  S0}};
			double [][] aB1= {{SXZ},{SYZ},{SZ}};
			Matrix M=new Matrix(aM1);
			Matrix B=new Matrix(aB1);
			if (this.debugLevel>2) {
				System.out.println(" M:");
				M.print(8, 6);
				System.out.println(" B:");
				B.print(8, 6);
				System.out.println(" Ax,Ay,B:");
				M.solve(B).print(8, 6);
			}
			double [] tilts=M.solve(B).getRowPackedCopy(); // singular ???
			if (this.debugLevel>2) {
				if (this.refineParameters.showThisCorrection) {
9092
					ShowDoubleFloatArrays.showArrays(gridCorr3d, getGridWidth(), getGridHeight(),  true, "before tilt:", titles);
Andrey Filippov's avatar
Andrey Filippov committed
9093 9094 9095 9096 9097 9098 9099 9100 9101 9102 9103 9104
				}
			}
			for (int v=0;v<height;v++) for (int u=0;u<width; u++){
				int index=u+v*width;
				gridCorr3d[2][index]-=tilts[0]*patternParameters.gridGeometry[v][u][0]+tilts[1]*patternParameters.gridGeometry[v][u][1]+tilts[2];
			}
		}
    	if (this.debugLevel>2) {
    		if (this.refineParameters.showThisCorrection) {
    			double [][] gridCorr3dClone=new double [4][width*height];
    			for (int c=0;c<gridCorr3dClone.length;c++) for (int i=0;i<gridCorr3dClone[c].length;i++)
    				gridCorr3dClone[c][i]=reliable[i]? gridCorr3d[c][i]:0.0;
9105
    			ShowDoubleFloatArrays.showArrays(gridCorr3dClone, getGridWidth(), getGridHeight(),  true, "after tilt:", titles);
Andrey Filippov's avatar
Andrey Filippov committed
9106 9107 9108
    		}
    	}
    	IJ.showStatus("");
Andrey Filippov's avatar
Andrey Filippov committed
9109 9110 9111

// combine in a single array?

Andrey Filippov's avatar
Andrey Filippov committed
9112 9113 9114 9115 9116 9117 9118 9119 9120 9121 9122 9123 9124 9125
    	double [][][] result={gridCorr3d,gridZCorr3d,gridZCorr3dWeight};
		return  result;
	}
	public double [][][] calculateGridXYZCorr2D(
			final int width,
			final int height,
			final int [] stationGroups,
			final boolean [] selectedImages,
			final double [][] cameraXYZ,
			final LensDistortionParameters lensDistortionParametersProto,
			final boolean showIndividual,
			final int threadsMax,
			final boolean updateStatus
			){
9126 9127
//		final boolean isTripod=this.fittingStrategy.distortionCalibrationData.eyesisCameraParameters.is_tripod;
//		final boolean cartesian=this.fittingStrategy.distortionCalibrationData.eyesisCameraParameters.cartesian;
Andrey Filippov's avatar
Andrey Filippov committed
9128 9129 9130 9131 9132 9133 9134 9135 9136 9137 9138 9139 9140 9141 9142 9143 9144 9145 9146 9147 9148 9149 9150 9151 9152 9153 9154 9155 9156 9157 9158 9159 9160 9161 9162 9163 9164
		final int [][] dirs=            {{0,0},{-1,0},{1,0},{0,-1},{0,1}}; // possible to make 8 directions
		final double [][][] derivatives={ // for of /du, /dv 3 variants, depending on which neighbors are available
				{
					{ 0.0,-0.5, 0.5, 0.0, 0.0},
					{ 1.0,-1.0, 0.0, 0.0, 0.0},
					{-1.0, 0.0, 1.0, 0.0, 0.0}
				},
				{
					{ 0.0, 0.0, 0.0,-0.5, 0.5},
					{ 1.0, 0.0, 0.0,-1.0, 0.0},
					{-1.0, 0.0, 0.0, 0.0, 1.0}}};
		final double [][][] gridCorr2d=new double [selectedImages.length][][]; // per-image grid {dx,dy,weight} corrections
		for (int i=0;i<gridCorr2d.length;i++) {
			gridCorr2d[i]=null;
			cameraXYZ[i]=null;
		}
		// Should it be just once - common for all images? (removed from the "for" loop)
		final double [] diff=calcYminusFx(this.currentfX);
		final int debugLevel=this.debugLevel;
		final int [] imageStartIndex=this.imageStartIndex;
		final double [] Y=this.Y;
		final double [] weightFunction= this.weightFunction;
   		final Thread[] threads = newThreadArray(threadsMax);
   		final AtomicInteger imageNumberAtomic = new AtomicInteger(0);
   		final AtomicInteger imageFinishedAtomic = new AtomicInteger(0);
   		final double [] progressValues=new double [selectedImages.length];
   		int numSelectedImages=0;
   		for (int i=0;i<selectedImages.length;i++) if (selectedImages[i]) numSelectedImages++;
   		int selectedIndex=0;
   		for (int i=0;i<selectedImages.length;i++) {
   			progressValues[i]=(selectedIndex+1.0)/numSelectedImages;
   			if (selectedImages[i]) selectedIndex++;
   			if (selectedIndex>=numSelectedImages) selectedIndex--;
   		}
		IJ.showStatus("Calculating pattern geometry correction...");
		for (int ithread = 0; ithread < threads.length; ithread++) {
			threads[ithread] = new Thread() {
Andrey Filippov's avatar
Andrey Filippov committed
9165
				@Override
Andrey Filippov's avatar
Andrey Filippov committed
9166 9167 9168 9169 9170 9171 9172 9173 9174 9175 9176 9177
				public void run() {
					LensDistortionParameters lensDistortionParameters=lensDistortionParametersProto.clone(); // see - if that is needed - maybe new is OK
					//   					LensDistortionParameters lensDistortionParameters= new LensDistortionParameters();
					for (int imgNum=imageNumberAtomic.getAndIncrement(); imgNum<selectedImages.length; imgNum=imageNumberAtomic.getAndIncrement()) if (selectedImages[imgNum]){
						//		for (int imgNum=0;imgNum<selectedImages.length;imgNum++) if (selectedImages[imgNum]) {
						int station=fittingStrategy.distortionCalibrationData.gIP[imgNum].getStationNumber(); // number of sub-camera
						if (stationGroups[station]<0) continue; // do not process images that do not belong to selected stations
						gridCorr2d[imgNum]=new double [4][width*height]; // dx, dy only - added zCorr per station
						for (int n=0;n<gridCorr2d[imgNum].length;n++) for (int i=0;i<gridCorr2d[imgNum][0].length;i++) gridCorr2d[imgNum][n][i]=0.0;
						//		int chnNum=fittingStrategy.distortionCalibrationData.gIP[imgNum].channel; // number of sub-camera
						cameraXYZ[imgNum]=new double[3];
						// The following method sets this.lensDistortionParameters and invokes this.lensDistortionParameters.recalcCommons();
Andrey Filippov's avatar
Andrey Filippov committed
9178
						lensDistortionParameters.lensCalcInterParamers(
Andrey Filippov's avatar
Andrey Filippov committed
9179
								lensDistortionParameters,
9180 9181 9182 9183
								fittingStrategy.distortionCalibrationData.isTripod(),
								fittingStrategy.distortionCalibrationData.isCartesian(),
					    		fittingStrategy.distortionCalibrationData.getPixelSize(imgNum),
					    		fittingStrategy.distortionCalibrationData.getDistortionRadius(imgNum),
Andrey Filippov's avatar
Andrey Filippov committed
9184 9185 9186 9187 9188 9189 9190 9191 9192 9193 9194 9195 9196 9197 9198 9199 9200 9201 9202 9203 9204 9205 9206 9207 9208 9209 9210 9211 9212 9213 9214 9215 9216 9217 9218 9219 9220 9221 9222 9223 9224 9225 9226 9227 9228 9229 9230 9231 9232 9233 9234 9235 9236 9237 9238 9239 9240 9241 9242 9243 9244 9245 9246 9247 9248 9249 9250 9251 9252 9253 9254 9255 9256 9257 9258 9259 9260 9261 9262 9263 9264
								null, //this.interParameterDerivatives, // [22][]
								fittingStrategy.distortionCalibrationData.getParameters(imgNum), // 22-long parameter vector for the image
								null); // if no derivatives, null is OK
						//				false); // calculate this.interParameterDerivatives -derivatives array (false - just this.values)
						cameraXYZ[imgNum]=lensDistortionParameters.getLensCenterCoordinates();
						if (debugLevel>2) {
							System.out.println("calculateGridXYZCorr(): imgNum="+imgNum+" lens coordinates (mm)={"+
									IJ.d2s(cameraXYZ[imgNum][0],3)+", "+IJ.d2s(cameraXYZ[imgNum][1],3)+", "+IJ.d2s(cameraXYZ[imgNum][2],3)+"}");
						}
						//		double [] diff=calcYminusFx(this.currentfX); // removed from the loop
						// find data range for the selected image
						int index=imageStartIndex[imgNum]; // set when fitting series is init
						double [][] imgData=new double[showIndividual?7:5][getGridHeight() * width]; // dPX, dPY, Px, Py, alpha
						for (int i=0;i<imgData.length;i++) for (int j=0;j<imgData[i].length;j++)imgData[i][j]=0.0;
						// first pass - prepare [v][u]arrays
						for (int i=0;i<fittingStrategy.distortionCalibrationData.gIP[imgNum].pixelsUV.length;i++){
							int u=fittingStrategy.distortionCalibrationData.gIP[imgNum].pixelsUV[i][0]+patternParameters.U0;
							int v=fittingStrategy.distortionCalibrationData.gIP[imgNum].pixelsUV[i][1]+patternParameters.V0;
							int vu=u+width*v;
							imgData[0][vu]= diff[2*(index+i)]; // out of bound 1410
							imgData[1][vu]= diff[2*(index+i)+1];
							imgData[2][vu]= Y[2*(index+i)];  // measured pixel x
							imgData[3][vu]= Y[2*(index+i)+1];// measured pixel y

							//				imgData[4][vu]= fittingStrategy.distortionCalibrationData.getMask(chnNum, imgData[2][vu], imgData[3][vu]);

							if (weightFunction!=null) {
								imgData[4][vu]= weightFunction[2*(index+i)];
							} else {
								imgData[4][vu]= 1.0;
							}
						}
						// second pass - calculate derivatives, and residuals in mm
						for (int i=0;i<fittingStrategy.distortionCalibrationData.gIP[imgNum].pixelsUV.length;i++){
							int u=fittingStrategy.distortionCalibrationData.gIP[imgNum].pixelsUV[i][0]+patternParameters.U0;
							int v=fittingStrategy.distortionCalibrationData.gIP[imgNum].pixelsUV[i][1]+patternParameters.V0;
							int vu=u+width*v;
							gridCorr2d[imgNum][0][vu]=0.0;
							gridCorr2d[imgNum][1][vu]=0.0;
							gridCorr2d[imgNum][2][vu]=patternParameters.getZCorr(vu,station); // per-station Z correction from average
							gridCorr2d[imgNum][3][vu]=0.0; // weight
							double [][] gXY =new double[dirs.length][3];
							//			double [][] gpXY=new double[dirs.length][2];
							double [][] gpXY=new double[dirs.length][3];
							boolean [] dirMask=new boolean [dirs.length];
							for (int dir=0;dir<dirs.length;dir++){
								int u1=u+dirs[dir][0];
								int v1=v+dirs[dir][1];
								int vu1=u1+width*v1;
								dirMask[dir] = (u1>=0) && (v1>=0) && (u1<width) && (v1<height) && (imgData[4][vu1]>0);
								if (dirMask[dir]){
									gXY[dir][0]= patternParameters.gridGeometry[v1][u1][0];
									gXY[dir][1]= patternParameters.gridGeometry[v1][u1][1];
									gXY[dir][2]= patternParameters.gridGeometry[v1][u1][2]; // Here - average Z
									gpXY[dir][0]=imgData[2][vu1];
									gpXY[dir][1]=imgData[3][vu1];
								} else {
									gXY[dir][0]= 0.0;
									gXY[dir][1]= 0.0;
									gXY[dir][2]= 0.0;
									gpXY[dir][0]=0.0;
									gpXY[dir][1]=0.0;

								}
							}
							int [] variants={-1,-1}; // {horizontal, vertical}
							boolean variantsExist=true;
							for (int duv=0;duv<2;duv++){ // 0 - horizontal, 1 - vertical
								for (int variant=0;variant<derivatives[duv].length;variant++) { // variants: 0 half of right/left, 1 left deriv, 2 - right deriv
									boolean fit=true;
									for (int dir=0;dir<dirs.length;dir++) if ((derivatives[duv][variant][dir]!=0) && !dirMask[dir]){
										fit=false;
										break;
									}
									if (fit) {
										variants[duv]=variant;
										break;
									}
								}
								if (variants[duv]<0) { // could not find any variant to calculate derivatives for this direction
									variantsExist=false;
Andrey Filippov's avatar
Andrey Filippov committed
9265
									break;
Andrey Filippov's avatar
Andrey Filippov committed
9266 9267 9268 9269 9270 9271 9272 9273 9274 9275 9276 9277 9278 9279 9280 9281 9282 9283 9284 9285 9286 9287 9288 9289 9290 9291
								}
							}
							if (!variantsExist){
								imgData[4][vu]=0.0;
								continue;
							}
							double [][] dXY_dUV= new double [2][2];
							double [][] dpXY_dUV=new double [2][2];
							for (int nom=0;nom<2;nom++) { // 0-x, 1 - y
								for (int denom=0;denom<2;denom++) { //0 - du, 1 - dv
									dXY_dUV [nom][denom]=0.0;
									dpXY_dUV[nom][denom]=0.0;
									for (int dir=0;dir<dirs.length;dir++){
										dXY_dUV [nom][denom]+=gXY [dir][nom]*derivatives[denom][variants[denom]][dir];
										dpXY_dUV[nom][denom]+=gpXY[dir][nom]*derivatives[denom][variants[denom]][dir];
									}
								}
							}
							double [] dpXY={imgData[0][vu],imgData[1][vu]};
							Matrix MdpXY=    new Matrix(dpXY,2); // 2 rows
							Matrix MdXY_dUV= new Matrix(dXY_dUV);
							Matrix MdpXY_dUV=new Matrix(dpXY_dUV);
							if ((new LUDecomposition(MdpXY_dUV)).isNonsingular()){
								/*
								 * MdpXY= MdpXY_dUV* MdUV
								 * MdXY=  MdXY_dUV * MdUV
Andrey Filippov's avatar
Andrey Filippov committed
9292
								 * MdUV=  MdpXY_dUV.solve(MdpXY);
Andrey Filippov's avatar
Andrey Filippov committed
9293 9294 9295 9296 9297 9298 9299 9300 9301 9302 9303
								 * MdXY=  MdXY_dUV * MdpXY_dUV.solve(MdpXY);
								 */
								Matrix MdXY=MdXY_dUV.times(MdpXY_dUV.solve(MdpXY));
								double [] dXY=MdXY.getRowPackedCopy();
								gridCorr2d[imgNum][0][vu]=dXY[0];
								gridCorr2d[imgNum][1][vu]=dXY[1];
								gridCorr2d[imgNum][3][vu]=imgData[4][vu]; // weight
							}
						} // end scanning pixels
						if (showIndividual) {
							String [] titles={"diff-X","diff-Y","pX","pY","alpha","X-correction(mm)","Y-correction(mm)","Z-correction(mm)"};
9304
							ShowDoubleFloatArrays.showArrays(imgData, width, height,  true, "Grid"+imgNum, titles);
Andrey Filippov's avatar
Andrey Filippov committed
9305 9306 9307 9308
						}
   						final int numFinished=imageFinishedAtomic.getAndIncrement();
//						IJ.showProgress(progressValues[numFinished]);
						SwingUtilities.invokeLater(new Runnable() {
Andrey Filippov's avatar
Andrey Filippov committed
9309
							@Override
Andrey Filippov's avatar
Andrey Filippov committed
9310 9311 9312 9313 9314 9315 9316 9317 9318 9319 9320 9321 9322 9323 9324 9325 9326 9327
							public void run() {
								// Here, we can safely update the GUI
								// because we'll be called from the
								// event dispatch thread
								IJ.showProgress(progressValues[numFinished]);
							}
						});
					}
				}
			};
		}
		startAndJoin(threads);

		IJ.showProgress(1.0);
		return gridCorr2d;
	}


Andrey Filippov's avatar
Andrey Filippov committed
9328 9329 9330



Andrey Filippov's avatar
Andrey Filippov committed
9331 9332 9333
	/**
	 * Calculates corrections to X and Y coordinates of the grid nodes
	 * //@param distortionCalibrationData - used to receive sensor mask(s)
Andrey Filippov's avatar
Andrey Filippov committed
9334
	 * @param grid3DCorrection - if true - calculate 3d correction, false - slow 3d (2d perpendicular to view)
Andrey Filippov's avatar
Andrey Filippov committed
9335 9336 9337 9338 9339 9340 9341 9342 9343 9344 9345 9346 9347 9348 9349 9350 9351 9352 9353 9354 9355 9356 9357 9358 9359 9360
	 * @param maxZCorr - maximal allowed correction in Z-direction (if wants more, will fall back to 2-d correction (perpendicular to the view)
	 * @param showIndividual - show individual images
	 * @return first index - 0 - correction x (mm), 1 - correction y(mm), 2 - correction z(mm)  3 - weight (number of images used)
	 */

	public double [][] calculateGridXYZCorr3D( // old version
//			DistortionCalibrationData distortionCalibrationData,
			boolean grid3DCorrection,
			boolean rotateCorrection,
			double maxZCorr,
			boolean showIndividual){
		int width=getGridWidth();
		int height=getGridHeight();
		int [][] dirs=            {{0,0},{-1,0},{1,0},{0,-1},{0,1}}; // possible to make 8 directions
		double [][][] derivatives={ // for of /du, /dv 3 variants, depending on which neighbors are available
				{
					{ 0.0,-0.5, 0.5, 0.0, 0.0},
					{ 1.0,-1.0, 0.0, 0.0, 0.0},
					{-1.0, 0.0, 1.0, 0.0, 0.0}
				},
				{
					{ 0.0, 0.0, 0.0,-0.5, 0.5},
					{ 1.0, 0.0, 0.0,-1.0, 0.0},
					{-1.0, 0.0, 0.0, 0.0, 1.0}}};
		boolean [] selectedImages=fittingStrategy.selectedImages();
		double [][][] gridCorr2d=new double [selectedImages.length][][]; // per-image grid {dx,dy,weight} corrections
Andrey Filippov's avatar
Andrey Filippov committed
9361

Andrey Filippov's avatar
Andrey Filippov committed
9362 9363 9364 9365 9366 9367 9368 9369 9370 9371 9372 9373 9374 9375 9376
		double [][] cameraXYZ=new double [selectedImages.length][];
		for (int i=0;i<gridCorr2d.length;i++) {
			gridCorr2d[i]=null;
			cameraXYZ[i]=null;
		}
		int numSelected=0;
		for (int imgNum=0;imgNum<selectedImages.length;imgNum++) if (selectedImages[imgNum]) numSelected++;
		int numProcessed=0;
		IJ.showStatus("Calculating pattern geometry correction...");
		for (int imgNum=0;imgNum<selectedImages.length;imgNum++) if (selectedImages[imgNum]) {
			gridCorr2d[imgNum]=new double [3][width*height]; // dx, dy only
			for (int n=0;n<gridCorr2d[imgNum].length;n++) for (int i=0;i<gridCorr2d[imgNum][0].length;i++) gridCorr2d[imgNum][n][i]=0.0;
//			int chnNum=fittingStrategy.distortionCalibrationData.gIP[imgNum].channel; // number of sub-camera
			cameraXYZ[imgNum]=new double[3];
			// The following method sets this.lensDistortionParameters and invokes this.lensDistortionParameters.recalcCommons();
Andrey Filippov's avatar
Andrey Filippov committed
9377
			this.lensDistortionParameters.lensCalcInterParamers(
Andrey Filippov's avatar
Andrey Filippov committed
9378
					this.lensDistortionParameters,
9379 9380 9381 9382
					fittingStrategy.distortionCalibrationData.isTripod(),
					fittingStrategy.distortionCalibrationData.isCartesian(),
		    		fittingStrategy.distortionCalibrationData.getPixelSize(imgNum),
		    		fittingStrategy.distortionCalibrationData.getDistortionRadius(imgNum),
Andrey Filippov's avatar
Andrey Filippov committed
9383 9384 9385 9386 9387 9388 9389 9390 9391 9392 9393 9394 9395 9396 9397 9398
					null, //this.interParameterDerivatives, // [22][]
//					fittingStrategy.distortionCalibrationData.pars[imgNum], // 22-long parameter vector for the image
					fittingStrategy.distortionCalibrationData.getParameters(imgNum), // 22-long parameter vector for the image
					null); // if no derivatives, null is OK
//					false); // calculate this.interParameterDerivatives -derivatives array (false - just this.values)
			cameraXYZ[imgNum]=lensDistortionParameters.getLensCenterCoordinates();
			if (this.debugLevel>2) {
				System.out.println("calculateGridXYZCorr(): imgNum="+imgNum+" lens coordinates (mm)={"+
						IJ.d2s(cameraXYZ[imgNum][0],3)+", "+IJ.d2s(cameraXYZ[imgNum][1],3)+", "+IJ.d2s(cameraXYZ[imgNum][2],3)+"}");
			}
			double [] diff=calcYminusFx(this.currentfX);
			// find data range for the selected image
			int index=this.imageStartIndex[imgNum]; // set when fitting series is init
/*
			int index=0;
			int numImg=fittingStrategy.distortionCalibrationData.getNumImages();
Andrey Filippov's avatar
Andrey Filippov committed
9399

Andrey Filippov's avatar
Andrey Filippov committed
9400 9401 9402 9403 9404 9405 9406 9407 9408 9409 9410 9411 9412 9413 9414 9415 9416 9417 9418 9419 9420 9421 9422 9423 9424 9425 9426 9427 9428 9429 9430 9431 9432 9433 9434 9435 9436 9437 9438 9439 9440 9441 9442 9443 9444 9445 9446 9447 9448 9449 9450 9451 9452 9453 9454 9455 9456 9457 9458 9459 9460 9461 9462 9463 9464 9465 9466
			for (int iNum=0;(iNum<imgNum) && (iNum<numImg) ;iNum++) if (selectedImages[iNum]) //
				index+=fittingStrategy.distortionCalibrationData.gIP[iNum].pixelsUV.length;
			//System.out.println ("+++++++++++++imgNum="+imgNum+" index="+index);
*/
			if (this.debugLevel>2) {
				System.out.println("calculateGridXYZCorr(): fX.length="+this.currentfX.length+" this image index="+index);
			}
			double [][] imgData=new double[showIndividual?7:5][getGridHeight() * width]; // dPX, dPY, Px, Py, alpha
			for (int i=0;i<imgData.length;i++) for (int j=0;j<imgData[i].length;j++)imgData[i][j]=0.0;
			// first pass - prepare [v][u]arrays
			for (int i=0;i<fittingStrategy.distortionCalibrationData.gIP[imgNum].pixelsUV.length;i++){
				int u=fittingStrategy.distortionCalibrationData.gIP[imgNum].pixelsUV[i][0]+patternParameters.U0;
				int v=fittingStrategy.distortionCalibrationData.gIP[imgNum].pixelsUV[i][1]+patternParameters.V0;
				int vu=u+width*v;
				imgData[0][vu]=   diff[2*(index+i)]; // out of bound 1410
				imgData[1][vu]=   diff[2*(index+i)+1];
				imgData[2][vu]= this.Y[2*(index+i)];  // measured pixel x
				imgData[3][vu]= this.Y[2*(index+i)+1];// measured pixel y

				//				imgData[4][vu]= fittingStrategy.distortionCalibrationData.getMask(chnNum, imgData[2][vu], imgData[3][vu]);

				if (this.weightFunction!=null) {
					imgData[4][vu]= this.weightFunction[2*(index+i)];
				} else {
					imgData[4][vu]= 1.0;
				}
				//				if (imgNum==1) System.out.println ("---index="+index+" i="+i+" vu="+vu+ " v="+v+" u="+u+" x="+IJ.d2s(this.Y[2*(index+i)],1)+" y="+IJ.d2s(this.Y[2*(index+i)+1],1));
			}
			// second pass - calculate derivatives, and residuals in mm
			for (int i=0;i<fittingStrategy.distortionCalibrationData.gIP[imgNum].pixelsUV.length;i++){
				int u=fittingStrategy.distortionCalibrationData.gIP[imgNum].pixelsUV[i][0]+patternParameters.U0;
				int v=fittingStrategy.distortionCalibrationData.gIP[imgNum].pixelsUV[i][1]+patternParameters.V0;
				int vu=u+width*v;
				gridCorr2d[imgNum][0][vu]=0.0;
				gridCorr2d[imgNum][1][vu]=0.0;
				gridCorr2d[imgNum][2][vu]=0.0; // weight

				double [][] gXY =new double[dirs.length][3];
				double [][] gpXY=new double[dirs.length][2];
				boolean [] dirMask=new boolean [dirs.length];
				for (int dir=0;dir<dirs.length;dir++){
					int u1=u+dirs[dir][0];
					int v1=v+dirs[dir][1];
					int vu1=u1+width*v1;
					dirMask[dir] = (u1>=0) && (v1>=0) && (u1<width) && (v1<height) && (imgData[4][vu1]>0);
					gXY[dir][0]= dirMask[dir]?patternParameters.gridGeometry[v1][u1][0]:0.0;
					gXY[dir][1]= dirMask[dir]?patternParameters.gridGeometry[v1][u1][1]:0.0;
					gXY[dir][2]= dirMask[dir]?patternParameters.gridGeometry[v1][u1][2]:0.0; // Add per-station (optionally)
					gpXY[dir][0]=dirMask[dir]?imgData[2][vu1]:0.0;
					gpXY[dir][1]=dirMask[dir]?imgData[3][vu1]:0.0;
				}
				int [] variants={-1,-1}; // {horizontal, vertical}
				boolean variantsExist=true;
				for (int duv=0;duv<2;duv++){ // 0 - horizontal, 1 - vertical
					for (int variant=0;variant<derivatives[duv].length;variant++) { // variants: 0 half of right/left, 1 left deriv, 2 - right deriv
						boolean fit=true;
						for (int dir=0;dir<dirs.length;dir++) if ((derivatives[duv][variant][dir]!=0) && !dirMask[dir]){
							fit=false;
							break;
						}
						if (fit) {
							variants[duv]=variant;
							break;
						}
					}
					if (variants[duv]<0) { // could not find any variant to calculate derivatives for this direction
						variantsExist=false;
Andrey Filippov's avatar
Andrey Filippov committed
9467
						break;
Andrey Filippov's avatar
Andrey Filippov committed
9468 9469 9470 9471 9472 9473 9474 9475 9476 9477 9478 9479 9480 9481 9482 9483 9484
					}
				}
				if (!variantsExist){
					imgData[4][vu]=0.0;
					continue;
				}
				double [][] dXY_dUV= new double [2][2];
				double [][] dpXY_dUV=new double [2][2];
				for (int nom=0;nom<2;nom++) { // 0-x, 1 - y
					for (int denom=0;denom<2;denom++) { //0 - du, 1 - dv
						dXY_dUV [nom][denom]=0.0;
						dpXY_dUV[nom][denom]=0.0;
						for (int dir=0;dir<dirs.length;dir++){
							dXY_dUV [nom][denom]+=gXY [dir][nom]*derivatives[denom][variants[denom]][dir];
							dpXY_dUV[nom][denom]+=gpXY[dir][nom]*derivatives[denom][variants[denom]][dir];
						}
					}
Andrey Filippov's avatar
Andrey Filippov committed
9485

Andrey Filippov's avatar
Andrey Filippov committed
9486 9487 9488 9489 9490 9491 9492 9493 9494
				}
				double [] dpXY={imgData[0][vu],imgData[1][vu]};
				Matrix MdpXY=    new Matrix(dpXY,2); // 2 rows
				Matrix MdXY_dUV= new Matrix(dXY_dUV);
				Matrix MdpXY_dUV=new Matrix(dpXY_dUV);
				if ((new LUDecomposition(MdpXY_dUV)).isNonsingular()){
					/*
					 * MdpXY= MdpXY_dUV* MdUV
					 * MdXY=  MdXY_dUV * MdUV
Andrey Filippov's avatar
Andrey Filippov committed
9495
					 * MdUV=  MdpXY_dUV.solve(MdpXY);
Andrey Filippov's avatar
Andrey Filippov committed
9496 9497 9498 9499 9500 9501 9502 9503 9504 9505 9506
					 * MdXY=  MdXY_dUV * MdpXY_dUV.solve(MdpXY);
					 */
					Matrix MdXY=MdXY_dUV.times(MdpXY_dUV.solve(MdpXY));
					double [] dXY=MdXY.getRowPackedCopy();
					gridCorr2d[imgNum][0][vu]=dXY[0];
					gridCorr2d[imgNum][1][vu]=dXY[1];
					gridCorr2d[imgNum][2][vu]=imgData[4][vu]; // weight
				}
			} // end scanning pixels
			if (showIndividual) {
		        String [] titles={"diff-X","diff-Y","pX","pY","alpha","X-correction(mm)","Y-correction(mm)","Z-correction(mm)"};
9507
				ShowDoubleFloatArrays.showArrays(imgData, width, height,  true, "Grid"+imgNum, titles);
Andrey Filippov's avatar
Andrey Filippov committed
9508 9509 9510 9511 9512 9513 9514 9515 9516 9517 9518 9519 9520 9521 9522 9523 9524 9525 9526 9527 9528 9529 9530 9531 9532 9533 9534 9535 9536 9537 9538 9539 9540 9541 9542
			}
			IJ.showProgress(++numProcessed,numSelected);
		}
		IJ.showProgress(1.0);
		IJ.showStatus("Calculating pattern 3d correction...");
// now using gridCorr2d[imgNum], cameraXYZ[imgNum] and patternParameters.gridGeometry[v][u] find the 3d correction     public double [][][] gridGeometry=null; // [v][u]{x,y,z,"alpha"} alpha=0 - no ghrid, 1 - grid
		double [][] gridCorr3d=new double [4][width*height];
		for (int n=0;n<gridCorr3d.length;n++) for (int i=0;i<gridCorr3d[0].length;i++) gridCorr3d[n][i]=0.0;
		double Cx,Cy,Cz,Cxy,Cxz,Cyz;
		double [] V= new double[3];
		double [] V2= new double[3];
		int debugIndex=(height/2)*width+ (width/2);
		int debugIndex1=(height/2)*width+ (width/4);
		for (int v=0;v<height;v++) for (int u=0;u<width; u++){
			int index=u+v*width;
			boolean thisDebug=(this.debugLevel>1) && ((index==debugIndex) || (index==debugIndex1));
			if (thisDebug) System.out.println("calculateGridXYZCorr3D() debug("+this.debugLevel+"): index="+index+" v="+v+" u="+u);
			double [][] aM={{0.0,0.0,0.0},{0.0,0.0,0.0},{0.0,0.0,0.0}};
			double [][] aB ={{0.0},{0.0},{0.0}};
			double alpha=0.0;
			boolean fallBack2D=true;
			if (grid3DCorrection) {
				for (int imgNum=0;imgNum<selectedImages.length;imgNum++)
					if ((gridCorr2d[imgNum]!=null)  && (gridCorr2d[imgNum][2][index]>0.0)) {
						// calculate unity vector from the camera lens to the grid point
						double absV=0.0;
						for (int i=0;i<V.length;i++){
							V[i]=patternParameters.gridGeometry[v][u][i]-cameraXYZ[imgNum][i];
							absV+=V[i]*V[i];
						}
						absV=Math.sqrt(absV);
						if (absV>0) for (int i=0;i<V.length;i++) V[i]/=absV;
						for (int i=0;i<V.length;i++) V2[i]=V[i]*V[i];
						if (thisDebug) System.out.println(" imgNum="+imgNum+" V[0]="+IJ.d2s(V[0],4)+" V[1]="+IJ.d2s(V[1],4)+" V[2]="+IJ.d2s(V[2],4)+
								" V2[0]="+IJ.d2s(V2[0],4)+" V2[1]="+IJ.d2s(V2[1],4)+" V2[2]="+IJ.d2s(V2[2],4));
Andrey Filippov's avatar
Andrey Filippov committed
9543 9544
						// When performin 3-d correction (X,Y,Z) the result point has to have minimal weighted sum of squared distances to all rays
// when summing for different stations, multiply W by sign(image belongs to station)
Andrey Filippov's avatar
Andrey Filippov committed
9545 9546 9547 9548 9549 9550 9551 9552 9553 9554 9555 9556 9557 9558 9559 9560 9561
/*
Px, Py - calculated correction for individual image
V={Vx,Vy,Vz} unity vector from the camera lens center to the {Px,Py,0}
A - vector from the {Px,Py,0} to {X,Y,Z} = {X-Px,Y-Py,Z}
Projection of A on V will have length of A(.)V, Vector B=V*(A(.)V)
Vector D=A-B = A - V*(A(.)V)
D2=D(.)D= A(.)A - 2* (A(.)V ) * (A(.)V ) + (A(.)V ) * (A(.)V ) = A(.)A -  (A(.)V ) * (A(.)V )
D2=A(.)A -  (A(.)V )^2

A(.)A=(X-Px)^2 + (Y-Py)^2 + Z^2 =X^2 -2*X*Px +Px^2 +Y^2 -2*Y*Py +Py^2 +Z^2
A(.)A=X^2 -2*X*Px +Px^2 +Y^2 -2*Y*Py +Py^2 +Z^2
A(.)V=      (X-Px)*Vx + (Y-Py)*Vy + Z*Vz
(A(.)V)^2= ((X-Px)*Vx + (Y-Py)*Vy + Z*Vz)^2 = ((X-Px)*Vx)^2 + ((Y-Py)*Vy)^2 + (Z*Vz)^2 + 2*((X-Px)*Vx)*((Y-Py)*Vy)+ 2*((X-Px)*Vx)*(Z*Vz)+2*((Y-Py)*Vy)*(Z*Vz)
(A(.)V)^2= X^2*Vx^2 +Px^2*Vx^2 - 2*X*Px*Vx^2 +Y^2*Vy^2+Py^2*Vy^2-2*Y*Py*Vy^2 +Z^2*Vz^2 +2*X*Y*Vx*Vy +2*Px*Py*Vx*Vy - 2*X*Py*Vx*Vy - 2*Y*Px*Vx*Vy +2*X*Z*Vx*Vz - 2*Z*Px*Vx*Vz +2*Y*Z*Vy*Vz -2*z*Py*Vy*Vz

D2=
  +X^2 - X^2*Vx^2
Andrey Filippov's avatar
Andrey Filippov committed
9562
  +Y^2 - Y^2*Vy^2
Andrey Filippov's avatar
Andrey Filippov committed
9563 9564 9565 9566 9567 9568 9569 9570 9571 9572 9573 9574 9575 9576 9577 9578 9579 9580
  +Z^2 - Z^2*Vz^2
-2*X*Y* Vx*Vy
-2*X*Z* Vx*Vz
-2*Y*Z* Vy*Vz
-2*X*Px +2*X*Px*Vx^2+ 2*X*Py*Vx*Vy
-2*Y*Py +2*Y*Py*Vy^2+ 2*Y*Px*Vx*Vy
+2*Z*Px*Vx*Vz   +2*Z*Py*Vy*Vz
+Px^2  +Py^2 -Px^2*Vx^2   -Py^2*Vy^2    -2*Px*Py*Vx*Vy

0= dD2/dX/2= X*(1-Vx^2) - Y* Vx*Vy - Z* Vx*Vz -Px + Px*Vx^2  + Py*Vx*Vy
0= dD2/dY/2= Y*(1-Vy^2) - X* Vx*Vy - Z* Vy*Vz -Py + Py*Vy^2  + Px*Vx*Vy
0= dD2/dZ/2= Z*(1-Vz^2) - X* Vx*Vz - Y* Vy*Vz     + Px*Vx*Vz + Py*Vy*Vz


 X*(Vx^2-1) + Y* (Vx*Vy)  + Z* (Vx*Vz)   =  Px * (Vx^2-1)  + Py* (Vx*Vy)
 X*(Vx*Vy)  + Y* (Vy^2-1) + Z* (Vy*Vz)   =  Px * (Vx*Vy)   + Py * (Vy^2-1)
 X*(Vx*Vz)  + Y* (Vy*Vz)  + Z* (Vz^2-1)  =  Px * (Vx*Vz)   + Py* (Vy*Vz)

Andrey Filippov's avatar
Andrey Filippov committed
9581

Andrey Filippov's avatar
Andrey Filippov committed
9582
 */
Andrey Filippov's avatar
Andrey Filippov committed
9583

Andrey Filippov's avatar
Andrey Filippov committed
9584 9585 9586
//   | sum(Wi*Cxi),  sum(Wi*Cxyi), sum(Wi*Cxzi) |
//M= | sum(Wi*Cxyi), sum(Wi*Cyi ), sum(Wi*Cyzi) |
//   | sum(Wi*Cxzi), sum(Wi*Cyzi), sum(Wi*Czi ) |
Andrey Filippov's avatar
Andrey Filippov committed
9587

Andrey Filippov's avatar
Andrey Filippov committed
9588 9589 9590
//   | sum(Wi*(P0xi*Cxi + P0yi*Cxyi + P0zi*Cxzi)) |
//B= | sum(Wi*(P0yi*Cyi + P0xi*Cyxi + P0zi*Cyzi)) |
//   | sum(Wi*(P0zi*Czi + P0yi*Czyi + P0xi*Czxi)) |
Andrey Filippov's avatar
Andrey Filippov committed
9591
/*
Andrey Filippov's avatar
Andrey Filippov committed
9592 9593 9594 9595 9596 9597 9598 9599 9600 9601 9602 9603 9604 9605 9606 9607 9608 9609 9610 9611 9612 9613 9614 9615 9616 9617 9618 9619 9620 9621 9622 9623 9624 9625 9626 9627 9628 9629
	X*(Vxi^2-1) + Y*(Vxi*Vyi) + Z*(Vxi*Vzi) = P0xi*(Vxi^2-1) +P0yi*(Vxi*Vyi) + P0zi*(Vxi*Vzi)
	X*(Vxi*Vyi) + Y*(Vyi^2-1) + Z*(Vyi*Vzi) = P0xi*(Vxi*Vyi) +P0yi*(Vyi^2-1) + P0zi*(Vyi*Vzi)
	X*(Vxi*Vzi) + Y*(Vxi*Vyi) + Z*(Vzi^2-1) = P0xi*(Vxi*Vzi) +P0yi*(Vxi*Vyi) + P0zi*(Vzi^2-1)

	X*Cx  + Y*Cxy + Z*Cxz = P0xi*Cx  +P0yi*Cxy + P0zi*Cxz
	X*Cxy + Y*Cy  + Z*Cyz = P0xi*Cxy +P0yi*Cy  + P0zi*Cyz
	X*Cxz + Y*Cyz + Z*Cz  = P0xi*Cxz +P0yi*Cyz + P0zi*Cz
	P0zi==0.0, so - now we'll use P0zi - difference from this station to average

	X*Cx  + Y*Cxy + Z*Cxz = P0xi*Cx  +P0yi*Cxy
	X*Cxy + Y*Cy  + Z*Cyz = P0xi*Cxy +P0yi*Cy
	X*Cxz + Y*Cyz + Z*Cz  = P0xi*Cxz +P0yi*Cyz

*/
						Cx=V2[0]-1.0;
						Cy=V2[1]-1.0;
						Cz=V2[2]-1.0;
						Cxy= V[0]*V[1];
						Cxz= V[0]*V[2];
						Cyz= V[1]*V[2];
						if (thisDebug) System.out.println(" Cx="+IJ.d2s(Cx,6)+" Cy="+IJ.d2s(Cy,6)+" Cz="+IJ.d2s(Cz,6)+
								" Cxy="+IJ.d2s(Cxy,6)+" Cxz="+IJ.d2s(Cxz,6)+" Cyz="+IJ.d2s(Cyz,6));


						double W=gridCorr2d[imgNum][2][index];
						double Px=gridCorr2d[imgNum][0][index];
						double Py=gridCorr2d[imgNum][1][index];
						alpha+=W;
						if (thisDebug) System.out.println(imgNum+": Px="+IJ.d2s(Px,6)+" Py="+IJ.d2s(Py,6)+" W="+IJ.d2s(W,6));
						aM[0][0]+=W*Cx;
						aM[0][1]+=W*Cxy;
						aM[0][2]+=W*Cxz;
						aM[1][1]+=W*Cy;
						aM[1][2]+=W*Cyz;
						aM[2][2]+=W*Cz;
						aB[0][0]+=W*(Px*Cx  + Py*Cxy);// Pz==0.0
						aB[1][0]+=W*(Px*Cxy + Py*Cy);// Pz==0.0
						aB[2][0]+=W*(Px*Cxz + Py*Cyz);// Pz==0.0
Andrey Filippov's avatar
Andrey Filippov committed
9630
					}
Andrey Filippov's avatar
Andrey Filippov committed
9631 9632 9633 9634 9635 9636 9637 9638 9639 9640 9641 9642 9643 9644 9645 9646 9647 9648 9649 9650 9651 9652 9653 9654 9655 9656 9657 9658 9659 9660 9661 9662 9663 9664 9665 9666 9667 9668 9669 9670 9671 9672 9673 9674 9675 9676 9677 9678 9679 9680 9681 9682 9683 9684 9685 9686 9687 9688 9689 9690 9691 9692 9693 9694 9695 9696 9697 9698 9699 9700 9701 9702
				aM[1][0]+=aM[0][1];
				aM[2][0]+=aM[0][2];
				aM[2][1]+=aM[1][2];
				Matrix M=new Matrix(aM);
				Matrix B=new Matrix(aB);
				if (thisDebug) {
					System.out.println(" M:");
					M.print(8, 6);
					System.out.println(" B:");
					B.print(8, 6);
				}

				//			boolean fallBack2D=true;
				if ((new LUDecomposition(M)).isNonsingular()){
					double [] dXYZ=M.solve(B).getRowPackedCopy();
					for (int i=0;i<3;i++) gridCorr3d[i][index]=dXYZ[i];
					gridCorr3d[3][index]=alpha;
					fallBack2D=false; //TODO:  make sure delta Z (Math.abs(gridCorr3d[2][index])) is not too big!!
					if (Math.abs(gridCorr3d[2][index])>maxZCorr) {

						fallBack2D=true; // temporary limit
					}
					if (thisDebug) System.out.println(" dX="+IJ.d2s(gridCorr3d[0][index],6)+" dY="+IJ.d2s(gridCorr3d[1][index],6)+" dZ="+IJ.d2s(gridCorr3d[2][index],6));
				}
			}
			if(fallBack2D) { // make a 2d averaging of weighted dx, dy correction
				for (int i=0;i<gridCorr3d.length;i++) gridCorr3d[i][index]=0.0;
				double s=0;
				for (int imgNum=0;imgNum<selectedImages.length;imgNum++) if ((gridCorr2d[imgNum]!=null) &&(gridCorr2d[imgNum][2][index]>0.0)) {
					double W=gridCorr2d[imgNum][2][index];
					//			V[i]=patternParameters.gridGeometry[v][u][i]-cameraXYZ[imgNum][i];

					double [] cv={
							patternParameters.gridGeometry[v][u][0]-cameraXYZ[imgNum][0],
							patternParameters.gridGeometry[v][u][1]-cameraXYZ[imgNum][1],
							patternParameters.gridGeometry[v][u][2]-cameraXYZ[imgNum][2]};
					double cv2=cv[0]*cv[0]+cv[1]*cv[1]+cv[2]*cv[2];
					double kv=(gridCorr2d[imgNum][0][index]*cv[0]+gridCorr2d[imgNum][1][index]*cv[1])/cv2;
					gridCorr3d[0][index]+=W*(gridCorr2d[imgNum][0][index]-cv[0]*kv);
					gridCorr3d[1][index]+=W*(gridCorr2d[imgNum][1][index]-cv[1]*kv);
					gridCorr3d[2][index]+=W*(                            -cv[2]*kv);
					s+=W;
				}
				if (s>0){
					gridCorr3d[0][index]/=s;
					gridCorr3d[1][index]/=s;
					gridCorr3d[2][index]/=s;
				} else {
					gridCorr3d[0][index]=0.0;
					gridCorr3d[1][index]=0.0;
					gridCorr3d[2][index]=0.0;
				}
				gridCorr3d[3][index]=s;
				if (thisDebug) System.out.println(" Using 2d averaging: dX="+IJ.d2s(gridCorr3d[0][index],6)+
						" dY="+IJ.d2s(gridCorr3d[1][index],6)+" dZ="+IJ.d2s(gridCorr3d[2][index],6));
			}
		}
		// Make average correction zero is it needed?
		// create "reliable" mask for averaging/tilting - disregard the outmost grid pixels
		boolean [] reliable=new boolean [width*height];
		double wThreshold=0.0;
		for (int v=0;v<height;v++) for (int u=0;u<width;u++){
			int index=u+v*width;
			reliable[index]=false;
			if ((v>0) && (u>0) && (v<(height-1)) && (u<(width-1)) &&
					(gridCorr3d[3][index]>wThreshold) &&
					(gridCorr3d[3][index-1]>wThreshold) &&
					(gridCorr3d[3][index+1]>wThreshold) &&
					(gridCorr3d[3][index-width]>wThreshold) &&
					(gridCorr3d[3][index+width]>wThreshold) ){
				reliable[index]=true;
			}
Andrey Filippov's avatar
Andrey Filippov committed
9703

Andrey Filippov's avatar
Andrey Filippov committed
9704 9705
		}
		double corrAverage;
Andrey Filippov's avatar
Andrey Filippov committed
9706
		for (int c=0;c<3;c++){
Andrey Filippov's avatar
Andrey Filippov committed
9707 9708 9709 9710 9711 9712 9713 9714 9715 9716 9717 9718 9719 9720 9721 9722 9723 9724 9725 9726 9727 9728 9729 9730 9731 9732 9733 9734 9735 9736 9737 9738 9739 9740 9741 9742 9743 9744 9745 9746 9747 9748 9749 9750 9751 9752 9753 9754 9755 9756 9757 9758 9759
			corrAverage=0.0;
			double s=0.0;
			for (int i=0;i<gridCorr3d[0].length;i++) if (reliable[i]) {
				corrAverage+=gridCorr3d[c][i]*gridCorr3d[3][i];
				s+=gridCorr3d[3][i];
			}
			corrAverage/=s;
//			System.out.println("zCorrAverage["+c+"="+corrAverage);
			for (int i=0;i<gridCorr3d[c].length;i++) gridCorr3d[c][i]-=corrAverage;
		}
// for Z correction compensate for x/y tilts
		String [] titles={"X-correction(mm)","Y-correction(mm)","Z-correction","Weight"};
		if (rotateCorrection) {
			double SX=0.0,SX2=0.0,SZ=0.0,SXY=0.0,SXZ=0.0,S0=0.0,SY=0.0,SY2=0.0,SYZ=0.0;
			double [][] gridGeom=new double [3][gridCorr3d[0].length];
			for (int c=0;c<gridGeom.length;c++) for (int i=0;i<gridGeom[c].length;i++)gridGeom[c][i]=0.0;

			for (int v=0;v<height;v++) for (int u=0;u<width; u++){
				int index=u+v*width;
				double W=gridCorr3d[3][index];
				gridGeom[0][index]=patternParameters.gridGeometry[v][u][0];
				gridGeom[1][index]=patternParameters.gridGeometry[v][u][1];
				gridGeom[2][index]=W;
				if ((reliable[index]) && (W>0.0)){
					S0+=W;
					SX+=  W*patternParameters.gridGeometry[v][u][0];
					SX2+= W*patternParameters.gridGeometry[v][u][0]*patternParameters.gridGeometry[v][u][0];
					SY+=  W*patternParameters.gridGeometry[v][u][1];
					SY2+= W*patternParameters.gridGeometry[v][u][1]*patternParameters.gridGeometry[v][u][1];
					SXY+= W*patternParameters.gridGeometry[v][u][0]*patternParameters.gridGeometry[v][u][1];
					SZ+=  W*gridCorr3d[2][index];
					SXZ+= W*gridCorr3d[2][index]*patternParameters.gridGeometry[v][u][0];
					SYZ+= W*gridCorr3d[2][index]*patternParameters.gridGeometry[v][u][1];
				}
			}
			double [][] aM= {
					{SX2, SXY, SX},
					{SXY, SY2, SY},
					{SX,  SY,  S0}};
			double [][] aB= {{SXZ},{SYZ},{SZ}};
			Matrix M=new Matrix(aM);
			Matrix B=new Matrix(aB);
			if (this.debugLevel>2) {
				System.out.println(" M:");
				M.print(8, 6);
				System.out.println(" B:");
				B.print(8, 6);
				System.out.println(" Ax,Ay,B:");
				M.solve(B).print(8, 6);
			}
			double [] tilts=M.solve(B).getRowPackedCopy();
			if (this.debugLevel>2) {
				if (this.refineParameters.showThisCorrection) {
9760
					ShowDoubleFloatArrays.showArrays(gridCorr3d, getGridWidth(), getGridHeight(),  true, "before tilt:", titles);
Andrey Filippov's avatar
Andrey Filippov committed
9761 9762 9763 9764 9765 9766 9767 9768 9769 9770 9771 9772
				}
			}
			for (int v=0;v<height;v++) for (int u=0;u<width; u++){
				int index=u+v*width;
				gridCorr3d[2][index]-=tilts[0]*patternParameters.gridGeometry[v][u][0]+tilts[1]*patternParameters.gridGeometry[v][u][1]+tilts[2];
			}
		}
    	if (this.debugLevel>2) {
    		if (this.refineParameters.showThisCorrection) {
    			double [][] gridCorr3dClone=new double [4][width*height];
    			for (int c=0;c<gridCorr3dClone.length;c++) for (int i=0;i<gridCorr3dClone[c].length;i++)
    				gridCorr3dClone[c][i]=reliable[i]? gridCorr3d[c][i]:0.0;
9773
    			ShowDoubleFloatArrays.showArrays(gridCorr3dClone, getGridWidth(), getGridHeight(),  true, "after tilt:", titles);
Andrey Filippov's avatar
Andrey Filippov committed
9774 9775 9776 9777 9778 9779
    		}
    	}
    	IJ.showStatus("");
		return  gridCorr3d;
	}
/**
Andrey Filippov's avatar
Andrey Filippov committed
9780
 *
Andrey Filippov's avatar
Andrey Filippov committed
9781 9782 9783 9784 9785
 * @param gridCorr3D Array of grid corrections (1-st index: dx, dy, dz, mask (>0 - valid point)
 * @param gridZCorr Optional per-station z-correction (or null)
 * @param width // width of the grid array
 * @param preShrink // shrink input array by this number of pixels (hor/vert) befere extrapolating (remove bad border nodes)
 * @param expand    // expand/extrapolate this number of steps after shrinking (or until no pixels left
Andrey Filippov's avatar
Andrey Filippov committed
9786
 * @param sigma     // effective radius for fitting the extrapolation plane, in nodes
Andrey Filippov's avatar
Andrey Filippov committed
9787 9788 9789 9790 9791 9792 9793 9794 9795 9796 9797 9798 9799 9800 9801 9802 9803 9804 9805 9806 9807 9808 9809 9810 9811 9812 9813 9814 9815 9816 9817
 * @param ksigma    // size if square to consider (measured in ksigma-s). 2.0 means square is 4*sigma by 4*sigma
 * @return true if OK, false if error
 */
	public boolean shrinkExtrapolateGridCorrection(
			double [][] gridCorr3D, // dx,dy,dz, mask >0
			double [][] gridZCorr, // per-station additional Z-correction (or null)
			int width,
			int preShrink,
			int expand,
			double sigma,
			double ksigma){
		int length=gridCorr3D[0].length;
        int height=	length/width;
//		int decimate=fittingStrategy.distortionCalibrationData.eyesisCameraParameters.decimateMasks;
//		int sWidth= (fittingStrategy.distortionCalibrationData.eyesisCameraParameters.sensorWidth-1)/decimate+1;
//		int sHeight=(fittingStrategy.distortionCalibrationData.eyesisCameraParameters.sensorHeight-1)/decimate+1;
//		double sigma=nsigma/decimate;
		boolean [] fMask=new boolean[length];
		for (int i=0;i<fMask.length;i++)
			fMask[i]=gridCorr3D[3][i]>0;
		int len= (int) Math.ceil(sigma*ksigma);
		double [] gaussian=new double[len+1];
		double k=0.5/sigma/sigma;
		for (int i=0;i<=len;i++) gaussian[i]=Math.exp(-i*i*k);
		int [][] dirs={{-1,0},{1,0},{0,-1},{0,1}};
		List <Integer> extList=new ArrayList<Integer>(1000);
		Integer Index,Index2;
		extList.clear();
		// create initial wave
		int debugThreshold=2;
		if (this.debugLevel>debugThreshold) System.out.println("shrinkExtrapolateGridCorrection width="+width+" height="+height);
Andrey Filippov's avatar
Andrey Filippov committed
9818

Andrey Filippov's avatar
Andrey Filippov committed
9819 9820 9821 9822 9823 9824 9825 9826 9827 9828 9829 9830 9831 9832 9833 9834
		for (int iy=0;iy<height;iy++) for (int ix=0;ix<width;ix++) {
			Index=iy*width+ix;
			if (fMask[Index]) {
				int numNew=0;
				for (int dir=0;dir<dirs.length;dir++){
					int ix1=ix+dirs[dir][0];
					int iy1=iy+dirs[dir][1];
					// Will not shrink from the array border!
					if ((ix1>=0) && (iy1>=0) && (ix1<width) && (iy1<height)) {
						if (!fMask[iy1*width+ix1]) numNew++;
					}
					if (numNew>0) extList.add(Index); // neighbor will have non-singular matrix
				}
			}
		}
		if (this.debugLevel>debugThreshold) System.out.println("Initial wave length="+extList.size());
Andrey Filippov's avatar
Andrey Filippov committed
9835
		// now shrink
Andrey Filippov's avatar
Andrey Filippov committed
9836 9837 9838 9839 9840 9841 9842 9843 9844 9845 9846 9847 9848 9849 9850 9851
		// unmask current wave
		for (int i=extList.size()-1; i>=0;i--) fMask[extList.get(i)]=false;
		if (extList.size()==0) return false; // no points
		for (int nShrink=0;nShrink<preShrink;nShrink++){
			int size=extList.size();
			if (this.debugLevel>debugThreshold) System.out.println("shrinking, size="+size);
			if (size==0) return false; // no points
			// wave step, unmasking
			for (int i=0; i<size;i++) {
				Index=extList.get(0);
				extList.remove(0);
				int iy=Index/width;
				int ix=Index%width;
				for (int dir=0;dir<dirs.length;dir++){
					int ix1=ix+dirs[dir][0];
					int iy1=iy+dirs[dir][1];
Andrey Filippov's avatar
Andrey Filippov committed
9852
					if ((ix1>=0) && (iy1>=0) && (ix1<width) && (iy1<height)){
Andrey Filippov's avatar
Andrey Filippov committed
9853 9854 9855 9856 9857 9858 9859 9860 9861 9862 9863
						Index=iy1*width+ix1;
						if (fMask[Index]){
							extList.add(Index);
							fMask[Index]=false; // restore later?
						}
					}
				}
			}
		}
		// restore mask on the front
		for (int i=extList.size()-1; i>=0;i--) fMask[extList.get(i)]=true;
Andrey Filippov's avatar
Andrey Filippov committed
9864

Andrey Filippov's avatar
Andrey Filippov committed
9865 9866 9867 9868 9869 9870
		   // repeat with the wave until there is place to move, but not more than "expand" steps
		   int [] dirs2=new int [2];
		   for (int n=0; (n<expand) && (extList.size()>0); n++ ){
			   if (this.updateStatus) IJ.showStatus("Expanding, step="+(n+1)+" (of "+expand+"), extList.size()="+extList.size());
//			   if (this.updateStatus) showStatus("Expanding, step="+(n+1)+" (of "+expand+"), extList.size()="+extList.size(),0);
			   if (this.debugLevel>debugThreshold) System.out.println("Expanding, step="+n+", extList.size()="+extList.size());
Andrey Filippov's avatar
Andrey Filippov committed
9871
			   // move wave front 1 pixel hor/vert
Andrey Filippov's avatar
Andrey Filippov committed
9872 9873 9874 9875 9876 9877 9878 9879
			   for (int i=extList.size();i>0;i--){ // repeat current size times
				   Index=extList.get(0);
				   extList.remove(0);
				   int iy=Index/width;
				   int ix=Index%width;
				   for (int dir=0;dir<dirs.length;dir++){
					   int ix1=ix+dirs[dir][0];
					   int iy1=iy+dirs[dir][1];
Andrey Filippov's avatar
Andrey Filippov committed
9880
					   if ((ix1>=0) && (iy1>=0) && (ix1<width) && (iy1<height)){
Andrey Filippov's avatar
Andrey Filippov committed
9881 9882 9883 9884 9885 9886 9887 9888
						   Index=iy1*width+ix1;
						   if (!fMask[Index]){
							   // verify it has neighbors in the perpendicular direction to dir
							   dirs2[0]=(dir+2) & 3;
							   dirs2[1]=dirs2[0] ^ 1;
							   for (int dir2=0;dir2<dirs2.length;dir2++){
								   int ix2=ix+dirs[dirs2[dir2]][0]; // from the old, not the new point!
								   int iy2=iy+dirs[dirs2[dir2]][1];
Andrey Filippov's avatar
Andrey Filippov committed
9889
								   if ((ix2>=0) && (iy2>=0) && (ix2<width) && (iy2<height)){
Andrey Filippov's avatar
Andrey Filippov committed
9890 9891 9892 9893 9894 9895 9896 9897 9898 9899 9900 9901 9902 9903 9904 9905 9906 9907 9908 9909 9910 9911
									   Index2=iy2*width+ix2;
									   if (fMask[Index2]){ // has orthogonal neighbor, OK to add
										   extList.add(Index);
										   fMask[Index]=true; // remove later
										   break;
									   }
								   }
							   }
						   }
					   }
				   }
			   }
			   // now un-mask the pixels in new list new
			   for (int i =0;i<extList.size();i++){
				   Index=extList.get(i);
				   fMask[Index]=false; // now mask is only set for known pixels
			   }
	// Calculate values (extrapolate) for the pixels in the list
			/*
Err = sum (W(x,y)*(f(x,y)-F0-Ax*(x-X0)-Ay*(y-Y0))^2)=
sum (Wxy*(Fxy^2+F0^2+Ax^2*(x-X0)^2+Ay^2*(y-Y0)^2
-2*Fxy*F0 -2*Fxy*Ax*(x-X0) - 2*Fxy*Ay*(y-Y0)
Andrey Filippov's avatar
Andrey Filippov committed
9912
+2*F0*Ax*(x-X0) + 2*F0*Ay*(y-Y0)
Andrey Filippov's avatar
Andrey Filippov committed
9913 9914 9915 9916 9917 9918 9919 9920 9921 9922 9923 9924 9925 9926 9927 9928 9929 9930 9931 9932 9933 9934 9935 9936 9937 9938 9939 9940 9941 9942 9943 9944 9945
+2*Ax*(x-X0)*Ay*(y-Y0))
(1)0=dErr/dF0= 2*sum (Wxy*(F0-Fxy+Ax*(x-X0)+Ay(y-Y0)))
(2)0=dErr/dAx= 2*sum (Wxy*(Ax*(x-X0)^2-Fxy*(x-X0) +F0*(x-X0)+Ay*(x-x0)*(y-Y0)))
(3)0=dErr/dAy= 2*sum (Wxy*(Ay*(y-y0)^2-Fxy*(y-Y0) +F0*(y-Y0)+Ax*(x-x0)*(y-Y0)))

S0 = sum(Wxy)
SF=  sum(Wxy*Fxy)
SX=  sum(Wxy*(x-X0)
SY=  sum(Wxy*(y-Y0)
SFX= sum(Wxy*Fxy*(x-X0)
SFY= sum(Wxy*Fxy*(y-Y0)
SX2= sum(Wxy*(x-X0)^2
SY2= sum(Wxy*(y-Y0)^2
SXY= sum(Wxy*(x-X0)*(y-Y0)

(1) F0*S0 - SF + Ax*SX +Ay*Sy = 0
(2) Ax*SX2-SFX+F0*SX+Ay*SXY = 0
(3) Ay*Sy2 -SFY + F0*SY +Ax*SXY = 0

(1) F0*S0  + Ax*SX +Ay*SY = SF
(2) Ax*SX2+F0*SX+Ay*SXY = SFX
(3) Ay*Sy2  + F0*SY +Ax*SXY = SFY


   | F0 |
V= | Ax |
   | Ay |

     | SF  |
B =  | SFX |
     | SFY |

     | S0  SX   SY  |
Andrey Filippov's avatar
Andrey Filippov committed
9946
M =  | SX  SX2  SXY |
Andrey Filippov's avatar
Andrey Filippov committed
9947 9948 9949 9950 9951 9952 9953 9954 9955 9956 9957 9958 9959 9960 9961 9962 9963 9964 9965 9966 9967 9968 9969 9970 9971 9972 9973 9974 9975 9976 9977 9978 9979 9980 9981 9982 9983 9984 9985 9986 9987 9988
     | SY  SXY  SY2 |

M * V = B
			 */
			   int numOriginalComponents=3;
			   boolean useExtra=gridZCorr!=null;
			for (int i =0;i<extList.size();i++){
        		Index=extList.get(i);
        		int iy=Index/width;
        		int ix=Index%width;
        		double [] S0=new double [3+(useExtra?gridZCorr.length:0)];
        		for (int ii=0;ii<S0.length;ii++) S0[ii]=0.0;
//        		double [] S0= {0.0,0.0,0.0};
        		double [] SF= S0.clone();
        		double [] SX= S0.clone();
        		double [] SY= S0.clone();
        		double [] SFX=S0.clone();
        		double [] SFY=S0.clone();
        		double [] SX2=S0.clone();
        		double [] SY2=S0.clone();
        		double [] SXY=S0.clone();
        		int iYmin=iy-len; if (iYmin<0) iYmin=0;
        		int iYmax=iy+len; if (iYmax>=height) iYmax=height-1;
        		int iXmin=ix-len; if (iXmin<0) iXmin=0;
        		int iXmax=ix+len; if (iXmax>=width) iXmax=width-1;
        		for (int iy1=iYmin;iy1<=iYmax;iy1++) for (int ix1=iXmin;ix1<=iXmax;ix1++) {
        			int ind=ix1+iy1*width;
        			if (fMask[ind]){
        				double w=gaussian[(iy1>=iy)?(iy1-iy):(iy-iy1)]*gaussian[(ix1>=ix)?(ix1-ix):(ix-ix1)];
        				for (int m=0;m<S0.length;m++){
        					double d=(m<numOriginalComponents)?gridCorr3D[m][ind]:gridZCorr[m-numOriginalComponents][ind];
        					S0[m]+= w;
        					SF[m]+= w*d;
        					SX[m]+= w*(ix1-ix);
        					SY[m]+= w*(iy1-iy);
        					SFX[m]+=w*d*(ix1-ix);
        					SFY[m]+=w*d*(iy1-iy);
        					SX2[m]+=w*(ix1-ix)*(ix1-ix);
        					SY2[m]+=w*(iy1-iy)*(iy1-iy);
        					SXY[m]+=w*(ix1-ix)*(iy1-iy);
        				}
        			}
Andrey Filippov's avatar
Andrey Filippov committed
9989

Andrey Filippov's avatar
Andrey Filippov committed
9990 9991 9992 9993 9994 9995 9996 9997 9998 9999 10000 10001 10002 10003 10004 10005 10006
        		}
        		for (int m=0;m<S0.length;m++){
        			double [][] aB={{SF[m]},{SFX[m]},{SFY[m]}};
        			double [][] aM={
        					{S0[m],SX[m], SY[m]},
        					{SX[m],SX2[m],SXY[m]},
        					{SY[m],SXY[m],SY2[m]}
        			};
        			Matrix B=new Matrix(aB);
        			Matrix M=new Matrix(aM);
        			Matrix V=M.solve(B);
        			if (m<numOriginalComponents) gridCorr3D[m][Index]=V.get(0,0);
        			else gridZCorr[m-numOriginalComponents][Index]=V.get(0,0);
        		}
    			if (this.debugLevel>debugThreshold) System.out.println("updated v="+(Index/width)+" u="+(Index%width)+" {"+
    					IJ.d2s(gridCorr3D[0][Index],2)+","+IJ.d2s(gridCorr3D[1][Index],2)+","+IJ.d2s(gridCorr3D[2][Index],2)+"}");
			}
Andrey Filippov's avatar
Andrey Filippov committed
10007 10008

// set mask again for the new calculated layer of pixels
Andrey Filippov's avatar
Andrey Filippov committed
10009 10010 10011 10012 10013
			for (int i =0;i<extList.size();i++){
        		Index=extList.get(i);
				fMask[Index]=true;
			}
        }
Andrey Filippov's avatar
Andrey Filippov committed
10014
	   return true;
Andrey Filippov's avatar
Andrey Filippov committed
10015
	}
Andrey Filippov's avatar
Andrey Filippov committed
10016

Andrey Filippov's avatar
Andrey Filippov committed
10017 10018 10019 10020 10021 10022 10023 10024 10025 10026 10027 10028 10029 10030 10031 10032
	public void logScale(
			double [] data,
			double fatZero){
		for (int i=0;i<data.length;i++){
			double d=((data[i]>=0)?data[i]:0.0);
			data[i]=(fatZero>0)?(Math.log(fatZero+d)):d;
		}
	}
	public void unLogScale(
			double [] data,
			double fatZero){
		for (int i=0;i<data.length;i++){
			if (fatZero>0.0) data[i]=Math.exp(data[i])-fatZero;
			if (data[i]<0.0) data[i]=0.0;
		}
	}
Andrey Filippov's avatar
Andrey Filippov committed
10033

Andrey Filippov's avatar
Andrey Filippov committed
10034
	/**
Andrey Filippov's avatar
Andrey Filippov committed
10035
	 * Extrapolates sensor correction beyond known data (in-place)
Andrey Filippov's avatar
Andrey Filippov committed
10036
	 * @param fieldXY [2][nPixels] vector field to extrapolate
Andrey Filippov's avatar
Andrey Filippov committed
10037 10038
	 * @param sMask [nPixels] alpha (0.0 .. 1.0) "reliability" mask to apply to vector field
	 * @param alphaThreshold start with pixels with alpha above this value (disregard border unreliable pixels)
Andrey Filippov's avatar
Andrey Filippov committed
10039 10040 10041 10042 10043 10044
	 * @param nsigma when fitting plane through new point use Gaussian weight function for the neighbors
	 *  (normalized to non-decimated points)
	 * @param ksigma Process pixels in a square with the side 2*sigma*ksigma
	 * @return false if nothing to extrapolate (too small mask)?
	 */
	public boolean extrapolateSensorCorrection(
10045
			int    numChn,
Andrey Filippov's avatar
Andrey Filippov committed
10046 10047 10048 10049 10050 10051
			boolean [] whichExtrapolate,
			double [][] fieldXY,
			double []sMask,
			double alphaThreshold,
			double nsigma,
			double ksigma){
Andrey Filippov's avatar
Andrey Filippov committed
10052

10053 10054 10055
		int decimate = getDecimateMasks(numChn);
		int sWidth =   (getSensorWidth(numChn)-1)/decimate+1;
		int sHeight =  (getSensorHeight(numChn)-1)/decimate+1;
Andrey Filippov's avatar
Andrey Filippov committed
10056 10057 10058 10059 10060 10061 10062 10063 10064 10065 10066 10067 10068 10069 10070 10071 10072 10073 10074 10075 10076 10077 10078 10079 10080 10081 10082 10083 10084 10085 10086 10087 10088
		double sigma=nsigma/decimate;
		boolean [] fMask=new boolean[fieldXY[0].length];
		for (int i=0;i<fMask.length;i++)
			fMask[i]=sMask[i]>=alphaThreshold;
		int len= (int) Math.ceil(sigma*ksigma);
		double [] gaussian=new double[len+1];
		double k=0.5/sigma/sigma;
		for (int i=0;i<=len;i++) gaussian[i]=Math.exp(-i*i*k);
		int [][] dirs={{-1,0},{1,0},{0,-1},{0,1}};
		List <Integer> extList=new ArrayList<Integer>(1000);
		Integer Index;
		extList.clear();
		// create initial wave
		if (this.debugLevel>2) System.out.println("extrapolateSensorCorrection() decimate="+decimate+", sWidth="+sWidth+" sHeight="+sHeight);
		for (int iy=0;iy<sHeight;iy++) for (int ix=0;ix<sWidth;ix++) {
			Index=iy*sWidth+ix;
			if (fMask[Index]) {
				int numOld=0;
				int numNew=0;
				for (int dir=0;dir<dirs.length;dir++){
					int ix1=ix+dirs[dir][0];
					int iy1=iy+dirs[dir][1];
					if ((ix1>=0) && (iy1>=0) && (ix1<sWidth) && (iy1<sHeight)) {
						if (fMask[iy1*sWidth+ix1]) numOld++;
						else numNew++;
					}
					if ((numNew>0) && (numOld>1)) extList.add(Index); // neighbor will have non-singular matrix
				}
			}
		}
		if (extList.size()==0) return false;
        while (extList.size()>0){
    		if (this.debugLevel>2) System.out.println("extList.size()="+extList.size());
Andrey Filippov's avatar
Andrey Filippov committed
10089 10090

        	// move wave front 1 pixel hor/vert
Andrey Filippov's avatar
Andrey Filippov committed
10091 10092 10093 10094 10095 10096 10097 10098
        	for (int i=extList.size();i>0;i--){ // repeat current size times
        		Index=extList.get(0);
        		extList.remove(0);
        		int iy=Index/sWidth;
        		int ix=Index%sWidth;
				for (int dir=0;dir<dirs.length;dir++){
					int ix1=ix+dirs[dir][0];
					int iy1=iy+dirs[dir][1];
Andrey Filippov's avatar
Andrey Filippov committed
10099
					if ((ix1>=0) && (iy1>=0) && (ix1<sWidth) && (iy1<sHeight)){
Andrey Filippov's avatar
Andrey Filippov committed
10100 10101 10102 10103 10104 10105 10106 10107 10108 10109 10110 10111 10112 10113 10114 10115 10116 10117
						Index=iy1*sWidth+ix1;
						if (!fMask[Index]){
							extList.add(Index);
							fMask[Index]=true; // remove later
						}
					}
				}
        	}
			// now un-mask the pixels in new list new
			for (int i =0;i<extList.size();i++){
        		Index=extList.get(i);
				fMask[Index]=false; // now mask is only set for known pixels
			}
// Calculate values (extrapolate) for the pixels in the list
			/*
Err = sum (W(x,y)*(f(x,y)-F0-Ax*(x-X0)-Ay*(y-Y0))^2)=
sum (Wxy*(Fxy^2+F0^2+Ax^2*(x-X0)^2+Ay^2*(y-Y0)^2
-2*Fxy*F0 -2*Fxy*Ax*(x-X0) - 2*Fxy*Ay*(y-Y0)
Andrey Filippov's avatar
Andrey Filippov committed
10118
+2*F0*Ax*(x-X0) + 2*F0*Ay*(y-Y0)
Andrey Filippov's avatar
Andrey Filippov committed
10119 10120 10121 10122 10123 10124 10125 10126 10127 10128 10129 10130 10131 10132 10133 10134 10135 10136 10137 10138 10139 10140 10141 10142 10143 10144 10145 10146 10147 10148 10149 10150 10151
+2*Ax*(x-X0)*Ay*(y-Y0))
(1)0=dErr/dF0= 2*sum (Wxy*(F0-Fxy+Ax*(x-X0)+Ay(y-Y0)))
(2)0=dErr/dAx= 2*sum (Wxy*(Ax*(x-X0)^2-Fxy*(x-X0) +F0*(x-X0)+Ay*(x-x0)*(y-Y0)))
(3)0=dErr/dAy= 2*sum (Wxy*(Ay*(y-y0)^2-Fxy*(y-Y0) +F0*(y-Y0)+Ax*(x-x0)*(y-Y0)))

S0 = sum(Wxy)
SF=  sum(Wxy*Fxy)
SX=  sum(Wxy*(x-X0)
SY=  sum(Wxy*(y-Y0)
SFX= sum(Wxy*Fxy*(x-X0)
SFY= sum(Wxy*Fxy*(y-Y0)
SX2= sum(Wxy*(x-X0)^2
SY2= sum(Wxy*(y-Y0)^2
SXY= sum(Wxy*(x-X0)*(y-Y0)

(1) F0*S0 - SF + Ax*SX +Ay*Sy = 0
(2) Ax*SX2-SFX+F0*SX+Ay*SXY = 0
(3) Ay*Sy2 -SFY + F0*SY +Ax*SXY = 0

(1) F0*S0  + Ax*SX +Ay*SY = SF
(2) Ax*SX2+F0*SX+Ay*SXY = SFX
(3) Ay*Sy2  + F0*SY +Ax*SXY = SFY


   | F0 |
V= | Ax |
   | Ay |

     | SF  |
B =  | SFX |
     | SFY |

     | S0  SX   SY  |
Andrey Filippov's avatar
Andrey Filippov committed
10152
M =  | SX  SX2  SXY |
Andrey Filippov's avatar
Andrey Filippov committed
10153 10154 10155 10156 10157 10158 10159 10160 10161 10162 10163 10164 10165 10166 10167 10168 10169 10170 10171 10172 10173 10174 10175 10176 10177 10178 10179 10180 10181 10182 10183 10184 10185 10186 10187 10188 10189 10190 10191
     | SY  SXY  SY2 |

M * V = B
			 */
			double [] zeros= new double[whichExtrapolate.length];
			for (int i=0;i<zeros.length;i++)zeros[i]=0.0;
			for (int i =0;i<extList.size();i++){
        		Index=extList.get(i);
        		int iy=Index/sWidth;
        		int ix=Index%sWidth;
        		double [] S0= zeros.clone();
        		double [] SF= zeros.clone();
        		double [] SX= zeros.clone();
        		double [] SY= zeros.clone();
        		double [] SFX=zeros.clone();
        		double [] SFY=zeros.clone();
        		double [] SX2=zeros.clone();
        		double [] SY2=zeros.clone();
        		double [] SXY=zeros.clone();
        		int iYmin=iy-len; if (iYmin<0) iYmin=0;
        		int iYmax=iy+len; if (iYmax>=sHeight) iYmax=sHeight-1;
        		int iXmin=ix-len; if (iXmin<0) iXmin=0;
        		int iXmax=ix+len; if (iXmax>=sWidth) iXmax=sWidth-1;
        		for (int iy1=iYmin;iy1<=iYmax;iy1++) for (int ix1=iXmin;ix1<=iXmax;ix1++) {
        			int ind=ix1+iy1*sWidth;
        			if (fMask[ind]){
        				double w=gaussian[(iy1>=iy)?(iy1-iy):(iy-iy1)]*gaussian[(ix1>=ix)?(ix1-ix):(ix-ix1)];
        				for (int m=0;m<whichExtrapolate.length;m++) if(whichExtrapolate[m]){
        					S0[m]+= w;
        					SF[m]+= w*fieldXY[m][ind];
        					SX[m]+= w*(ix1-ix);
        					SY[m]+= w*(iy1-iy);
        					SFX[m]+=w*fieldXY[m][ind]*(ix1-ix);
        					SFY[m]+=w*fieldXY[m][ind]*(iy1-iy);
        					SX2[m]+=w*(ix1-ix)*(ix1-ix);
        					SY2[m]+=w*(iy1-iy)*(iy1-iy);
        					SXY[m]+=w*(ix1-ix)*(iy1-iy);
        				}
        			}
Andrey Filippov's avatar
Andrey Filippov committed
10192

Andrey Filippov's avatar
Andrey Filippov committed
10193 10194 10195 10196 10197 10198 10199 10200 10201 10202 10203 10204 10205 10206 10207
        		}
        		for (int m=0;m<whichExtrapolate.length;m++) if(whichExtrapolate[m]){
        			double [][] aB={{SF[m]},{SFX[m]},{SFY[m]}};
        			double [][] aM={
        					{S0[m],SX[m], SY[m]},
        					{SX[m],SX2[m],SXY[m]},
        					{SY[m],SXY[m],SY2[m]}
        			};
        			Matrix B=new Matrix(aB);
        			Matrix M=new Matrix(aM);
        			Matrix V=M.solve(B);
        			fieldXY[m][Index]=V.get(0,0);
        		}

			}
Andrey Filippov's avatar
Andrey Filippov committed
10208 10209

// set mask again for the new calculated layer of pixels
Andrey Filippov's avatar
Andrey Filippov committed
10210 10211 10212 10213 10214 10215
			for (int i =0;i<extList.size();i++){
        		Index=extList.get(i);
				fMask[Index]=true;
			}
        }
		return true;
Andrey Filippov's avatar
Andrey Filippov committed
10216

Andrey Filippov's avatar
Andrey Filippov committed
10217
	}
Andrey Filippov's avatar
Andrey Filippov committed
10218 10219


Andrey Filippov's avatar
Andrey Filippov committed
10220 10221 10222 10223 10224
	/**
	 * Calculates residual correction from  the measured sensor pX, pY to the calculated {pixel X, pixel Y}
	 * @param distortionCalibrationData
	 * @param showIndividual - show individual images
	 * @param showIndividualNumber - which image to show (-1 - all)
Andrey Filippov's avatar
Andrey Filippov committed
10225
	 * @return
Andrey Filippov's avatar
Andrey Filippov committed
10226 10227 10228 10229 10230 10231 10232 10233 10234 10235 10236
	 */
	public double [][][] calculateSensorXYCorr(
			DistortionCalibrationData distortionCalibrationData,
			boolean showIndividual,
			int showIndividualNumber, // which image to show (-1 - all)
			boolean useGridAlpha // use grid alpha, false - use old calculations
			){
		int numChannels=distortionCalibrationData.getNumChannels(); // number of used channels
		int width=getGridWidth();
		int height=getGridHeight();
    	int imgRGBIndex=   3;
Andrey Filippov's avatar
Andrey Filippov committed
10237

Andrey Filippov's avatar
Andrey Filippov committed
10238 10239 10240 10241 10242 10243 10244
		int [] uvInc={0,1,width,width+1}; // four corners as vu index
		int [][] cycles={ // counter-clockwise corners bounding the area  (only orthogonal sides?)
				{1,0,2},
				{2,3,1},
				{0,2,3},
				{3,1,0}};
		double [][][] gridPCorr=new double [numChannels][][];
Andrey Filippov's avatar
Andrey Filippov committed
10245
		for (int chnNum=0;chnNum<gridPCorr.length;chnNum++) gridPCorr[chnNum]=null;
Andrey Filippov's avatar
Andrey Filippov committed
10246 10247 10248 10249 10250 10251 10252 10253 10254 10255
		boolean [] selectedImages=fittingStrategy.selectedImages();
		boolean debugExit=false;
		int debugCntr=2;
		int numSelected=0;
		for (int imgNum=0;imgNum<selectedImages.length;imgNum++) if (selectedImages[imgNum]) numSelected++;
		int numProcessed=0;
		IJ.showStatus("Calculating sensor corrections...");
		for (int imgNum=0;imgNum<selectedImages.length;imgNum++) if (selectedImages[imgNum]) {
			if (debugExit) break;
			int chnNum=fittingStrategy.distortionCalibrationData.gIP[imgNum].channel; // number of sub-camera
10256 10257 10258 10259 10260

			int decimate=getDecimateMasks(chnNum);
			int sWidth= (getSensorWidth(chnNum)-1)/decimate+1;
			int sHeight=(getSensorHeight(chnNum)-1)/decimate+1;

Andrey Filippov's avatar
Andrey Filippov committed
10261 10262
			int station=fittingStrategy.distortionCalibrationData.gIP[imgNum].getStationNumber(); // number of sub-camera
			double [][] photometrics=patternParameters.getPhotometricBySensor(station,chnNum); // head/bottom grid intensity/alpha
Andrey Filippov's avatar
Andrey Filippov committed
10263

Andrey Filippov's avatar
Andrey Filippov committed
10264 10265
			if (showIndividual && ((showIndividualNumber<0) || (showIndividualNumber==chnNum))) {
				String [] titles={"R","G","B","A"};
10266
				ShowDoubleFloatArrays.showArrays(photometrics, width, height,  true, "Photometrics"+chnNum+"-"+imgNum, titles);
Andrey Filippov's avatar
Andrey Filippov committed
10267 10268
			}

Andrey Filippov's avatar
Andrey Filippov committed
10269

Andrey Filippov's avatar
Andrey Filippov committed
10270 10271 10272 10273 10274 10275
			// initialize this array if it is needed, leave unused null
			if (gridPCorr[chnNum]==null){
				 gridPCorr[chnNum]=new double [7][sWidth*sHeight];
				for (int n=0;n<gridPCorr[chnNum].length;n++) for (int i=0;i<gridPCorr[chnNum][0].length;i++) gridPCorr[chnNum][n][i]=0.0;
			}
			double [][] thisPCorr=null;
Andrey Filippov's avatar
Andrey Filippov committed
10276

Andrey Filippov's avatar
Andrey Filippov committed
10277 10278 10279 10280 10281 10282 10283 10284 10285 10286 10287 10288 10289
			thisPCorr=new double [7][sWidth*sHeight]; // calculate for a single (this) image, accumulate in the end
			for (int n=0;n<thisPCorr.length;n++) for (int i=0;i<thisPCorr[0].length;i++) thisPCorr[n][i]=0.0;
			double [] diff=calcYminusFx(this.currentfX);
			// find data range for the selected image
			int index=0;
			int numImg=fittingStrategy.distortionCalibrationData.getNumImages();
			for (int iNum=0;(iNum<imgNum) && (iNum<numImg) ;iNum++) if (selectedImages[iNum])
				index+=fittingStrategy.distortionCalibrationData.gIP[iNum].pixelsUV.length;
			if (this.debugLevel>2) {
				System.out.println("calculateGridXYCorr(): fX.length="+this.currentfX.length+" this image index="+index);
			}
			double [][] imgData=new double[8][height * width]; // dPX, dPY, Px, Py, alpha,R,G,B
			for (int i=0;i<imgData.length;i++) for (int j=0;j<imgData[i].length;j++)imgData[i][j]=0.0;
Andrey Filippov's avatar
Andrey Filippov committed
10290

Andrey Filippov's avatar
Andrey Filippov committed
10291 10292 10293 10294 10295 10296 10297 10298 10299
			for (int i=0;i<fittingStrategy.distortionCalibrationData.gIP[imgNum].pixelsUV.length;i++){
				int u=fittingStrategy.distortionCalibrationData.gIP[imgNum].pixelsUV[i][0]+patternParameters.U0; // starting from 0
				int v=fittingStrategy.distortionCalibrationData.gIP[imgNum].pixelsUV[i][1]+patternParameters.V0; // starting from 0
				int vu=u+width*v;
				imgData[0][vu]=   diff[2*(index+i)];
				imgData[1][vu]=   diff[2*(index+i)+1];
				imgData[2][vu]= this.Y[2*(index+i)];  // measured pixel x
				imgData[3][vu]= this.Y[2*(index+i)+1];// measured pixel y
				imgData[4][vu]= this.weightFunction[2*(index+i)];
Andrey Filippov's avatar
Andrey Filippov committed
10300

Andrey Filippov's avatar
Andrey Filippov committed
10301 10302 10303 10304 10305 10306 10307 10308
				for (int c=0;c<3;c++){
//					double g=gridGeometry[v][u][gridRGBIndex+c];
					double g=photometrics[c][vu];
					imgData[5+c][vu]=(g>0)?(fittingStrategy.distortionCalibrationData.gIP[imgNum].pixelsXY[i][imgRGBIndex+c]/g):g;
				}
			}
			if (showIndividual && ((showIndividualNumber<0) || (showIndividualNumber==chnNum))) {
				String [] titles={"dPx","dPy","Px","Py","A","R","G","B"};// dPX, dPY, Px, Py, alpha,R,G,B - rgb - full, not incremental
10309
				ShowDoubleFloatArrays.showArrays(imgData, width, height,  true, "imgData"+imgNum, titles);
Andrey Filippov's avatar
Andrey Filippov committed
10310

Andrey Filippov's avatar
Andrey Filippov committed
10311 10312 10313 10314 10315 10316 10317 10318
			}

			// now use imgData array to fill thisPCorr by linear interpolation
			for (int v=0;v<(height-1); v++) for (int u=0; u<(width-1);u++){
				if (debugExit) break;
				int vu=u+width*v;
                double [][] cornerXY =new double[4][];
                for (int i=0;i<uvInc.length;i++){
Andrey Filippov's avatar
Andrey Filippov committed
10319
                	int vu1=vu+uvInc[i];
Andrey Filippov's avatar
Andrey Filippov committed
10320 10321 10322 10323 10324 10325 10326 10327 10328 10329 10330 10331 10332 10333 10334 10335 10336 10337 10338 10339 10340 10341 10342 10343 10344 10345 10346 10347 10348 10349 10350 10351 10352 10353 10354 10355 10356 10357 10358 10359 10360 10361 10362 10363 10364 10365 10366 10367 10368 10369 10370 10371 10372
                	if (imgData[4][vu1]>0.0){
                		cornerXY[i]=new double[2];
                		cornerXY[i][0]=imgData[2][vu1];
                		cornerXY[i][1]=imgData[3][vu1];
                	} else cornerXY[i]=null;
                }
                boolean [] cycleFits=new boolean[cycles.length];
                boolean anyFits=false;
                for (int i=0;i<cycles.length;i++){
                	cycleFits[i]=true;
                	for (int j=0;j<cycles[i].length;j++) if (cornerXY[cycles[i][j]]==null) {
                		cycleFits[i]=false;
                		break;
                	}
                	anyFits |=cycleFits[i];
                }
                if (!anyFits) continue; // not a single cycle
				if ((this.debugLevel>3) && !debugExit) {
					String debugString="cycleFits ";
					for (int i =0;i<cycleFits.length; i++) debugString+=" "+cycleFits[i];
					System.out.println(debugString);
				}
                if (cycleFits[0]&&cycleFits[1]){ // remove overlaps
                	cycleFits[2]=false;
                	cycleFits[3]=false;
                }
                boolean minMaxUndefined=true;
				double minX=0,maxX=0,minY=0,maxY=0;
				// find bounding rectangle;
				for (int nCycle=0;nCycle<cycles.length;nCycle++) if (cycleFits[nCycle]){
					int [] cycle=cycles[nCycle];
					for (int corner=0; corner<cycle.length;corner++){
						if (minMaxUndefined || (minX>cornerXY[cycle[corner]][0])) minX=cornerXY[cycle[corner]][0];
						if (minMaxUndefined || (maxX<cornerXY[cycle[corner]][0])) maxX=cornerXY[cycle[corner]][0];
						if (minMaxUndefined || (minY>cornerXY[cycle[corner]][1])) minY=cornerXY[cycle[corner]][1];
						if (minMaxUndefined || (maxY<cornerXY[cycle[corner]][1])) maxY=cornerXY[cycle[corner]][1];
						minMaxUndefined=false;
					}
				}
				int iMinX=(int) Math.floor(minX/decimate);
				int iMinY=(int) Math.floor(minY/decimate);
				int iMaxX=(int) Math.ceil(maxX/decimate);
				int iMaxY=(int) Math.ceil(maxY/decimate);
				// not sure if these checks are needed, got out of bounds wheriDy was =484=sHeight
				if (iMinX<0) iMinX=0;
				if (iMaxX>=sWidth) iMaxX=sWidth-1;
				if (iMinY<0) iMinY=0;
				if (iMaxY>=sHeight) iMaxY=sHeight-1;
				double [] originXY=new double [2];
				double [] endXY=new double [2];
				boolean debugHadPixels=false;
//TODO: scan X,Y in this rectangle, for points in defined squares/triangles find if the point is inside (accurate not to loose any).
				for (int idY=iMinY; idY<=iMaxY;idY++){
Andrey Filippov's avatar
Andrey Filippov committed
10373

Andrey Filippov's avatar
Andrey Filippov committed
10374 10375 10376 10377 10378 10379 10380 10381 10382 10383 10384 10385 10386 10387 10388 10389 10390 10391 10392 10393 10394
					double pY=idY*decimate; // in sensor pixels
					for (int idX=iMinX; idX<=iMaxX;idX++){
						double pX=idX*decimate; // in sensor pixels
						// scan allowed triangles, usually 2
						for (int nCycle=0;nCycle<cycles.length;nCycle++) if (cycleFits[nCycle]){
							int [] cycle=cycles[nCycle];
							// is this point inside?
							if (debugExit) {
								for (int nEdge=0;nEdge<cycle.length;nEdge++){
									int nextNEdge=(nEdge==(cycle.length-1))?0:(nEdge+1);
									System.out.println("nEdge="+nEdge+" nextNEdge"+nextNEdge);

									originXY[0]=imgData[2][vu+uvInc[cycle[nEdge]]];
									originXY[1]=imgData[3][vu+uvInc[cycle[nEdge]]];
									endXY[0]=   imgData[2][vu+uvInc[cycle[nextNEdge]]];
									endXY[1]=   imgData[3][vu+uvInc[cycle[nextNEdge]]];
									System.out.println("--- pX="+IJ.d2s(pX,1)+" originXY[0]="+IJ.d2s(originXY[0],1)+
											" endXY[1]="+IJ.d2s(endXY[1],1)+" originXY[1]="+IJ.d2s(originXY[1],1));
									System.out.println("--- pY="+IJ.d2s(pY,1)+" originXY[1]="+IJ.d2s(originXY[1],1)+
											" endXY[0]="+IJ.d2s(endXY[0],1)+" originXY[0]="+IJ.d2s(originXY[0],1));
									System.out.println("Cross-product="+IJ.d2s(((pX-originXY[0])*(endXY[1]-originXY[1]) - (pY-originXY[1])*(endXY[0]-originXY[0])),1));
Andrey Filippov's avatar
Andrey Filippov committed
10395

Andrey Filippov's avatar
Andrey Filippov committed
10396 10397 10398 10399 10400 10401 10402 10403 10404 10405 10406 10407 10408 10409 10410 10411 10412 10413 10414 10415 10416 10417 10418 10419 10420
								}
							}

							boolean inside=true;
							for (int nEdge=0;nEdge<cycle.length;nEdge++){
								int nextNEdge=(nEdge==(cycle.length-1))?0:(nEdge+1);

								originXY[0]=imgData[2][vu+uvInc[cycle[nEdge]]];
								originXY[1]=imgData[3][vu+uvInc[cycle[nEdge]]];
								endXY[0]=   imgData[2][vu+uvInc[cycle[nextNEdge]]];
								endXY[1]=   imgData[3][vu+uvInc[cycle[nextNEdge]]];
								if (((pX-originXY[0])*(endXY[1]-originXY[1]) - (pY-originXY[1])*(endXY[0]-originXY[0]))<0.0){
									inside=false;
									break;
								}
							}
							if (!inside) continue; // point is outside of the interpolation area, try next triangle (if any)
//							if ((this.debugLevel>3) && !debugExit) {
							if (this.debugLevel>3) {
								System.out.println("idX="+idX+" idY="+idY+" nCycle="+nCycle);
								String debugString1="cycle:";
								for (int i =0;i<cycle.length; i++) debugString1+=" "+cycle[i];
								System.out.println(debugString1);
							}

Andrey Filippov's avatar
Andrey Filippov committed
10421
							/* interpolate:
Andrey Filippov's avatar
Andrey Filippov committed
10422 10423 10424
							1. taking cycles[0] as origin and two (non co-linear) edge vectors - V1:from 0 to 1 and V2 from 1 to 2
							    find a1 and a2  so that vector V  (from 0  to pXY) = a1*V1+ a2*V2
							2. if F0 is the value of the interpolated function at cycles[0], F1 and F2 - at cycles[1] and cycles2
Andrey Filippov's avatar
Andrey Filippov committed
10425
							   then F=F0+(F1-F0)*a1 +(F2-F1)*a2
Andrey Filippov's avatar
Andrey Filippov committed
10426 10427 10428 10429 10430 10431 10432 10433 10434 10435 10436 10437 10438 10439 10440 10441 10442 10443 10444 10445 10446 10447 10448 10449 10450 10451 10452 10453 10454 10455 10456 10457 10458 10459 10460 10461 10462 10463
							 */
							double [] XY0={imgData[2][vu+uvInc[cycle[0]]],imgData[3][vu+uvInc[cycle[0]]]};
							double [] XY1={imgData[2][vu+uvInc[cycle[1]]],imgData[3][vu+uvInc[cycle[1]]]};
							double [] XY2={imgData[2][vu+uvInc[cycle[2]]],imgData[3][vu+uvInc[cycle[2]]]};
							double [] V= {pX-XY0[0],pY-XY0[1]};
							double [][] M={
									{XY1[0]-XY0[0],XY2[0]-XY1[0]},
									{XY1[1]-XY0[1],XY2[1]-XY1[1]}};
							double det=M[0][0]*M[1][1]-M[1][0]*M[0][1];
							double [][] MInverse={
									{ M[1][1]/det,-M[0][1]/det},
									{-M[1][0]/det, M[0][0]/det}};
							double [] a12={
									MInverse[0][0]*V[0]+MInverse[0][1]*V[1],
									MInverse[1][0]*V[0]+MInverse[1][1]*V[1]};
							int pCorrIndex=idY*sWidth+idX;
// some points may be accumulated multiple times - thisPCorr[3] will take care of this
							if (this.debugLevel>3) {
								System.out.println("XY0="+IJ.d2s(XY0[0],3)+":"+IJ.d2s(XY0[1],3));
								System.out.println("XY1="+IJ.d2s(XY1[0],3)+":"+IJ.d2s(XY1[1],3));
								System.out.println("XY2="+IJ.d2s(XY2[0],3)+":"+IJ.d2s(XY2[1],3));
								System.out.println("M00="+IJ.d2s(M[0][0],3)+" M01="+IJ.d2s(M[0][1],3));
								System.out.println("M10="+IJ.d2s(M[1][0],3)+" M11="+IJ.d2s(M[1][1],3));
								System.out.println("MInverse00="+IJ.d2s(MInverse[0][0],5)+" MInverse01="+IJ.d2s(MInverse[0][1],5));
								System.out.println("MInverse10="+IJ.d2s(MInverse[1][0],5)+" MInverse11="+IJ.d2s(MInverse[1][1],5));
								System.out.println("a12="+IJ.d2s(a12[0],3)+":"+IJ.d2s(a12[1],3));
								System.out.println("imgData[0][vu+uvInc[cycle[0]]]="+IJ.d2s(imgData[0][vu+uvInc[cycle[0]]],3)+
										"imgData[1][vu+uvInc[cycle[0]]]="+IJ.d2s(imgData[1][vu+uvInc[cycle[0]]],3));
								System.out.println("imgData[0][vu+uvInc[cycle[1]]]="+IJ.d2s(imgData[0][vu+uvInc[cycle[1]]],3)+
										"imgData[1][vu+uvInc[cycle[1]]]="+IJ.d2s(imgData[1][vu+uvInc[cycle[1]]],3));
								System.out.println("imgData[0][vu+uvInc[cycle[2]]]="+IJ.d2s(imgData[0][vu+uvInc[cycle[2]]],3)+
										"imgData[1][vu+uvInc[cycle[2]]]="+IJ.d2s(imgData[1][vu+uvInc[cycle[2]]],3));
							}

							double [] corr={
									 imgData[0][vu+uvInc[cycle[0]]]+ // dPx
									(imgData[0][vu+uvInc[cycle[1]]]-imgData[0][vu+uvInc[cycle[0]]])*a12[0]+
									(imgData[0][vu+uvInc[cycle[2]]]-imgData[0][vu+uvInc[cycle[1]]])*a12[1],
Andrey Filippov's avatar
Andrey Filippov committed
10464

Andrey Filippov's avatar
Andrey Filippov committed
10465 10466 10467
									 imgData[1][vu+uvInc[cycle[0]]]+ // dPy
									(imgData[1][vu+uvInc[cycle[1]]]-imgData[1][vu+uvInc[cycle[0]]])*a12[0]+
									(imgData[1][vu+uvInc[cycle[2]]]-imgData[1][vu+uvInc[cycle[1]]])*a12[1],
Andrey Filippov's avatar
Andrey Filippov committed
10468

Andrey Filippov's avatar
Andrey Filippov committed
10469 10470 10471 10472 10473 10474 10475 10476 10477 10478 10479 10480 10481 10482 10483 10484 10485 10486 10487 10488
									 imgData[4][vu+uvInc[cycle[0]]]+ // alpha
									(imgData[4][vu+uvInc[cycle[1]]]-imgData[4][vu+uvInc[cycle[0]]])*a12[0]+
									(imgData[4][vu+uvInc[cycle[2]]]-imgData[4][vu+uvInc[cycle[1]]])*a12[1],
									 imgData[5][vu+uvInc[cycle[0]]]+ // Red measured/pattern
									(imgData[5][vu+uvInc[cycle[1]]]-imgData[5][vu+uvInc[cycle[0]]])*a12[0]+
									(imgData[5][vu+uvInc[cycle[2]]]-imgData[5][vu+uvInc[cycle[1]]])*a12[1],
									 imgData[6][vu+uvInc[cycle[0]]]+ // Green measured/pattern
									(imgData[6][vu+uvInc[cycle[1]]]-imgData[6][vu+uvInc[cycle[0]]])*a12[0]+
									(imgData[6][vu+uvInc[cycle[2]]]-imgData[6][vu+uvInc[cycle[1]]])*a12[1],
									 imgData[7][vu+uvInc[cycle[0]]]+ // Blue  measured/pattern
									(imgData[7][vu+uvInc[cycle[1]]]-imgData[7][vu+uvInc[cycle[0]]])*a12[0]+
									(imgData[7][vu+uvInc[cycle[2]]]-imgData[7][vu+uvInc[cycle[1]]])*a12[1]
									};
							if (this.debugLevel>3) {
								System.out.println("corr="+IJ.d2s(corr[0],3)+" "+IJ.d2s(corr[1],3)+" "+IJ.d2s(corr[2],3));
							}
 if (pCorrIndex>thisPCorr[0].length) {
	 System.out.println("imgNum=" + imgNum+": "+	fittingStrategy.distortionCalibrationData.gIP[imgNum].path);
	 System.out.println("thisPCorr[0].length="+thisPCorr[0].length+" pCorrIndex="+pCorrIndex+" sWidth="+sWidth+" idY="+idY+" idX="+idX);
 }
Andrey Filippov's avatar
Andrey Filippov committed
10489
							thisPCorr[0][pCorrIndex]+= corr[0];// dPx
Andrey Filippov's avatar
Andrey Filippov committed
10490 10491 10492 10493 10494 10495 10496 10497 10498 10499 10500 10501 10502 10503 10504 10505 10506 10507 10508 10509 10510 10511 10512 10513 10514 10515 10516 10517 10518 10519 10520 10521 10522 10523 10524
							thisPCorr[1][pCorrIndex]+= corr[1];// dPy
							thisPCorr[2][pCorrIndex]+= corr[2];// alpha
							thisPCorr[3][pCorrIndex]+= 1.0;    // number of times accumulated
							thisPCorr[4][pCorrIndex]+= corr[3];// red
							thisPCorr[5][pCorrIndex]+= corr[4];// green
							thisPCorr[6][pCorrIndex]+= corr[5];// blue

							if (this.debugLevel>3) {
								debugHadPixels=true;
//								if (!debugExit) debugCntr--;
//								if (debugCntr==0) debugExit=true; // exit after first non-empty tile
							}

//gridPCorr[chnNum]
						}
					} // idX
					// use same order in calculations, make sure no gaps
				} // idY
				if ((this.debugLevel>3) && (debugHadPixels)){
					if (!debugExit) {
						System.out.println(
								" minX="+IJ.d2s(minX,1)+
								" maxX="+IJ.d2s(maxX,1));
						System.out.println(
								" minY="+IJ.d2s(minY,1)+
								" maxY="+IJ.d2s(maxY,1));
						System.out.println(
								" iMinX="+iMinX+
								" iMaxX="+iMaxX);
						System.out.println(
								" iMinY="+iMinY+
								" iMaxY="+iMaxY);
					}
					if (!debugExit) debugCntr--;
					if (debugCntr==0) debugExit=true; // exit after first non-empty tile
Andrey Filippov's avatar
Andrey Filippov committed
10525

Andrey Filippov's avatar
Andrey Filippov committed
10526 10527
				}
			} // finished image
Andrey Filippov's avatar
Andrey Filippov committed
10528 10529


Andrey Filippov's avatar
Andrey Filippov committed
10530 10531
/*			if (showIndividual) {
				String [] titles={"dPx","dPy","alpha","Multiple","Red","Green","Blue"};
10532
				ShowDoubleFloatArrays.showArrays(thisPCorr, sWidth, sHeight,  true, "thisPCorr_pre"+imgNum, titles);
Andrey Filippov's avatar
Andrey Filippov committed
10533
			}
Andrey Filippov's avatar
Andrey Filippov committed
10534 10535
*/
			// some points may be calculated multiple times
Andrey Filippov's avatar
Andrey Filippov committed
10536 10537 10538 10539 10540 10541 10542 10543 10544 10545 10546
			for (int i=0;i<gridPCorr[chnNum][0].length;i++) if (thisPCorr[3][i]>=1.0){
				thisPCorr[0][i]/=thisPCorr[3][i]; // dPx
				thisPCorr[1][i]/=thisPCorr[3][i]; // dPy
				thisPCorr[2][i]/=thisPCorr[3][i]; // alpha
				thisPCorr[4][i]/=thisPCorr[3][i]; // r
				thisPCorr[5][i]/=thisPCorr[3][i]; // g
				thisPCorr[6][i]/=thisPCorr[3][i]; // b
			}

			if (showIndividual && ((showIndividualNumber<0) || (showIndividualNumber==chnNum))) {
				String [] titles={"dPx","dPy","alpha","Multiple","Red","Green","Blue"};
10547
				ShowDoubleFloatArrays.showArrays(thisPCorr, sWidth, sHeight,  true, "thisPCorr"+imgNum, titles);
Andrey Filippov's avatar
Andrey Filippov committed
10548 10549 10550 10551 10552 10553 10554 10555 10556 10557 10558 10559 10560
			}
			for (int i=0;i<gridPCorr[chnNum][0].length;i++) if (thisPCorr[2][i]>0){
				gridPCorr[chnNum][0][i]+=thisPCorr[0][i]*thisPCorr[2][i];
				gridPCorr[chnNum][1][i]+=thisPCorr[1][i]*thisPCorr[2][i];
				/**TODO: not used anyway - just for debugging? see if just the sensor mask should go here? Or when saving?*/
				if (gridPCorr[chnNum][2][i]<thisPCorr[2][i]) gridPCorr[chnNum][2][i]=thisPCorr[2][i]; // best alpha
				gridPCorr[chnNum][3][i]+=                thisPCorr[2][i]; // sum of weights from all images
				gridPCorr[chnNum][4][i]+=thisPCorr[4][i]*thisPCorr[2][i];
				gridPCorr[chnNum][5][i]+=thisPCorr[5][i]*thisPCorr[2][i];
				gridPCorr[chnNum][6][i]+=thisPCorr[6][i]*thisPCorr[2][i];
			}
			IJ.showProgress(++numProcessed, numSelected);
		}
Andrey Filippov's avatar
Andrey Filippov committed
10561
/*
Andrey Filippov's avatar
Andrey Filippov committed
10562 10563
		if (showIndividual) {
			String [] titles={"dPx","dPy","alpha","Multiple","Red","Green","Blue"};
10564
			for (int chnNum=0;chnNum<gridPCorr.length;chnNum++) if (gridPCorr[chnNum]!=null) ShowDoubleFloatArrays.showArrays(gridPCorr[chnNum], sWidth, sHeight,  true, "gridPCorr1"+chnNum, titles);
Andrey Filippov's avatar
Andrey Filippov committed
10565
		}
Andrey Filippov's avatar
Andrey Filippov committed
10566
*/
Andrey Filippov's avatar
Andrey Filippov committed
10567 10568 10569 10570 10571 10572 10573 10574 10575
		for (int chnNum=0;chnNum<gridPCorr.length;chnNum++) if (gridPCorr[chnNum]!=null){
			for (int i=0;i<gridPCorr[chnNum][0].length;i++) if (gridPCorr[chnNum][2][i]>0){ //null pointer
				gridPCorr[chnNum][0][i]/=gridPCorr[chnNum][3][i];
				gridPCorr[chnNum][1][i]/=gridPCorr[chnNum][3][i];
				gridPCorr[chnNum][4][i]/=gridPCorr[chnNum][3][i];
				gridPCorr[chnNum][5][i]/=gridPCorr[chnNum][3][i];
				gridPCorr[chnNum][6][i]/=gridPCorr[chnNum][3][i];
			}
		}
Andrey Filippov's avatar
Andrey Filippov committed
10576
/*
Andrey Filippov's avatar
Andrey Filippov committed
10577 10578
		if (showIndividual) {
			String [] titles={"dPx","dPy","alpha","Multiple","Red","Green","Blue"};
10579
			for (int chnNum=0;chnNum<gridPCorr.length;chnNum++) if (gridPCorr[chnNum]!=null) ShowDoubleFloatArrays.showArrays(gridPCorr[chnNum], sWidth, sHeight,  true, "gridPCorr2"+chnNum, titles);
Andrey Filippov's avatar
Andrey Filippov committed
10580
		}
Andrey Filippov's avatar
Andrey Filippov committed
10581
*/
Andrey Filippov's avatar
Andrey Filippov committed
10582 10583
		return gridPCorr;
	}
Andrey Filippov's avatar
Andrey Filippov committed
10584

Andrey Filippov's avatar
Andrey Filippov committed
10585 10586 10587 10588 10589 10590 10591 10592 10593 10594 10595 10596 10597 10598 10599 10600 10601 10602 10603 10604 10605 10606 10607 10608 10609 10610 10611 10612
/**
 * Calculate partial derivative analytically (as the Jacobian calculation) and by difference divided by delta and compare
 * Done to debug derivatives calculation
 */
	public void compareDerivatives(){
		if (fittingStrategy==null) {
			String msg="Fitting strategy does not exist, exiting";
			IJ.showMessage("Error",msg);
			throw new IllegalArgumentException (msg);
		}
    	int numSeries=fittingStrategy.getNumSeries();
	    GenericDialog gd = new GenericDialog("Debug: verifying partial derivatives calculation, select series number");
		gd.addNumericField("Series number to show (0.."+(numSeries-1), this.seriesNumber, 0);
		gd.addCheckbox("Show actual parameters (false: X0,Y0,distance, angles)", true);
		gd.addCheckbox("Apply sensor mask (fade near edges)", true);
		gd.addCheckbox("Debug derivatives (show analytic/difference match)",true);
	    gd.showDialog();
	    if (gd.wasCanceled()) return;
	    this.seriesNumber=     (int) gd.getNextNumber();
	    boolean useActualParameters=gd.getNextBoolean();
	    boolean applySensorMask=gd.getNextBoolean();
	    boolean debugDerivatives=gd.getNextBoolean();
	    // currently not possible to debug "internal" parameters, so
//	    debugDerivatives&=useActualParameters; //*******************
		initFittingSeries(false,filterForAll,this.seriesNumber);
		int numPars=this.currentVector.length;
    	String [] parameterNames;
    	String [] parameterUnits;
Andrey Filippov's avatar
Andrey Filippov committed
10613

Andrey Filippov's avatar
Andrey Filippov committed
10614
    	if (useActualParameters) {
10615 10616
    		parameterNames=new String[fittingStrategy.distortionCalibrationData.getNumDescriptions()];
    		parameterUnits=new String[fittingStrategy.distortionCalibrationData.getNumDescriptions()];
Andrey Filippov's avatar
Andrey Filippov committed
10617 10618
    		for (int i=0;i<parameterNames.length;i++){
    			// TODO: move to DdistortionCalibrationData methods()
10619 10620
    			parameterNames[i]=fittingStrategy.distortionCalibrationData.descrField(i,0);
    			parameterUnits[i]=fittingStrategy.distortionCalibrationData.descrField(i,2);
Andrey Filippov's avatar
Andrey Filippov committed
10621 10622 10623 10624 10625 10626 10627 10628 10629 10630 10631 10632 10633 10634 10635 10636 10637 10638 10639 10640 10641
    		}
    	} else {
    		parameterNames=lensDistortionParameters.getAllNames();
    		parameterUnits=lensDistortionParameters.getAllUnits();
    	}
	    gd = new GenericDialog((debugDerivatives?"Debug: verifying partial derivatives calculation,":"Showing partial derivatives,") +" select parameter number");
	    if (useActualParameters) {
	    	for (int i=0;i<this.currentVector.length;i++){
	    		int parNum=fittingStrategy.parameterMap[i][1];
	    		int imgNum=fittingStrategy.parameterMap[i][0];
	    		gd.addMessage(i+": "+parameterNames[parNum]+
	    				"["+imgNum+"]("+parameterUnits[parNum]+") "+IJ.d2s(this.currentVector[i],3));
	    	}
			gd.addNumericField("Select parameter number (0.."+(numPars-1)+") from above", 0, 0);
	    } else {
	    	for (int i=0;i<parameterNames.length;i++){
	    		gd.addMessage(i+": "+parameterNames[i]+"("+parameterUnits[i]+") ");
	    	}
			gd.addNumericField("Select parameter number (0.."+(parameterNames.length-1)+") from above", 0, 0);

	    }
10642
		if (debugDerivatives) gd.addNumericField("Select delta to increment selected parameter", .001, 5);
Andrey Filippov's avatar
Andrey Filippov committed
10643
		if (debugDerivatives) gd.addCheckbox("Show inter-parameter derivatives matrix", true);
10644
		WindowTools.addScrollBars(gd);
Andrey Filippov's avatar
Andrey Filippov committed
10645 10646 10647 10648 10649 10650 10651 10652 10653 10654 10655 10656 10657
	    gd.showDialog();
	    if (gd.wasCanceled()) return;
	    int selectedParameter=     (int) gd.getNextNumber();
	    double delta=0;
	    if (debugDerivatives) delta=     gd.getNextNumber();
	    boolean showInterparameterDerivatives=false;
	    if (debugDerivatives) showInterparameterDerivatives=gd.getNextBoolean();
		double [] this_currentfX=null;
	    double [] d_derivative;
	    double [] d_delta=null;
	    String title;
	    if (useActualParameters) {
	    	this_currentfX=calculateFxAndJacobian(this.currentVector, true); // is it always true here (this.jacobian==null)
10658
	    	d_derivative=this.jacobian[selectedParameter].clone(); //  wrong?
Andrey Filippov's avatar
Andrey Filippov committed
10659 10660 10661 10662 10663 10664 10665 10666 10667 10668 10669 10670 10671 10672 10673 10674 10675 10676 10677 10678 10679 10680 10681 10682 10683 10684 10685 10686 10687 10688 10689 10690 10691 10692 10693 10694 10695
	    	if (debugDerivatives) {
	    		double[] modVector=this.currentVector.clone();
	    		modVector[selectedParameter]+=delta;
	    		d_delta=calculateFxAndJacobian(modVector, true);
	    		if (this.debugLevel>3) {
	    			for (int i=0;i<d_delta.length;i++) {
	    				System.out.println(i+": "+IJ.d2s(d_delta[i],3)+" - "+IJ.d2s(this_currentfX[i],3)+" = "
	    						+ IJ.d2s(d_delta[i]-this_currentfX[i],3));
	    			}

	    		}
	    		for (int i=0;i<d_delta.length;i++) d_delta[i]= (d_delta[i]-this_currentfX[i])/delta;
	    	}
		    int parNum=fittingStrategy.parameterMap[selectedParameter][1];
			int imgNum=fittingStrategy.parameterMap[selectedParameter][0];
			title=parameterNames[parNum]+"_derivatives:"+imgNum;
	    } else {
	    	d_derivative=calculateJacobian16(this.currentVector, -1,0.0)[selectedParameter].clone();
	    	if (debugDerivatives) d_delta=     calculateJacobian16(this.currentVector, -1,delta)[selectedParameter].clone();
			title=parameterNames[selectedParameter]+"_derivatives";
	    }
	    if (this.debugLevel>3) {
		    for (int i=0;i<d_delta.length;i++) {
		    	System.out.println(i+":: "+IJ.d2s(d_delta[i],3)+" - "+IJ.d2s(d_derivative[i],3));
		    }
	    }
	    double [] sumWeight=showCompareDerivatives (d_derivative, d_delta, applySensorMask, !useActualParameters,  title ); // d_delta==null - no debug
	    if (showInterparameterDerivatives && (delta>0)) {
	    debugCompareInterparameterDerivatives(
	    		this.currentVector.clone(),
	    		-1, //int imgNum,
	    		delta);
	    }
	    for (int i=0;i<sumWeight.length; i++) if (sumWeight[i]>0.0){
	    	System.out.println("Image "+i+", "+title+"derivative RMS="+sumWeight[i]);
	    }
	}
Andrey Filippov's avatar
Andrey Filippov committed
10696 10697


Andrey Filippov's avatar
Andrey Filippov committed
10698 10699
	/**
	 * Show comparison of the calculated partial derivatives in Jacobian and approximated by difference
Andrey Filippov's avatar
Andrey Filippov committed
10700
	 * for incremented parameters
Andrey Filippov's avatar
Andrey Filippov committed
10701 10702 10703 10704
	 * @param imgNumber - number of image in series to show
	 * @param d_derivative vector array of "true" derivatives (from Jacobian)
	 * @param d_delta approximated derivatives from varying parameter
	 * @param title image title
Andrey Filippov's avatar
Andrey Filippov committed
10705
	 * @return rms
Andrey Filippov's avatar
Andrey Filippov committed
10706 10707
	 */
	public double showCompareDerivatives(int imgNumber, double [] d_derivative, double [] d_delta, boolean applySensorMask, String title ){
10708
		String [] titlesDebug={"dX-derivative","dY-derivative","abs-derivative","diff-X (should be 0)","diff-Y (should be 0)","dX-delta/delta","dY-delta/delta","dX-delta","dY-delta"};
Andrey Filippov's avatar
Andrey Filippov committed
10709 10710 10711
		String [] titlesNoDebug={"dX-derivative","dY-derivative","abs-derivative"};
		String [] titles= (d_delta==null)? titlesNoDebug:titlesDebug;
		double [] d_diff=new double [d_derivative.length];
10712
		double [] r_diff=new double [d_derivative.length];
Andrey Filippov's avatar
Andrey Filippov committed
10713
		double [] aDeriv=new double [d_derivative.length/2];
Andrey Filippov's avatar
Andrey Filippov committed
10714

10715 10716 10717 10718
		if (d_delta!=null) for (int i=0;i<d_diff.length;i++){
			d_diff[i]=d_derivative[i]-d_delta[i];
			r_diff[i]=d_diff[i]/d_delta[i];
		}
Andrey Filippov's avatar
Andrey Filippov committed
10719 10720 10721 10722 10723 10724 10725 10726 10727 10728 10729 10730 10731 10732 10733 10734 10735 10736
// find data range for the selected image
		int index=0;
		int numImg=fittingStrategy.distortionCalibrationData.getNumImages();
		boolean [] selectedImages=fittingStrategy.selectedImages();
		for (int imgNum=0;(imgNum<imgNumber) && (imgNum<numImg) ;imgNum++) if (selectedImages[imgNum])
			index+=fittingStrategy.distortionCalibrationData.gIP[imgNum].pixelsUV.length;
		double sumWeights=0.0;
		double sumDerivatives2=0.0;
		double w,sqrtW;
		for (int i=2*index;i<2*(2*index+fittingStrategy.distortionCalibrationData.gIP[imgNumber].pixelsUV.length);i++){
			w=applySensorMask?this.weightFunction[i]:1.0;
			if (w<0.0) w=0.0;
			sumWeights+=w;
			sumDerivatives2+=d_derivative[i]*d_derivative[i]*w;
			sqrtW=Math.sqrt(w);
			d_derivative[i]*=sqrtW; // for display
			if (d_delta!=null) d_delta[i]*=sqrtW;
			if ((i&1)==0) aDeriv[i>>1]=Math.sqrt(d_derivative[i]*d_derivative[i]+d_derivative[i+1]*d_derivative[i+1]);
Andrey Filippov's avatar
Andrey Filippov committed
10737
		}
Andrey Filippov's avatar
Andrey Filippov committed
10738 10739 10740 10741 10742
		sumDerivatives2=Math.sqrt(sumDerivatives2/sumWeights*2.0); // 2.0 because x,y pair should not be averaged, just added
		titles[2]+=":rms="+sumDerivatives2;
		int width=getGridWidth();
		double [][] imgData=new double[titles.length][getGridHeight() * width];
		for (int i=0;i<imgData.length;i++) for (int j=0;j<imgData[i].length;j++)imgData[i][j]=0.0;
Andrey Filippov's avatar
Andrey Filippov committed
10743

Andrey Filippov's avatar
Andrey Filippov committed
10744 10745 10746 10747 10748 10749 10750 10751 10752 10753
		for (int i=0;i<fittingStrategy.distortionCalibrationData.gIP[imgNumber].pixelsUV.length;i++){
			int u=fittingStrategy.distortionCalibrationData.gIP[imgNumber].pixelsUV[index+i][0]+patternParameters.U0;
			int v=fittingStrategy.distortionCalibrationData.gIP[imgNumber].pixelsUV[index+i][1]+patternParameters.V0;
			int vu=u+width*v;
			imgData[0][vu]=   d_derivative[2*(index+i)];
			imgData[1][vu]=   d_derivative[2*(index+i)+1];
			imgData[2][vu]=   aDeriv[index+i];
			if (d_delta!=null) {
				imgData[3][vu]=   d_diff[2*(index+i)];
				imgData[4][vu]=   d_diff[2*(index+i)+1];
10754 10755 10756 10757
				imgData[5][vu]=   r_diff[2*(index+i)];
				imgData[6][vu]=   r_diff[2*(index+i)+1];
				imgData[7][vu]=   d_delta[2*(index+i)];
				imgData[8][vu]=   d_delta[2*(index+i)+1];
Andrey Filippov's avatar
Andrey Filippov committed
10758 10759
			}
		}
10760
		ShowDoubleFloatArrays.showArrays(imgData, width, getGridHeight(),  true, title, titles);
Andrey Filippov's avatar
Andrey Filippov committed
10761 10762 10763 10764
		return sumDerivatives2;
	}
	/**
	 * Show comparison of the calculated partial derivatives in Jacobian and approximated by difference
Andrey Filippov's avatar
Andrey Filippov committed
10765
	 * for incremented parameters (for all selected images in the series)
Andrey Filippov's avatar
Andrey Filippov committed
10766 10767 10768 10769 10770 10771 10772 10773 10774 10775 10776 10777 10778 10779 10780 10781 10782 10783 10784 10785
	 * @param d_derivative vector array of "true" derivatives (from Jacobian)
	 * @param d_delta approximated derivatives form varying parameter
	 * @param applySensorMask Multiply by sensor mask (fade near edges)
	 * @param single calculate just the first selected image
	 * @param title image title
	 * @return array of rms
	 */

	public double[] showCompareDerivatives (double [] d_derivative, double [] d_delta, boolean applySensorMask, boolean single, String title ){
		boolean [] selectedImages=fittingStrategy.selectedImages();
		double [] diffs= new double [selectedImages.length];
		for (int imgNum=0;imgNum<diffs.length;imgNum++) diffs[imgNum]=0.0;
		for (int imgNum=0;imgNum<selectedImages.length;imgNum++) if (selectedImages[imgNum]) {
			diffs[imgNum] =showCompareDerivatives(imgNum, d_derivative, d_delta, applySensorMask, title+"-"+imgNum);
			if (single) break;
		}
		return diffs;
	}

	/**
Andrey Filippov's avatar
Andrey Filippov committed
10786
	 *
Andrey Filippov's avatar
Andrey Filippov committed
10787 10788 10789 10790 10791 10792 10793 10794 10795 10796 10797 10798 10799 10800 10801 10802 10803 10804 10805 10806 10807 10808 10809 10810 10811 10812 10813 10814 10815
	 * @param delta if 0 - actual derivatives, >0 - approximate derivatives by deltas
	 * @return for each v,u - values and derivatives
	 */
	public double [][][][] calcGridOnSensor( double delta) {
    	int gridHeight=patternParameters.gridGeometry.length;
    	int gridWidth=patternParameters.gridGeometry[0].length;
    	this.gridOnSensor=new double[gridHeight][gridWidth][2][15];
    	double [][] node;
 //   	double [][][] nodes=new double [15][][];
    	boolean dMode=delta>0;
        if (this.debugLevel>2){
        	System.out.println("calcGridOnSensor()");
        	System.out.println("this.lensDistortionParameters.distance="+IJ.d2s(this.lensDistortionParameters.distance, 3));
        	System.out.println("this.lensDistortionParameters.x0="+      IJ.d2s(this.lensDistortionParameters.x0, 3));
        	System.out.println("this.lensDistortionParameters.y0="+      IJ.d2s(this.lensDistortionParameters.y0, 3));
        	System.out.println("this.lensDistortionParameters.z0="+      IJ.d2s(this.lensDistortionParameters.z0, 3));
        	System.out.println("this.lensDistortionParameters.pitch="+   IJ.d2s(this.lensDistortionParameters.pitch, 3));
        	System.out.println("this.lensDistortionParameters.yaw="+IJ.d2s(this.lensDistortionParameters.yaw, 3));
        	System.out.println("this.lensDistortionParameters.roll="+IJ.d2s(this.lensDistortionParameters.roll, 3));
        	System.out.println("this.lensDistortionParameters.focalLength="+IJ.d2s(this.lensDistortionParameters.focalLength, 3));
        	System.out.println("this.lensDistortionParameters.px0="+IJ.d2s(this.lensDistortionParameters.px0, 3));
        	System.out.println("this.lensDistortionParameters.py0="+IJ.d2s(this.lensDistortionParameters.py0, 3));
        	System.out.println("this.lensDistortionParameters.distortionA8="+IJ.d2s(this.lensDistortionParameters.distortionA8, 5));
        	System.out.println("this.lensDistortionParameters.distortionA7="+IJ.d2s(this.lensDistortionParameters.distortionA7, 5));
        	System.out.println("this.lensDistortionParameters.distortionA6="+IJ.d2s(this.lensDistortionParameters.distortionA6, 5));
        	System.out.println("this.lensDistortionParameters.distortionA5="+IJ.d2s(this.lensDistortionParameters.distortionA5, 5));
        	System.out.println("this.lensDistortionParameters.distortionA="+IJ.d2s(this.lensDistortionParameters.distortionA, 5));
        	System.out.println("this.lensDistortionParameters.distortionB="+IJ.d2s(this.lensDistortionParameters.distortionB, 5));
        	System.out.println("this.lensDistortionParameters.distortionC="+IJ.d2s(this.lensDistortionParameters.distortionC, 5));
10816
        	System.out.println("this.lensDistortionParameters.lensDistortionModel="+this.lensDistortionParameters.lensDistortionModel);
10817 10818 10819 10820 10821 10822 10823 10824
        	for (int i=0;i<this.lensDistortionParameters.r_xy.length;i++){
            	System.out.println("this.lensDistortionParameters.r_xy["+i+"][0]="+IJ.d2s(this.lensDistortionParameters.r_xy[i][0], 5));
            	System.out.println("this.lensDistortionParameters.r_xy["+i+"][1]="+IJ.d2s(this.lensDistortionParameters.r_xy[i][1], 5));
        	}
        	for (int i=0;i<this.lensDistortionParameters.r_od.length;i++){
            	System.out.println("this.lensDistortionParameters.r_od["+i+"][0]="+IJ.d2s(this.lensDistortionParameters.r_od[i][0], 5));
            	System.out.println("this.lensDistortionParameters.r_od["+i+"][1]="+IJ.d2s(this.lensDistortionParameters.r_od[i][1], 5));
        	}
Andrey Filippov's avatar
Andrey Filippov committed
10825 10826
        }
        LensDistortionParameters ldp=this.lensDistortionParameters.clone();
10827 10828
        // 06/2019 - need to update distortionRadius, pixelSize)

Andrey Filippov's avatar
Andrey Filippov committed
10829
//		public void setLensDistortionParameters(LensDistortionParameters ldp
Andrey Filippov's avatar
Andrey Filippov committed
10830

Andrey Filippov's avatar
Andrey Filippov committed
10831 10832 10833 10834 10835 10836 10837 10838 10839 10840 10841 10842 10843 10844 10845
        for (int v=0; v<gridHeight; v++) for (int u=0; u<gridWidth; u++) if (patternParameters.gridGeometry[v][u][3]>0) {
        	this.lensDistortionParameters.setLensDistortionParameters(ldp); // restore
        	node=this.lensDistortionParameters.calcPartialDerivatives(
        			patternParameters.gridGeometry[v][u][0],//double xp, // target point horizontal, positive - right,  mm
        			patternParameters.gridGeometry[v][u][1],//double yp, // target point vertical,   positive - down,  mm
        			patternParameters.gridGeometry[v][u][2],//double zp, // target point horizontal, positive - away from camera,  mm
        			!dMode);//boolean calculateAll){ // calculate derivatives, false - values only
        	if (this.debugLevel>3) {
        		System.out.println("calcPartialDerivatives("+
        				IJ.d2s(patternParameters.gridGeometry[v][u][0],2)+","+
        				IJ.d2s(patternParameters.gridGeometry[v][u][1],2)+","+
        				IJ.d2s(patternParameters.gridGeometry[v][u][2],2)+" ("+true+") -> "+
        				IJ.d2s(node[0][0],2)+"/"+IJ.d2s(node[0][1],2));
        	}
        	if (dMode) {
Andrey Filippov's avatar
Andrey Filippov committed
10846 10847
//        		double []pXY=node[0]; // px,py values
        		this.gridOnSensor[v][u][0][0]=node[0][0];
Andrey Filippov's avatar
Andrey Filippov committed
10848 10849 10850 10851 10852 10853 10854 10855
        		this.gridOnSensor[v][u][1][0]=node[0][1];
        		for (int j=1;j<15;j++) {  // was 14
        			this.lensDistortionParameters.setLensDistortionParameters(ldp, j, delta); // set one of the parameters (j) with added delta to ldp
                	node=this.lensDistortionParameters.calcPartialDerivatives(
                			patternParameters.gridGeometry[v][u][0],//double xp, // target point horizontal, positive - right,  mm
                			patternParameters.gridGeometry[v][u][1],//double yp, // target point vertical,   positive - down,  mm
                			patternParameters.gridGeometry[v][u][2],//double zp, // target point horizontal, positive - away from camera,  mm
                			false);
Andrey Filippov's avatar
Andrey Filippov committed
10856
            		this.gridOnSensor[v][u][0][j]=(node[0][0]-this.gridOnSensor[v][u][0][0])/delta;
Andrey Filippov's avatar
Andrey Filippov committed
10857 10858 10859 10860
            		this.gridOnSensor[v][u][1][j]=(node[0][1]-this.gridOnSensor[v][u][1][0])/delta;
        		}

        	} else for (int i=0;i<2;i++) for (int j=0;j<15;j++){ // was 14
Andrey Filippov's avatar
Andrey Filippov committed
10861
        		this.gridOnSensor[v][u][i][j]=node[j][i];
Andrey Filippov's avatar
Andrey Filippov committed
10862 10863 10864 10865 10866 10867 10868 10869 10870 10871 10872 10873 10874
        	}

        } else {
        	this.gridOnSensor[v][u]=null;
        }
        return this.gridOnSensor;
    }
    public int getGridWidth() {
    	return patternParameters.gridGeometry[0].length;
    }
    public int getGridHeight() {
    	return patternParameters.gridGeometry.length;
    }
Andrey Filippov's avatar
Andrey Filippov committed
10875

Andrey Filippov's avatar
Andrey Filippov committed
10876 10877 10878 10879 10880 10881 10882 10883 10884 10885 10886 10887 10888 10889 10890 10891 10892 10893 10894 10895 10896 10897 10898 10899 10900 10901 10902 10903 10904 10905 10906 10907 10908 10909 10910 10911 10912 10913 10914 10915 10916 10917 10918 10919 10920 10921 10922 10923 10924 10925 10926 10927 10928 10929 10930 10931 10932 10933 10934 10935 10936 10937 10938 10939 10940 10941 10942 10943 10944 10945 10946 10947 10948 10949 10950 10951
    public double [][] prepareDisplayGrid(){
    	int gridHeight=this.patternParameters.gridGeometry.length;
    	int gridWidth=this.patternParameters.gridGeometry[0].length;
    	double [][] dgrid=new double[3][gridHeight*gridWidth];
    	double average;
    	int num,index;
    	for (int i=0;i<dgrid.length;i++){
    		average=0.0;
    		num=0;
    		for (int v=0; v<gridHeight; v++) for (int u=0; u<gridWidth; u++) if (this.patternParameters.gridGeometry[v][u][3]>0) {
    			average+=this.patternParameters.gridGeometry[v][u][i];
    			num++;
    		}
    		average/=num;
    		index=0;
    		for (int v=0; v<gridHeight; v++) for (int u=0; u<gridWidth; u++) if (this.patternParameters.gridGeometry[v][u][3]>0) {
    			dgrid[i][index++]=this.patternParameters.gridGeometry[v][u][i];
    		} else {
    			dgrid[i][index++]=average;
    		}
    	}
    	return dgrid;
    }
    public String [] displayGridTitles() {
    	String [] titles={"Grid-X","Grid-Y","Grid-Z"};
    	return titles;
    }
    public String [] displayGridOnSensorTitles() {
    	String [] titles={
    			"PX","PY",
    			"dPX/dphi","dPY/dphi",
    			"dPX/dtheta","dPY/dtheta",
    			"dPX/dpsi","dPY/dpsi",
    			"dPX/dX0","dPY/dX0",
    			"dPX/dY0","dPY/dY0",
    			"dPX/dZ0","dPY/dZ0",
    			"dPX/df","dPY/df",
    			"dPX/ddist","dPY/dist",
    			"dPX/dDa","dPY/dDa",
    			"dPX/dDb","dPY/dDb",
    			"dPX/dDc","dPY/dDc",
    			"dPX/dPX0","dPY/dPX0",
    			"dPX/dPY0","dPY/dPY0"
    	};
    	return titles;
    }
    public double [][] prepareDisplayGridOnSensor(boolean showAll){
    	int gridHeight=this.patternParameters.gridGeometry.length;
    	int gridWidth=this.patternParameters.gridGeometry[0].length;
//    	double [][] dgrid=new double[showAll?28:2][gridHeight*gridWidth];
    	double [][] dgrid=new double[showAll?(2*15):2][gridHeight*gridWidth];
    	double average;
    	int num,index;
    	for (int i=0;i<dgrid.length/2;i++) for (int j=0;j<2;j++){
    		int ii=i*2+j;
    		average=0.0;
    		num=0;
    		for (int v=0; v<gridHeight; v++) for (int u=0; u<gridWidth; u++) if (this.patternParameters.gridGeometry[v][u][3]>0) {
    			average+=this.gridOnSensor[v][u][j][i];
    			num++;
    		}
    		average/=num;
    		index=0;
    		for (int v=0; v<gridHeight; v++) for (int u=0; u<gridWidth; u++) if (this.patternParameters.gridGeometry[v][u][3]>0) {
    			dgrid[ii][index++]=this.gridOnSensor[v][u][j][i];
    		} else {
    			dgrid[ii][index++]=average;
    		}
    	}
    	return dgrid;
    }
    /**
     * initialize image data with camera defaults
     * @param distortionCalibrationData grid distortionCalibrationData
     * @param eyesisCameraParameters deafault camera parameters
     */
Andrey Filippov's avatar
Andrey Filippov committed
10952

Andrey Filippov's avatar
Andrey Filippov committed
10953 10954
    // Used in Aberration_Calibration
    public void initImageSet(
10955
    		DistortionCalibrationData distortionCalibrationData,
Andrey Filippov's avatar
Andrey Filippov committed
10956
    		EyesisCameraParameters eyesisCameraParameters) {
10957
//    	DistortionCalibrationData distortionCalibrationData= new DistortionCalibrationData(filenames);
Andrey Filippov's avatar
Andrey Filippov committed
10958 10959 10960 10961 10962 10963 10964 10965 10966 10967 10968 10969
    	for (int i=0;i<distortionCalibrationData.getNumImages();i++){
    		int stationNumber=distortionCalibrationData.getImageStation(i);
    		int subCam=distortionCalibrationData.getImageSubcamera(i);
    		distortionCalibrationData.setParameters(eyesisCameraParameters.getParametersVector(stationNumber,subCam), i);
    		this.lensDistortionParameters.pixelSize=eyesisCameraParameters.getPixelSize(subCam);
    		this.lensDistortionParameters.distortionRadius=eyesisCameraParameters.getDistortionRadius(subCam);
    	}
    }
    public void copySensorConstants(EyesisCameraParameters eyesisCameraParameters) { // copy from the first channel
    		this.lensDistortionParameters.pixelSize=eyesisCameraParameters.getPixelSize(0);
    		this.lensDistortionParameters.distortionRadius=eyesisCameraParameters.getDistortionRadius(0);
    }
Andrey Filippov's avatar
Andrey Filippov committed
10970

Andrey Filippov's avatar
Andrey Filippov committed
10971 10972 10973 10974 10975 10976 10977
    /**
     * Update per-image parameters from those of the camera and those that have the same timestamp. Usually needed after adding or
     * enabling new images.
     * @param distortionCalibrationData grid distortionCalibrationData
     * @param eyesisCameraParameters - camera parameters (common and per sub-camera)
     * @return true if dialog was not canceled and programs ran
     */
Andrey Filippov's avatar
Andrey Filippov committed
10978

Andrey Filippov's avatar
Andrey Filippov committed
10979
    public boolean interactiveUpdateImageSet(
10980
    		DistortionCalibrationData distortionCalibrationData,
Andrey Filippov's avatar
Andrey Filippov committed
10981 10982
    		EyesisCameraParameters eyesisCameraParameters
    ){
10983
    	boolean resetParametersToZero=false;
10984
    	boolean updateAllSubcameras = false;
Andrey Filippov's avatar
Andrey Filippov committed
10985 10986 10987
    	boolean [] parameterMask= new boolean[distortionCalibrationData.getNumParameters()];
    	boolean [] channelMask=   new boolean[distortionCalibrationData.getNumSubCameras()];
    	boolean [] stationMask=   new boolean[distortionCalibrationData.getNumStations()];
10988 10989 10990 10991 10992
    	String [] source_stations = new String[stationMask.length+1];
    	source_stations[0] = "---";
    	for (int i = 0; i < stationMask.length; i++) {
    		source_stations[i+1]=""+i;
    	}
Andrey Filippov's avatar
Andrey Filippov committed
10993 10994 10995 10996
    	for (int i=0;i<parameterMask.length;i++) parameterMask[i]=false;
    	for (int i=0;i<channelMask.length;i++)   channelMask[i]=  true;
    	for (int i=0;i<stationMask.length;i++)   stationMask[i]=  true;
    	GenericDialog gd=new GenericDialog("Update (new) image settings from known data");
10997 10998
    	//
    	gd.addCheckbox("Reset selected parameters to zero (false - update from camera parameters)", resetParametersToZero);
10999 11000 11001
    	if (stationMask.length > 1) {
    		gd.addChoice("Copy selected parameters from tis station to all other stations" , source_stations, source_stations[0]);
    	}
11002
    	gd.addMessage("Select which individual image parameters to be updated from the camera parameters (or reset to 0)");
11003 11004 11005 11006 11007 11008
    	
    	gd.addCheckbox("Update all subcamera parameters", updateAllSubcameras);
    	
    	for (int i=0;i<parameterMask.length;i++) {
    		gd.addCheckbox(i+": "+distortionCalibrationData.getParameterName(i), parameterMask[i]);
    	}
Andrey Filippov's avatar
Andrey Filippov committed
11009 11010 11011 11012 11013 11014 11015 11016 11017 11018 11019
    	gd.addMessage("----------");
    	gd.addMessage("Select which channels (sub-cameras) to update");
    	for (int i=0;i<channelMask.length;i++) gd.addCheckbox("Subcamera "+i, channelMask[i]);
    	if (stationMask.length>1) {
        	gd.addMessage("----------");
        	gd.addMessage("Select which stations (camera/goniometer locations) to update");
        	for (int i=0;i<stationMask.length;i++) gd.addCheckbox("Station "+i, stationMask[i]);
    	}
    	gd.addMessage("----------");
    	gd.addCheckbox("Applying known extrinsic parameters to the same timestamp images", true);
    	gd.addCheckbox("Use closest (by motor steps) image if none for the same timestamp is enabled", true);
11020 11021
    	gd.addMessage("==== Note: The following correction will be applied to all subcameras, use selection above to specify which heights should be averaged" );
    	gd.addCheckbox("Vertically center the camera head by calculateing center above horizontal", false);
Andrey Filippov's avatar
Andrey Filippov committed
11022 11023 11024 11025
//    	gd.addCheckbox("Update currently disabled images", true);
	    WindowTools.addScrollBars(gd);
    	gd.showDialog();
    	if (gd.wasCanceled()) return false;
11026
    	resetParametersToZero=gd.getNextBoolean();
11027 11028 11029 11030 11031 11032
    	int source_station = -1;
    	if (stationMask.length > 1) {
    		source_station = gd.getNextChoiceIndex() - 1;
    	}

    	updateAllSubcameras = gd.getNextBoolean();
Andrey Filippov's avatar
Andrey Filippov committed
11033 11034 11035 11036 11037 11038 11039 11040
    	for (int i=0;i<parameterMask.length;i++) parameterMask[i]= gd.getNextBoolean();
    	for (int i=0;i<channelMask.length;i++)   channelMask[i]=   gd.getNextBoolean();
    	if (stationMask.length>1) {
    		for (int i=0;i<stationMask.length;i++) stationMask[i]= gd.getNextBoolean();
    	}
    	boolean updateFromTimestamps= gd.getNextBoolean();
    	boolean allowClosest=         gd.getNextBoolean();
    	boolean reCenterVertically=   gd.getNextBoolean();
11041 11042 11043 11044 11045 11046 11047 11048 11049 11050 11051 11052 11053 11054 11055 11056 11057 11058 11059

    	if (updateAllSubcameras) {
    		resetParametersToZero = false; // just for safety
        	for (int i=0;i<parameterMask.length;i++) {
        		parameterMask[i] |= distortionCalibrationData.isSubcameraParameter(i);
        	}
    	}
    	
    	if (source_station >= 0) {
    		updateOtherStations(
    	    		eyesisCameraParameters,
    	    		source_station,
    	    		parameterMask,
    	    		channelMask,
    	    		stationMask);    		
    	}
    	
    	
    	
Andrey Filippov's avatar
Andrey Filippov committed
11060 11061 11062
    	if (reCenterVertically){
    		eyesisCameraParameters.recenterVertically(channelMask, stationMask);
    		for (int i=0;i<channelMask.length;i++) channelMask[i]= true;
11063
    		parameterMask[distortionCalibrationData.getParameterIndexByName("subcamHeight")] = true;
Andrey Filippov's avatar
Andrey Filippov committed
11064 11065
    	}

Andrey Filippov's avatar
Andrey Filippov committed
11066

Andrey Filippov's avatar
Andrey Filippov committed
11067 11068
//		boolean updateDisabled=       gd.getNextBoolean();
    	updateImageSetFromCamera(
11069
    			resetParametersToZero,
Andrey Filippov's avatar
Andrey Filippov committed
11070 11071 11072 11073 11074 11075 11076 11077 11078 11079 11080 11081 11082
    			distortionCalibrationData,
    			eyesisCameraParameters,
    			parameterMask, //boolean [] parameterMask,
    			channelMask, // copy X,Y,Z (usually true)
    			stationMask // copy 2 goniometer angles (usually false)
    	);
    	if (updateFromTimestamps) {
    		updateImageSetFromSameTimestamps(
    				distortionCalibrationData,
    				eyesisCameraParameters,
    				null, // boolean [] selectedImages,
    				null, //boolean [] parameterMask,
    				allowClosest
Andrey Filippov's avatar
Andrey Filippov committed
11083
    				//,updateDisabled
Andrey Filippov's avatar
Andrey Filippov committed
11084 11085 11086 11087 11088
    		);
    		distortionCalibrationData.updateSetOrientation(null); // update orientation of image sets
    	}
    	return true;
    }
Andrey Filippov's avatar
Andrey Filippov committed
11089

Andrey Filippov's avatar
Andrey Filippov committed
11090 11091 11092 11093
    public boolean setSetFromClosestAndEstimateOrientation(
    		int numSet,
    		boolean [] selectedImages,
    		boolean [] parameterMask,
11094
    		DistortionCalibrationData distortionCalibrationData,
Andrey Filippov's avatar
Andrey Filippov committed
11095 11096 11097 11098 11099 11100 11101 11102 11103 11104 11105 11106 11107 11108 11109 11110 11111 11112 11113 11114 11115 11116 11117 11118 11119 11120 11121
    		EyesisCameraParameters eyesisCameraParameters){
    	if (selectedImages==null) {
    		selectedImages= new boolean[distortionCalibrationData.getNumImages()];
    		for (int i=0;i<selectedImages.length;i++) selectedImages[i]=distortionCalibrationData.gIP[i].enabled;
    	}
    	if (parameterMask==null) {
    		parameterMask= new boolean[distortionCalibrationData.getNumParameters()];
    		for (int i=0;i<parameterMask.length;i++) parameterMask[i]=true;
    	}
    	for (int i=0;i<parameterMask.length;i++) {
    		if (distortionCalibrationData.isSubcameraParameter(i))    	parameterMask[i]=false;
    	}

    	int enabledImage=getClosestImage( // {numEnabledSet,enabledChannel,enabledImage};
	    		distortionCalibrationData,
	    		selectedImages,
	    		numSet);
    	if (enabledImage<0) return false; // failed to find closest
		updateSetFromClosest(
				numSet,
				enabledImage,
				parameterMask,
				distortionCalibrationData);
		// invalidate current angles
		distortionCalibrationData.gIS[numSet].goniometerAxial=Double.NaN;
		distortionCalibrationData.gIS[numSet].goniometerTilt= Double.NaN;
		// re-estimate orientation
11122
		double [] ta=distortionCalibrationData.getImagesetTiltAxial(distortionCalibrationData.gIS[numSet].timeStamp); // updates tilt/axial (now interAxis too!)
Andrey Filippov's avatar
Andrey Filippov committed
11123 11124 11125
	    if ((ta==null) || Double.isNaN(ta[0]) || Double.isNaN(ta[1])) return false;
	    return true;
    }
Andrey Filippov's avatar
Andrey Filippov committed
11126

Andrey Filippov's avatar
Andrey Filippov committed
11127 11128

    public boolean interactiveUpdateImageSetOld(
11129
    		DistortionCalibrationData distortionCalibrationData,
Andrey Filippov's avatar
Andrey Filippov committed
11130 11131 11132 11133 11134 11135 11136 11137 11138 11139 11140 11141 11142 11143 11144 11145 11146 11147 11148
    		EyesisCameraParameters eyesisCameraParameters
    ){
    	GenericDialog gd=new GenericDialog("Update (new) image settings from known data");
    	gd.addCheckbox("Update per-image parameters from those of the camera", true);
    	gd.addCheckbox("Copy location of the camera (X,Y,Z)", true);
    	gd.addCheckbox("Copy orientation of the camera (tilt and axial)", false);
    	gd.addMessage("");
    	gd.addCheckbox("Update per-image parameters from those with the same timestamp", true);
    	gd.addCheckbox("Use closest (by motor steps) image if none for the same timestamp is enabled", true);
//    	gd.addCheckbox("Update currently disabled images", true);

    	gd.showDialog();
    	if (gd.wasCanceled()) return false;
    	boolean updateFromCamera=     gd.getNextBoolean();
    	boolean copyLocation=         gd.getNextBoolean();
    	boolean copyOrientation=      gd.getNextBoolean();
    	boolean updateFromTimestamps= gd.getNextBoolean();
    	boolean allowClosest=         gd.getNextBoolean();
//		boolean updateDisabled=       gd.getNextBoolean();
Andrey Filippov's avatar
Andrey Filippov committed
11149

Andrey Filippov's avatar
Andrey Filippov committed
11150 11151 11152 11153 11154 11155
    	boolean [] parameterMask= new boolean[distortionCalibrationData.getNumParameters()];
    	for (int i=0;i<parameterMask.length;i++) {
    		parameterMask[i]=true;
    		if (distortionCalibrationData.isLocationParameter(i)    && !copyLocation)    	parameterMask[i]=false;
    		if (distortionCalibrationData.isOrientationParameter(i) && !copyOrientation)	parameterMask[i]=false;
    	}
Andrey Filippov's avatar
Andrey Filippov committed
11156

Andrey Filippov's avatar
Andrey Filippov committed
11157
    	if (updateFromCamera) updateImageSetFromCamera(
11158
    			false, //resetParametersToZero
Andrey Filippov's avatar
Andrey Filippov committed
11159 11160 11161 11162 11163 11164 11165 11166 11167 11168 11169 11170 11171 11172 11173 11174 11175 11176 11177
    			distortionCalibrationData,
    			eyesisCameraParameters,
    			parameterMask, //boolean [] parameterMask,
    			null,
    			null
    	);
    	if (updateFromTimestamps) {
    		updateImageSetFromSameTimestamps(
    				distortionCalibrationData,
    				eyesisCameraParameters,
    				null, // boolean [] selectedImages,
    				null, //boolean [] parameterMask,
    				allowClosest
//    				,updateDisabled
    		);
    		distortionCalibrationData.updateSetOrientation(null); // update orientation of image sets
    	}
    	return true;
    }
Andrey Filippov's avatar
Andrey Filippov committed
11178

11179 11180 11181 11182 11183 11184 11185 11186 11187 11188 11189 11190 11191 11192 11193 11194 11195 11196 11197 11198 11199 11200 11201 11202 11203 11204 11205 11206 11207 11208 11209 11210
    
    /**
     * Update selected parameters from sourceStation to selected (stationMask) stations, filtered by channelMask
     * @param eyesisCameraParameters
     * @param sourceStation
     * @param parameterMask
     * @param channelMask
     * @param stationMask
     */
    public void updateOtherStations(
    		EyesisCameraParameters eyesisCameraParameters,
    		int                    sourceStation,
    		boolean []             parameterMask,
    		boolean []             channelMask,
    		boolean []             stationMask
    		) {
    	for (int stationNumber = 0; stationNumber <  stationMask.length; stationNumber++) if (stationMask[stationNumber]) {
    		for (int subCam=0; subCam < channelMask.length; subCam++) if (channelMask[subCam]) {
        		double [] oldVector=eyesisCameraParameters.getParametersVector(stationNumber,subCam);
        		double [] newVector=eyesisCameraParameters.getParametersVector(sourceStation,subCam);
        		for (int j=0;j<oldVector.length;j++) if (parameterMask[j]){
        			oldVector[j]=newVector[j];
        		}
    			eyesisCameraParameters.setParametersVector(
    					newVector,
    					parameterMask,
    					stationNumber,
    					subCam);
    		}
    	}
    }
    
Andrey Filippov's avatar
Andrey Filippov committed
11211

Andrey Filippov's avatar
Andrey Filippov committed
11212 11213 11214 11215 11216 11217 11218 11219 11220
    /**
     * Copies selected parameters from the camera parameters to per-image parameters (i.e. for new/previously disabled images)
     * @param distortionCalibrationData grid distortionCalibrationData
     * @param eyesisCameraParameters - camera parameters (common and per sub-camera)
     * @param parameterMask when element is true - copy parameters, false - keep current value. Null - selects all (filtered by the next parameters)
     * @param copyLocation copy location (x,Y,Z) of the camera , normally should be true
     * @param copyOrientation copy 2 goniometer angles, normally should be false
     */
    public void updateImageSetFromCamera(
11221
    		boolean resetParametersToZero, // reset to 0 instead of camera parameters
11222
    		DistortionCalibrationData distortionCalibrationData,
Andrey Filippov's avatar
Andrey Filippov committed
11223 11224 11225 11226
    		EyesisCameraParameters eyesisCameraParameters,
    		boolean [] parameterMask,
    		boolean [] channelMask,
    		boolean [] stationMask
Andrey Filippov's avatar
Andrey Filippov committed
11227
    		) {
11228
//    	DistortionCalibrationData distortionCalibrationData= new DistortionCalibrationData(filenames);
Andrey Filippov's avatar
Andrey Filippov committed
11229 11230 11231 11232 11233 11234 11235
    	for (int i=0;i<distortionCalibrationData.getNumImages();i++){
    		int stationNumber=distortionCalibrationData.getImageStation(i);
    		int subCam=distortionCalibrationData.getImageSubcamera(i);
    		if ((channelMask!=null) && !channelMask[subCam])        continue;
    		if ((stationMask!=null) && !stationMask[stationNumber]) continue;
    		double [] oldVector=distortionCalibrationData.getParameters(i);
    		double [] newVector=eyesisCameraParameters.getParametersVector(stationNumber,subCam);
11236 11237 11238 11239 11240 11241 11242 11243 11244 11245 11246
    		for (int j=0;j<oldVector.length;j++) if (parameterMask[j]){
    			if (resetParametersToZero) newVector[j]=0.0;
    			oldVector[j]=newVector[j];
    		}
    		if (resetParametersToZero){
    			eyesisCameraParameters.setParametersVector(
    					newVector,
    					parameterMask,
    					stationNumber,
    					subCam);
    		}
Andrey Filippov's avatar
Andrey Filippov committed
11247 11248 11249 11250 11251 11252 11253 11254 11255 11256 11257 11258 11259 11260 11261
    		distortionCalibrationData.setParameters(oldVector, i);
    		this.lensDistortionParameters.pixelSize=eyesisCameraParameters.getPixelSize(subCam);
    		this.lensDistortionParameters.distortionRadius=eyesisCameraParameters.getDistortionRadius(subCam);
    	}
    }
    /**
     * Copies selected (normally all) parameters from the selected images with the same timestamp (i.e. for new/previously disabled images)
     * @param distortionCalibrationData grid distortionCalibrationData
     * @param eyesisCameraParameters - camera parameters (common and per sub-camera)
     * @param selectedImages Use only selected images (null - all enabled)
     * @param parameterMask when element is true - copy parameters, false - keep current value. Null - selects all (and should be normally null)
     * @param allowClosest If there is no enabled image for the current timestamp, find the closest selected using motor coordinates
     * @param updateDisabled update disable images also
     */
    public void updateImageSetFromSameTimestamps(
11262
    		DistortionCalibrationData distortionCalibrationData,
Andrey Filippov's avatar
Andrey Filippov committed
11263 11264 11265 11266 11267 11268 11269 11270 11271 11272 11273 11274 11275 11276 11277 11278 11279 11280 11281 11282 11283 11284
    		EyesisCameraParameters eyesisCameraParameters,
    		boolean [] selectedImages,
    		boolean [] parameterMask,
    		boolean allowClosest
    		){
		System.out.println("updateImageSetFromSameTimestamps(), allowClosest="+allowClosest); //+" updateDisabled="+updateDisabled);
    	if (selectedImages==null) {
    		selectedImages= new boolean[distortionCalibrationData.getNumImages()];
    		for (int i=0;i<selectedImages.length;i++) selectedImages[i]=distortionCalibrationData.gIP[i].enabled;
//    		for (int i=0;i<selectedImages.length;i++) selectedImages[i]=distortionCalibrationData.gIP[i].enabled || updateDisabled;
    	}
    	if (parameterMask==null) {
    		parameterMask= new boolean[distortionCalibrationData.getNumParameters()];
    		for (int i=0;i<parameterMask.length;i++) parameterMask[i]=true;
    	}
    	for (int i=0;i<parameterMask.length;i++) {
    		if (distortionCalibrationData.isSubcameraParameter(i))    	parameterMask[i]=false;
    	}
    	for (int numSet=0; numSet<distortionCalibrationData.gIS.length;numSet++){
// find enabled image for this set
    		int enabledImage=-1;
    		// look for enabled image in the same imageSet
Andrey Filippov's avatar
Andrey Filippov committed
11285

Andrey Filippov's avatar
Andrey Filippov committed
11286 11287 11288 11289 11290 11291 11292 11293 11294 11295 11296 11297 11298 11299 11300 11301 11302 11303 11304 11305 11306 11307 11308 11309
    		for (int nChn=0;nChn<distortionCalibrationData.gIS[numSet].imageSet.length;nChn++) if (distortionCalibrationData.gIS[numSet].imageSet[nChn]!=null){
    			int img=distortionCalibrationData.gIS[numSet].imageSet[nChn].imgNumber;
    			if (selectedImages[img]){
        			enabledImage=img;
    				break;
    			}
    		}
    		// look for closest in the other imageSet
    		if ((enabledImage<0) && (allowClosest)){
    			enabledImage=getClosestImage( // {numEnabledSet,enabledChannel,enabledImage};
    			    		distortionCalibrationData,
    			    		selectedImages,
    			    		numSet);
    		}
    		if (enabledImage>=0){
    			updateSetFromClosest(
    					numSet,
    					enabledImage,
    					parameterMask,
    					distortionCalibrationData);
    		}
    	}

    }
Andrey Filippov's avatar
Andrey Filippov committed
11310

Andrey Filippov's avatar
Andrey Filippov committed
11311
    public int getClosestImage(
11312
    		DistortionCalibrationData distortionCalibrationData,
Andrey Filippov's avatar
Andrey Filippov committed
11313 11314 11315 11316 11317 11318 11319 11320 11321 11322 11323 11324 11325 11326
    		boolean [] selectedImages,
    		int numSet
    ){
    	int enabledChannel=-1;
    	int enabledImage=-1;
    	if (distortionCalibrationData.gIS[numSet].motors==null ){
    		if (this.debugLevel>0) System.out.println("getClosestSetChannelImage(): No motor data for timestamp "+distortionCalibrationData.gIS[numSet].timeStamp);
    		return -1;
    	}
    	double d2Min=-1;
    	for (int numOtherSet=0;numOtherSet<distortionCalibrationData.gIS.length;numOtherSet++)
    		if ((numOtherSet!=numSet) &&
    				(distortionCalibrationData.gIS[numOtherSet].stationNumber==distortionCalibrationData.gIS[numSet].stationNumber) &&
    				(distortionCalibrationData.gIS[numOtherSet].motors!=null) &&
Andrey Filippov's avatar
Andrey Filippov committed
11327
    				(distortionCalibrationData.gIS[numOtherSet].imageSet!=null)
Andrey Filippov's avatar
Andrey Filippov committed
11328 11329 11330 11331 11332 11333 11334 11335 11336 11337 11338 11339 11340 11341 11342 11343 11344 11345 11346 11347 11348 11349 11350 11351 11352 11353 11354 11355 11356 11357
    		) {
    			enabledChannel=-1;
    			int otherImage=-1;
    			for (int nChn=0;nChn<distortionCalibrationData.gIS[numOtherSet].imageSet.length;nChn++)
    				if (distortionCalibrationData.gIS[numOtherSet].imageSet[nChn]!=null){
    					otherImage=distortionCalibrationData.gIS[numOtherSet].imageSet[nChn].imgNumber;
    					if (selectedImages[otherImage]){
    						enabledChannel=nChn;
    						break;
    					}
    				}
    			if (enabledChannel>=0){
    				double d2=0;
    				for (int k=0;k<distortionCalibrationData.gIS[numOtherSet].motors.length;k++){
    					d2+=1.0*(distortionCalibrationData.gIS[numOtherSet].motors[k]-distortionCalibrationData.gIS[numSet].motors[k])*
    					(distortionCalibrationData.gIS[numOtherSet].motors[k]-distortionCalibrationData.gIS[numSet].motors[k]);
    				}
    				if ((d2Min<0) || (d2Min>d2)) {
    					d2Min=d2;
    					enabledImage=otherImage;
    				}
    			}
    		}
    	return enabledImage;
    }

    public void updateSetFromClosest(
    		int numSet,
    		int enabledImage,
    		boolean [] parameterMask,
11358
    		DistortionCalibrationData distortionCalibrationData
Andrey Filippov's avatar
Andrey Filippov committed
11359
    		){
11360
		int numEnabledSet=distortionCalibrationData.gIP[enabledImage].getSetNumber();
Andrey Filippov's avatar
Andrey Filippov committed
11361 11362
		distortionCalibrationData.gIS[numSet].setSetVector(distortionCalibrationData.gIS[numEnabledSet].getSetVector());
		System.out.println("getClosestSetChannelImage(): imageSet "+numSet+" set orientationEstimated=true, updated from imageSet "+numEnabledSet);
Andrey Filippov's avatar
Andrey Filippov committed
11363
		distortionCalibrationData.gIS[numSet].orientationEstimated=(numSet!=numEnabledSet);
Andrey Filippov's avatar
Andrey Filippov committed
11364 11365 11366 11367 11368 11369 11370 11371 11372
		double [] newVector=distortionCalibrationData.getParameters(enabledImage);
		for (int nChn=0;nChn<distortionCalibrationData.gIS[numSet].imageSet.length;nChn++)
			if (distortionCalibrationData.gIS[numSet].imageSet[nChn]!=null){ // will copy back to itself, OK
				int targetImage=distortionCalibrationData.gIS[numSet].imageSet[nChn].imgNumber;
				double [] oldVector=distortionCalibrationData.getParameters(targetImage);
				for (int j=0;j<oldVector.length;j++) if (parameterMask[j]) oldVector[j]=newVector[j];
				distortionCalibrationData.setParameters(oldVector, targetImage);
			}
    }
Andrey Filippov's avatar
Andrey Filippov committed
11373

Andrey Filippov's avatar
Andrey Filippov committed
11374 11375 11376 11377 11378 11379 11380 11381 11382 11383 11384 11385
    // TODO: Add updating to all Stations depending on type of adjustment. Initially only teh same station as image will be updated
    // Not needed - for "super" unselected images are also updated
    /**
     * Update camera/subcamera parameters from the currently selected set of images
     * several images may have different values for the same parameter, in that case
     * these parameters will have the value of the last image
     */
    public void updateCameraParametersFromCalculated(
    		boolean allImages ){
    	int numSeries=allImages?(-1):this.fittingStrategy.currentSeriesNumber;
		boolean [] selectedImages=fittingStrategy.selectedImages(numSeries); // all enabled
		boolean [] selectedImagesDebug=null;
11386 11387 11388 11389
		boolean include_disabled = allImages;
		if (include_disabled) {
			Arrays.fill(selectedImages, true);
		}
Andrey Filippov's avatar
Andrey Filippov committed
11390 11391
		boolean debugThis=false;
		int maxDebugImages=10;
11392
		if (this.debugLevel>0) System.out.println("updateCameraParametersFromCalculated("+allImages+")");
Andrey Filippov's avatar
Andrey Filippov committed
11393 11394 11395 11396 11397 11398 11399 11400 11401 11402 11403 11404 11405 11406 11407 11408 11409 11410
		if (this.debugLevel>2){
			int numSel=0;
			for (int i=0;i<selectedImages.length;i++) if (selectedImages[i]) numSel++;
			if (numSel<=maxDebugImages) debugThis=true;
			else {
				System.out.println ("Too many images ("+numSel+">"+ maxDebugImages +") to debug, skipping console println.");
				selectedImagesDebug=fittingStrategy.selectedImages(this.fittingStrategy.currentSeriesNumber); // all enabled

			}
		}
		for (int numImg=0;numImg<selectedImages.length; numImg++) if (selectedImages[numImg]){ // here only adjusted images should participate
			int subCam=fittingStrategy.distortionCalibrationData.getImageSubcamera(numImg);
//			double [] par=fittingStrategy.distortionCalibrationData.pars[numImg];
			double [] par=fittingStrategy.distortionCalibrationData.getParameters(numImg);
    		boolean [] update=new boolean[par.length];
    		for (int i=0;i<update.length;i++) update[i]=true;
    		int stationNumber=fittingStrategy.distortionCalibrationData.getImageStation(numImg);
    		// TODO: maybe determine - which parameters to be updated, not all - i.e. "super-common", or having the same value, etc.
Andrey Filippov's avatar
Andrey Filippov committed
11411
    		// but all those intrinsic are required to match calibration files saved
Andrey Filippov's avatar
Andrey Filippov committed
11412 11413 11414
			fittingStrategy.distortionCalibrationData.eyesisCameraParameters.setParametersVector(par, update, stationNumber, subCam);
			if (debugThis || ((selectedImagesDebug!=null) && selectedImagesDebug[numImg])){
				System.out.println ("Updating from image #"+numImg+" (subCam="+subCam+" stationNumber="+stationNumber+"):");
Andrey Filippov's avatar
Andrey Filippov committed
11415
//getParameterName
Andrey Filippov's avatar
Andrey Filippov committed
11416 11417 11418 11419
				for (int i=0;i<par.length;i++){
					System.out.println(i+": "+fittingStrategy.distortionCalibrationData.getParameterName(i)+" = "+par[i]);
				}
			}
11420
//			System.out.println(numImg+"[21]: "+fittingStrategy.distortionCalibrationData.getParameterName(21)+" = "+par[21]);
Andrey Filippov's avatar
Andrey Filippov committed
11421 11422 11423 11424 11425
		}
		if (this.debugLevel>1) System.out.println("updateCameraParametersFromCalculated("+allImages+") for series="+numSeries);
		// Next line is not needed anymore (will harm as will set orientationEstimated for all unselected sets)
//		if (!allImages) fittingStrategy.distortionCalibrationData.updateSetOrientation(selectedImages); // only for selected images (not all enabled), OK
    }
Andrey Filippov's avatar
Andrey Filippov committed
11426
	/* Create a Thread[] array as large as the number of processors available.
Andrey Filippov's avatar
Andrey Filippov committed
11427 11428 11429 11430 11431 11432 11433 11434
	 * 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
11435
/* Start all given threads and wait on each of them until all are done.
Andrey Filippov's avatar
Andrey Filippov committed
11436 11437 11438 11439 11440 11441 11442 11443 11444 11445 11446 11447
	 * 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 static void startAndJoin(Thread[] threads)
	{
		for (int ithread = 0; ithread < threads.length; ++ithread)
		{
			threads[ithread].setPriority(Thread.NORM_PRIORITY);
			threads[ithread].start();
		}

		try
Andrey Filippov's avatar
Andrey Filippov committed
11448
		{
Andrey Filippov's avatar
Andrey Filippov committed
11449 11450 11451 11452 11453 11454 11455
			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
11456
}
Andrey Filippov's avatar
Andrey Filippov committed
11457