#!/usr/bin/env python
"""
The argus_initial_calibrate and argus_refine scripts have many options
and can be annoying to use; this provides in a single command what we 
think are the best way to go for 90% of calibrations. 

For each replicate, a subset of the boards are chosen (specified by
patterns).  An initial calibration is obtained, then it is refined in
two passes to obtain k1, k2, and k3.  Other distortion parameters by
default are fixed at 0. It is possible to have the routine shuffle
which boards are used at every refining step by using the --shuffle flag.

Results are output to a file, by default named calibrations.csv; the file
has a one line header identifying the columns.  A summary of the results
is also given on screen to show the range of parameters for all calibrations
with rmse within threshold (default 1.1) of the lowest rmse. 
"""

import argparse
import logging
import os
import argus

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Simplified calibration workflow",epilog=__doc__)

    # input file
    parser.add_argument("ifile",
                        help=".pkl file with objectPoints, imagePoints, imageSize")

    # output file
    parser.add_argument("--ofile",default=None,
                        help=".csv output file with results, default calibration.csv")

    # other settings
    parser.add_argument("--patterns",type=int,default=20,
                        help="number of patterns to use, default 20")
    parser.add_argument("--replicates",type=int,default=1000,
                        help="number of replicates to use, default 1000")
    parser.add_argument("--shuffle",action="store_true",
                        help="shuffle boards between each refinement")
    parser.add_argument("--inverted",action="store_true",
                        help="Invert pattern?")
    parser.add_argument("--verbose","-v",action="store_true",
                        help="toggle verbosity")
    args = parser.parse_args()

    
    if args.verbose:
        logging.basicConfig(level=logging.DEBUG)
        logging.debug("entering verbose mode")
    else:
        logging.basicConfig(level=logging.INFO)

    # load points
    logging.debug("loading detected patterns from {0}".format(args.ifile))
    point_inputs = argus.CalibrationInputs.from_pkl(args.ifile)
    logging.debug("using {0} patterns".format(args.patterns))
    logging.debug("inverted {0}, shuffle {1}".format(args.inverted, args.shuffle))
    calibrator = argus.Calibrator(point_inputs,args.patterns,args.inverted,args.shuffle)

    # initialize results
    logging.debug("getting {0} replicates...".format(args.replicates))
    results = []
    for replicate in range(args.replicates):
        logging.debug("getting {0}th replicate calibration".format(replicate))
        if calibrator.get_initial():
            if calibrator.refine(flags=argus.FIRSTPASS):
                if calibrator.refine(flags=argus.SECONDPASS):
                    results.append(calibrator.camera)

    # output, compute and output stats
    if args.ofile is None:
        args.ofile = os.path.join(os.path.dirname(args.ifile),"calibrations.csv")

    argus.to_csv(results,args.ofile)
    argus.summarize(args.ofile)





