/*******************************************************************************
 * Copyright (c) 2010 Attila Kovacs <attila_kovacs@post.harvard.edu>.
 * All rights reserved. 
 * 
 * This file is part of crush.
 * 
 *     crush is free software: you can redistribute it and/or modify
 *     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.
 * 
 *     crush 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 crush.  If not, see <http://www.gnu.org/licenses/>.
 * 
 * Contributors:
 *     Attila Kovacs <attila_kovacs@post.harvard.edu> - initial API and implementation
 ******************************************************************************/

// Copyright (c) 2009,2010 Attila Kovacs

package crush;

import java.lang.reflect.*;
import java.util.Arrays;

import util.*;

// Gains can be linked to a channel's field, or can be internal...

public class CorrelatedMode extends Mode {
	
	public boolean fixedSignal = false;
	public int skipChannels = ~0;
	public float[] usedGains;
	
	public CorrelatedMode() {}
	
	public CorrelatedMode(ChannelGroup<?> group) {
		super(group);
	}
	
	public CorrelatedMode(ChannelGroup<?> group, Field gainField) { 
		super(group, gainField);
	}
	
	// TODO How to solve the indexing of valid channels...
	public ChannelGroup<?> getValidChannels() {
		return channels.getChannels().discard(skipChannels);		
	}
	
	// Compressing the dynamical range of gains helps arrive at the better 'mean' value
	// when the gains are scattered...
	public double dynamicalCompression = 1.0; 
	
	// Calculating an offset average (under compression) can mitigate the
	// biasing effect of many nearly blind detectors... 
	public double gainAveragingOffset = 0.0;
	
	public synchronized double normalizeGains() throws IllegalAccessException, IllegalStateException {
		if(fixedGains) throw new IllegalStateException("Correlate mode '" + name + "' has non-adjustable gains.");
		
		float[] gain = getGains();
		
		// Calculate the 5% tails of the gain distribution
		// on channels that are not flagged outside of gain...
		double[] point = new double[channels.size()];
		int n = 0;
		for(int k=0; k<channels.size(); k++) if(channels.get(k).isUnflagged(Channel.FLAG_GAIN)) 
			point[n++] = Math.abs(gain[k]);
		
		Arrays.sort(point);
		Range range = new Range();
		range.min = point[(int) Math.floor(0.05*n)];
		range.max = point[Math.max(0, (int) Math.ceil(0.95*n) - 1)];
		
		// Normalize by the mean absolute gain (w/o the 5% tails)
		// on channels not flagged outside of gain...
		double sum = 0.0, sumw = 0.0;
		for(int k=0; k<channels.size(); k++) if(range.contains(Math.abs(gain[k]))) {
			Channel channel = channels.get(k);
			if(channel.isUnflagged(~Channel.FLAG_GAIN)) { 	
				sum += Math.pow(gainAveragingOffset + Math.abs(gain[k]), dynamicalCompression);
				// It best to use equal weights, otherwise dead channels will bias gains towards 0
				sumw += 1.0;
			}
		}
		
		double aveG = 1.0;
		if(sumw > 0.0) {
			aveG = Math.pow(sum / sumw, 1.0/dynamicalCompression) - gainAveragingOffset;
			for(int k=0; k<channels.size(); k++) gain[k] /= aveG;
		}
		
		setGains(gain);
		
		return aveG;
	}
	
	public void decorrelate(Integration<?, ?> integration, boolean isRobust) {
		if(fixedSignal) throw new IllegalStateException("WARNING! Cannot decorrelate fixed signal modes.");
		try { integration.decorrelate(this, isRobust); }
		catch(IllegalAccessException e) { e.printStackTrace(); }
	}
	
	@Override
	public void getGains(Integration<?,?> integration, boolean isRobust) {
		super.getGains(integration, isRobust);
		if(!fixedSignal) {
			try { 
				double aveG = normalizeGains(); 
				Signal signal = integration.signals.get(this);
				if(signal != null) signal.scale(aveG);
			}
			catch(IllegalAccessException e) { e.printStackTrace(); }
		}
	}
	
	public void setUsedGains(float[] G) {
		// The used gains is an independent copy of the currently set values...
		if(usedGains == null) usedGains = new float[G.length];
		else if(usedGains.length != G.length) usedGains = new float[G.length];
		System.arraycopy(G, 0, usedGains, 0, G.length);
	}
	
	@Override
	public void setGains(float[] G) throws IllegalAccessException {
		setUsedGains(G);
		super.setGains(G);
	}
	
}
