
// GapPlot.java
// Andrew Davison, ad@coe.psu.ac.th, April 2023

/* Plot a graph of the first num primes (as green dots),
   overlaid with red dots to denote the prime pairs which
   are separated by the specified gap size.

   https://en.wikipedia.org/wiki/Prime_gap

   Usage:
     > compile GapPlot.java
     > run GapPlot <num primes> <gap size>
   e.g.
     > run GapPlot 100 2
     > run GapPlot 100 12
*/

import java.awt.Color;

import com.github.plot.Plot;
import com.github.plot.Plot.*;


public class GapPlot
{
  private static final int MAX_GAP = 100;

  public static void main(String[] args)
  {
    if (args.length != 2) {
      System.out.println("Usage: run GapPlot <num primes> <gap size>");
      return;
    }
    int numPrimes = Math.abs(Nut.parseInt(args[0]));
    int gapSize = Math.abs(Nut.parseInt(args[1]));

    int[] primes = Nut.loadPrimes("primes1M.txt");
    System.out.println("Loaded " + primes.length + " primes");

    if (numPrimes > primes.length)
      numPrimes = primes.length;

    // plot configuration
    Plot plot = Plot.plot( Plot.plotOpts().
                      title("Gap Primes").
                      legend(Plot.LegendFormat.RIGHT).
                      width(1300).height(500));

    plot.xAxis("x", Plot.axisOpts().
                      format(Plot.AxisFormat.NUMBER_INT));
    plot.yAxis("y", Plot.axisOpts().
                      format(Plot.AxisFormat.NUMBER_INT));

    Plot.Data plotPrimes = Plot.data();
    Plot.Data plotGaps = Plot.data();


    System.out.println(gapSize + "-gap pairs found in first " + 
                                               numPrimes + " primes:");
    int count = 0;
    for (int i = 1; i < numPrimes; i++) {
      plotPrimes.xy(primes[i], primes[i]);

      if (primes[i-1]+gapSize == primes[i]) {
        System.out.print("(" + primes[i-1] + "," + primes[i] + ") ");
        int midpt = (primes[i-1] + primes[i])/2;
        plotGaps.xy(midpt, midpt);  // show midpoint
        count++;
      }
    }
    System.out.println();
    System.out.println("Num. of pairs: " + count);

    if (count > 0) {  // plot the graph
      DataSeriesOptions primeOpts = Plot.seriesOpts().
                         line(Plot.Line.NONE).
                         marker(Plot.Marker.DIAMOND).
                         color(Color.GREEN).
                         markerColor(Color.GREEN);
     
      DataSeriesOptions twinOpts = Plot.seriesOpts().
                         line(Plot.Line.NONE).
                         marker(Plot.Marker.CIRCLE).
                         color(Color.RED).
                         markerColor(Color.RED);
     
      // add data and draw
      plot.series("Primes", plotPrimes, primeOpts);
      plot.series("Gaps (" + gapSize + ")", plotGaps, twinOpts);
     
      PlotUtils.viewPlot("Gap Primes", plot);
    }
  } /* main */

}