/*******************************************************************************
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 * 
 * This library 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 Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
 * USA
 * 
 * Contact Info:
 * 	Bruce Donald
 * 	Duke University
 * 	Department of Computer Science
 * 	Levine Science Research Center (LSRC)
 * 	Durham
 * 	NC 27708-0129 
 * 	USA
 * 	brd@cs.duke.edu
 * 
 * Copyright (C) 2011 Jeffrey W. Martin and Bruce R. Donald
 * 
 * <signature of Bruce Donald>, April 2011
 * Bruce Donald, Professor of Computer Science
 ******************************************************************************/


package edu.duke.donaldLab.jdshot.test.disco;

import java.awt.BasicStroke;
import java.awt.Color;
import java.io.File;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map.Entry;

import org.jfree.chart.JFreeChart;

import edu.duke.donaldLab.jdshot.chart.ChartFactory;
import edu.duke.donaldLab.jdshot.chart.ChartWriter;
import edu.duke.donaldLab.jdshot.chart.GeometryDataset;
import edu.duke.donaldLab.jdshot.chart.GeometryRenderer;
import edu.duke.donaldLab.jdshot.chart.GeometryType;
import edu.duke.donaldLab.jdshot.context.DistanceRestraintsContext;
import edu.duke.donaldLab.jdshot.context.RdcsContext;
import edu.duke.donaldLab.jdshot.context.SymmetryContext;
import edu.duke.donaldLab.jdshot.disco.AnnulusCalculator;
import edu.duke.donaldLab.jdshot.disco.AnnulusIndex;
import edu.duke.donaldLab.jdshot.disco.FaceInfo;
import edu.duke.donaldLab.jdshot.disco.OrientationCalculator;
import edu.duke.donaldLab.jdshot.disco.PositionCalculator;
import edu.duke.donaldLab.jdshot.disco.ResultsReader;
import edu.duke.donaldLab.jdshot.disco.AnnulusIndex.AnnulusEntry;
import edu.duke.donaldLab.jdshot.disco.cgal.Arrangement;
import edu.duke.donaldLab.jdshot.disco.cgal.Face;
import edu.duke.donaldLab.jdshot.disco.cgal.ShotCgal;
import edu.duke.donaldLab.jdshot.grid.Symmetry;
import edu.duke.donaldLab.jdshot.test.ExtendedTestCase;
import edu.duke.donaldLab.share.geom.Vector3;
import edu.duke.donaldLab.share.nmr.AlignmentTensor;
import edu.duke.donaldLab.share.nmr.Assignment;
import edu.duke.donaldLab.share.nmr.DistanceRestraint;
import edu.duke.donaldLab.share.perf.Progress;
import edu.duke.donaldLab.share.protein.AtomAddressInternal;

public class TestPerformance extends ExtendedTestCase
{
	public void testChart( )
	throws Exception
	{
		// build the dataset
		GeometryDataset dataset = new GeometryDataset();
		GeometryRenderer renderer = new GeometryRenderer();
		List<FaceInfo> msrs = new ResultsReader().readMsrs( new File( "src/resources/test/2KDC.searchResults.dat" ) );
		dataset.addSeries( "MSRs", GeometryType.Face, msrs );
		renderer.setSeriesStyle( dataset.getLastSeries(), null, Color.blue, new BasicStroke( 2.0f ) );
		
		JFreeChart chart = ChartFactory.createGeometryChart(
			"",
			"Angstroms",
			"Angstroms",
			renderer,
			dataset
		);
		
		File tempFile = File.createTempFile( "chart", "file" );
		ChartWriter.writePng( chart, tempFile );
		ChartWriter.writeEps( chart, tempFile );
		ChartWriter.writeSvg( chart, tempFile );
		tempFile.delete();
	}
	
	public void XtestPerformance( )
	throws Exception
	{
		// read inputs
		SymmetryContext symmetryContext = new SymmetryContext( Symmetry.Cn, new File( "src/resources/test/2KDC.monomer.protein" ), 3 );
		RdcsContext rdcsContext = new RdcsContext( symmetryContext, "src/resources/test/2KDC.experimental.rdc" );
		DistanceRestraintsContext distanceRestraintsContext = new DistanceRestraintsContext( symmetryContext, "src/resources/test/2KDC.experimental.onlyDisulfideBonds.noe" );

		// debug mode library
		// 	base time: 34.40s
		// 	only isUnboundedSide(): 22.88s
		// release mode library
		// 	base time: 10.40s
		// 	only isUnboundedSide(): 8.11s
		
		ShotCgal.init();
		try
		{
			// previous steps
			AlignmentTensor tensor = AlignmentTensor.compute( symmetryContext.getMonomer(), rdcsContext.getInternalRdcs() );
			Vector3 orientation = OrientationCalculator.computeOrientations( 3, tensor ).get( 0 );
			OrientationCalculator.normalizeProtein( symmetryContext.getMonomer(), orientation );
			AnnulusIndex annulusIndex = AnnulusCalculator.computeAnnuli( symmetryContext.getMonomer(), distanceRestraintsContext.getInternalRestraints(), 3 );
			
			// build and check the arrangement
			Arrangement arrangement = PositionCalculator.computeArrangementIncremental( Arrays.asList( annulusIndex ) );
			assertEquals( 1458, arrangement.getNumFaces() );
			
			// imitate the MSR computation
			boolean[] satisfiedRestraints = new boolean[annulusIndex.getNumRestraints()];
			System.out.println( "Performance test on " + arrangement.getNumFaces() + " faces..." );
			Progress progress = new Progress( arrangement.getNumFaces(), 1000 );
			for( Face face : arrangement )
			{
				// skip the unbounded face
				if( face.isUnbounded() )
				{
					continue;
				}
				
				// assume all restraints are satisfied until proven otherwise
				for( int i=0; i<annulusIndex.getNumRestraints(); i++ )
				{
					satisfiedRestraints[i] = true;
				}
				
				// for each distance restraint...
				for( Entry<DistanceRestraint<AtomAddressInternal>,HashMap<Assignment<AtomAddressInternal>,AnnulusEntry>> entry : annulusIndex )
				{
					for( AnnulusEntry annulusEntry : entry.getValue().values() )
					{
						isFaceInAnnulus( face, annulusEntry );
					}
				}
				
				// to keep memory usage low
				ShotCgal.cleanupUnreferenced();
				
				progress.incrementProgress();
			}
		}
		finally
		{
			ShotCgal.cleanup();
		}
	}
	
	private static boolean isFaceInAnnulus( Face face, AnnulusEntry entry )
	{
		if( entry.outerCircle == null )
		{
			return false;
		}
		
		if( entry.outerCircle.isOnUnboundedSide( face ) )
		{
			return false;
		}
		
		if( entry.innerCircle != null )
		{
			if( entry.innerCircle.isOnBoundedSide( face ) )
			{
				return false;
			}
		}
		
		return true;
	}
}
