Esempio n. 1
0
    def __init__(self, **kwargs):

        # These should go through the setters
        self.inroot = kwargs.get('inroot', DEF_INROOT)
        self.outroot = kwargs.get('outroot', DEF_OUTROOT)
        self.sweepmode = kwargs.get('sweep', False)
        self.analysis = kwargs.get('analysis', ANAL_DEFAULT)

        self._plot_dpi = kwargs.get('plot_dpi',
                                    None)  #Defaults based on matplotlibrc file
        self._plot_dim = kwargs.get('plot_dim', 'width=6cm')
        self._plot_fontsize = kwargs.get('fontsize', 18)
        # Ticksize defaults to 15 btw

        self.rname = kwargs.get('rname', '')
        self.overwrite = kwargs.get('overwrite', False)

        # Configure logger
        verbosity = kwargs.get('verbosity', 'warning')
        trace = kwargs.get('trace', False)

        # Pop kwargs['params'] for output below
        self.params = kwargs.pop('params', None)

        # Add logging later; consider outdirectory conflicts
        self.build_outroot()

        configure_logger(screen_level=verbosity,
                         name=__name__,
                         logfile=op.join(self.outroot, 'runlog.txt'),
                         mode='w')

        # Output the parameters
        self._run_params_file = op.join(self.outroot, 'runparameters.tex')
        with open(self._run_params_file, 'w') as f:

            # Hacky way to write latex section from raw string literals
            f.write(r'\subsection{Script Parameters}')
            f.write(r'\fboxsep5mm')
            f.write(
                r'\fcolorbox{black}{yellow}{\vbox{\hsize=10cm \noindent \scriptsize '
            )

            f.write(latex_multicols(self.params, title='PyUvVis Parameters'))
            f.write(latex_multicols(kwargs, 'Analysis Parameters'))
            f.write('}}')

        if self._plot_dpi > 600:
            logger.warn('Plotting dpi is set to %s.  > 600 may result in slow'
                        ' performance.')

        # Used for storing variables in reports/matlab other uses
        self._run_summary = ''
        self._csv_paths = []
Esempio n. 2
0
    def __init__(self, **kwargs):
              
        # These should go through the setters        
        self.inroot = kwargs.get('inroot', DEF_INROOT) 
        self.outroot = kwargs.get('outroot', DEF_OUTROOT)
        self.sweepmode = kwargs.get('sweep', False)
        self.analysis = kwargs.get('analysis', ANAL_DEFAULT)

        self._plot_dpi = kwargs.get('plot_dpi', None) #Defaults based on matplotlibrc file
        self._plot_dim = kwargs.get('plot_dim', 'width=6cm')
        self._plot_fontsize = kwargs.get('fontsize', 18)
        # Ticksize defaults to 15 btw
    
        
        self.rname = kwargs.get('rname', '')
        self.overwrite = kwargs.get('overwrite', False)
        
        # Configure logger
        verbosity = kwargs.get('verbosity', 'warning')
        trace = kwargs.get('trace', False)
                    
        # Pop kwargs['params'] for output below
        self.params = kwargs.pop('params', None)

        # Add logging later; consider outdirectory conflicts
        self.build_outroot()
        
        configure_logger(screen_level=verbosity, name = __name__,
                 logfile=op.join(self.outroot, 'runlog.txt'), mode='w')
        
        # Output the parameters
        self._run_params_file = op.join(self.outroot, 'runparameters.tex')
        with open(self._run_params_file, 'w') as f:
            
            # Hacky way to write latex section from raw string literals
            f.write(r'\subsection{Script Parameters}')
            f.write(r'\fboxsep5mm')
            f.write(r'\fcolorbox{black}{yellow}{\vbox{\hsize=10cm \noindent \scriptsize ')
  
            f.write(latex_multicols(self.params, title='PyUvVis Parameters'))
            f.write(latex_multicols(kwargs, 'Analysis Parameters'))
            f.write('}}')


        if self._plot_dpi > 600:
            logger.warn('Plotting dpi is set to %s.  > 600 may result in slow'
                       ' performance.')
            
        # Used for storing variables in reports/matlab other uses
        self._run_summary = '' 
        self._csv_paths = []
Esempio n. 3
0
import sys
import os
import os.path as op
from collections import OrderedDict

from pyuvvis.scripts.gwu_script.tex_templates import EXPERIMENT_MAIN, HEADER, \
    BLANK_SECTION

import logging
logger = logging.getLogger(__name__)
from pyuvvis.logger import log, configure_logger, logclass

from pyuvvis.scripts.gwu_script import LOGO_PATH

logger = configure_logger(name=__name__)

@logclass(public_lvl='info')
class Reporter(object):
    ''' Report is stored as an ordered dict.  Main is followed by sections. '''
    
    def __init__(self, **kwargs):
       
        self.overwrite = kwargs.get('overwrite', False)
       
        # Add main experimental body from template file or blank
        template_file = kwargs.get('template_file', None)
        if template_file:
            if not op.exists(template_file):
                raise IOError("Template file %s not found!")
            self.main_template = file(template_file, 'r').read() 
Esempio n. 4
0
import sys
import os
import os.path as op
from collections import OrderedDict

from pyuvvis.scripts.gwu_script.tex_templates import EXPERIMENT_MAIN, HEADER, \
    BLANK_SECTION

import logging
logger = logging.getLogger(__name__)
from pyuvvis.logger import log, configure_logger, logclass

from pyuvvis.scripts.gwu_script import LOGO_PATH

logger = configure_logger(name=__name__)


@logclass(public_lvl='info')
class Reporter(object):
    ''' Report is stored as an ordered dict.  Main is followed by sections. '''
    def __init__(self, **kwargs):

        self.overwrite = kwargs.get('overwrite', False)

        # Add main experimental body from template file or blank
        template_file = kwargs.get('template_file', None)
        if template_file:
            if not op.exists(template_file):
                raise IOError("Template file %s not found!")
            self.main_template = file(template_file, 'r').read()
Esempio n. 5
0
def main(args=None):

    if args:
        if isinstance(args, basestring):
            args = shlex.split(args)
        sys.argv = args

    parser = argparse.ArgumentParser(SCRIPTNAME,
                                     description='GWU PyUvVis composite'
                                     ' latex report assembly script',
                                     epilog='Additional help not found',
                                     usage='%s --globals <command> --cmdopts' %
                                     SCRIPTNAME)

    parser.add_argument('-v',
                        '--verbosity',
                        help='Set screen logging; '
                        'defaults to info.',
                        nargs='?',
                        default='warning',
                        const='info',
                        metavar='')
    parser.add_argument('-o', '--overwrite', action='store_true')

    #    parser.add_argument('-s', '--sep', metavar='',
    #                         help='Latex section separator.  Defaults to %s.  '
    #                         'Set to None to avoid auto sub-sectioning' %SEP_DEFAULT)

    # Sub Commands
    subparsers = parser.add_subparsers(title='commands', metavar='', dest='op')

    # TEMPLATE SUBCOMMAND
    p_template = subparsers.add_parser(
        'template',
        usage='%s --globals <template> outpath --opts ' % SCRIPTNAME,
        help='template help',
        epilog='PUT EXAMPLES HERE')
    p_template.add_argument(
        'outpath',
        metavar='outfile',
        help='Name of outfile (eg foo.tex or path/to/foo.tex)')

    p_template.add_argument(
        '-s',
        '--sections',
        metavar='',
        nargs='*',
        help='List of sections to add.'
        'or tree file.  If not tree file, default section template will be "template/section" '
        'section names will auto-break into subsections based on value of --sep',
        default=[])
    p_template.add_argument('-t', '--template_file', metavar='')

    # BUILD SUBCOMMAND
    p_build = subparsers.add_parser(
        'build',
        help='Adds latex doc header including '
        'begin/close document, title, author etc...',
        usage='%s --globals <build> texfile outpath --opts ' % SCRIPTNAME,
        epilog='Put examples here')
    p_build.add_argument('texfile',
                         help='Output file of %s template' % SCRIPTNAME)
    p_build.add_argument(
        'outpath',
        metavar='outfile',
        help='Name of outfile (eg foo.tex or path/to/foo.tex)')

    p_build.add_argument('--title',
                         default='Untitled',
                         metavar='',
                         help='Title '
                         ' in outfile')
    p_build.add_argument('--author',
                         default='Adam Hughes',
                         metavar='',
                         help='Author in outfile')
    p_build.add_argument('--email',
                         default='*****@*****.**',
                         metavar='',
                         help='Email in outfile')

    # Compile and open
    p_build.add_argument('--nocompile',
                         action='store_true',
                         help='Do not compile outfile'
                         ' (eg latex outfile.tex)')
    p_build.add_argument('--nopdf',
                         action='store_true',
                         help='When compiling,'
                         ' will call "latex" instead of "pdflatex"')
    p_build.add_argument('-c',
                         '--clean',
                         action='store_true',
                         help='Remove .aux, .log'
                         ' and other latex temporary files.')

    #SUMMARY SUBCOMMAND (not implemented)
    #p_summary = subparsers.add_parser('summary', help='summary help')
    #p_summary.add_argument('texfile')

    ns = parser.parse_args()

    # No logfile implemented
    configure_logger(screen_level='debug', name=__name__)
    logger.info('Namespace is: %s' % ns)

    reporter = Reporter(**ns.__dict__)  # Is this ok?

    if ns.op == 'template':
        reporter.output_template(ns.outpath)

    elif ns.op == 'build':
        reporter.make_report(ns.texfile, ns.outpath)

        # If compiling, choose pdflatex or latex
        if not ns.nocompile:

            if not ns.nopdf:
                latex_type = 'pdflatex'

            else:
                latex_type = 'latex'

            # Run latex or pdflatex twice to ensure contents load
            os.system('%s %s' % (latex_type, ns.outpath))
            os.system('%s %s' % (latex_type, ns.outpath))

        # Cleanup latex .toc/.log/.aux files of outfile
        if ns.clean:
            outdir, outname = op.split(op.abspath(ns.outpath))
            outname = op.splitext(outname)[0]
            for ext in ['toc', 'log', 'aux', 'out']:
                wastefile = op.join(outdir, outname + '.' + ext)
                if op.isfile(wastefile):
                    logger.info('Cleaning up file: "%s"' % wastefile)
                    os.remove(wastefile)

    else:
        NotImplemented
Esempio n. 6
0
def main():

    ns = parse()

    configure_logger(screen_level="info", name=__name__)
    logger.info("Logging initialized: set to info")

    outfile = op.abspath(op.join(SECTIONREPORTSDIR, OUTNAME))
    if op.exists(outfile) and not ns.overwrite:
        raise IOError("%s ALREADY EXISTS.  Remove or rerun with -o flag." % outfile)

    # Get all files; warn if directories found
    infiles = files_in_dir(SECTIONREPORTSDIR)

    ## Execute any outstanding tex files
    # if ns.runtexs:
    # texfiles = [f for f in infiles if ext(f) == '.tex']

    ## Don't run sweavetree.tex, only other tex files
    # if outfile in texfiles:
    # texfiles.remove( outfile )

    ## pdflatex on all files
    # for tf in texfiles:
    # logger.info('Twice executing "pdflatex %s"' % tf)
    ## Switch wd of auxilarry files will be written to .
    # wd = os.getcwd()
    # os.chdir(SECTIONREPORTSDIR)
    # os.system('pdflatex %s' % tf )
    # os.system('pdflatex %s' % tf )
    # os.chdir(wd)

    ## Regenerate files list as files have been udpated
    # infiles = files_in_dir(SECTIONREPORTSDIR)

    # Sort pdfs and make .tex snippet
    pdfs = [op.abspath(f) for f in infiles if ext(f) == ".pdf"]
    if not pdfs:
        raise AttributeError('NO PDFS FOUND IN "%s"' % SECTIONREPORTSDIR)
    pdfs.sort()

    # Consider making different styles
    with open(outfile, "w") as o:
        for idx, filename in enumerate(pdfs):

            # Take filename, replace '_' with '/' and remove .pdf to make section title
            # /foo/bar/f1_npsam.pdf ---> f1/npsam

            secname = op.basename(filename).replace("_", "-").replace(".pdf", "")
            outfile = op.join(SECTIONREPORTSDIR, op.basename(filename))

            if idx == 0:
                sectionheading = "\section{Sectional Data Analysis}\subsection{%s}" % secname
            else:
                sectionheading = "\subsection{%s}" % secname

            o.write("\includepdf[pages=1, offset=25 0, pagecommand=%s]{%s}\n" % (sectionheading, outfile))
            o.write("\includepdf[pages=2-,pagecommand={}]{%s}\n" % outfile)

    o.close()
    logger.info("%s written." % outfile)

    # Compile main report
    if ns.pdf:
        texfiles = [f for f in files_in_dir(".") if ext(f) == ".tex"]
        if len(texfiles) > 1:
            logger.critical(
                "There are more than one .tex files in this current" " directory.  Am not going to compile them..."
            )

        elif len(texfiles) == 0:
            logger.warn("No tex files found in current directory: --pdf option ignored use")

        else:
            maintexfile = texfiles[0]
            os.system("pdflatex %s" % maintexfile)
            os.system("pdflatex %s" % maintexfile)

    # \includepdf[pages=1,pagecommand=\section{Sectional Data Analysis}
    # \subsection{Fiber1/NPSAM}]{foo.pdf}
    # \includepdf[pages=2,pagecommand={}]{foo.pdf}

    # Clean up temporary tex files IN SWEAVESECTIONS
    if ns.clean:
        logger.warn("Removing all files of types %s in %s" % (TEMPFILES, SECTIONREPORTSDIR))
        for filename in infiles:
            if ext(filename) in TEMPFILES:
                os.remove(filename)

        logger.warn("Removing all files of types %s in CURRENT DIRECTORY" % TEMPFILES)
        for filename in files_in_dir("."):
            if ext(filename) in TEMPFILES:
                os.remove(filename)
Esempio n. 7
0
def main(args=None):
    
    if args:
        if isinstance(args, basestring):
            args=shlex.split(args)
        sys.argv = args               
    
    
    parser = argparse.ArgumentParser(SCRIPTNAME, description='GWU PyUvVis composite' 
            ' latex report assembly script', epilog='Additional help not found', 
            usage='%s --globals <command> --cmdopts' % SCRIPTNAME)    
        
    parser.add_argument('-v', '--verbosity', help='Set screen logging; '
                         'defaults to info.', nargs='?',
                         default='warning', const='info', metavar='')    
    parser.add_argument('-o', '--overwrite', action='store_true')

#    parser.add_argument('-s', '--sep', metavar='',
#                         help='Latex section separator.  Defaults to %s.  '
#                         'Set to None to avoid auto sub-sectioning' %SEP_DEFAULT)

    # Sub Commands
    subparsers = parser.add_subparsers(title='commands', metavar='', dest='op')    
    
    # TEMPLATE SUBCOMMAND
    p_template = subparsers.add_parser('template', 
        usage = '%s --globals <template> outpath --opts ' % SCRIPTNAME,    
        help='template help',
        epilog='PUT EXAMPLES HERE')
    p_template.add_argument('outpath', metavar='outfile',
        help='Name of outfile (eg foo.tex or path/to/foo.tex)')

    p_template.add_argument('-s', '--sections', metavar='', nargs='*', help='List of sections to add.'
        'or tree file.  If not tree file, default section template will be "template/section" '
        'section names will auto-break into subsections based on value of --sep',
        default=[]) 
    p_template.add_argument('-t', '--template_file', metavar='')
    
    
    
    # BUILD SUBCOMMAND
    p_build = subparsers.add_parser('build', help='Adds latex doc header including ' 
        'begin/close document, title, author etc...',
         usage = '%s --globals <build> texfile outpath --opts ' % SCRIPTNAME,    
         epilog='Put examples here')
    p_build.add_argument('texfile', help='Output file of %s template' % SCRIPTNAME)
    p_build.add_argument('outpath', metavar='outfile',
        help='Name of outfile (eg foo.tex or path/to/foo.tex)')
    
    p_build.add_argument('--title', default='Untitled', metavar='', help='Title '
                         ' in outfile')
    p_build.add_argument('--author', default='Adam Hughes', metavar='', 
                         help='Author in outfile')
    p_build.add_argument('--email', default='*****@*****.**', metavar='', 
                         help='Email in outfile')
            

    # Compile and open
    p_build.add_argument('--nocompile', action='store_true', help='Do not compile outfile'
                         ' (eg latex outfile.tex)' ) 
    p_build.add_argument('--nopdf', action='store_true', help='When compiling,' 
                         ' will call "latex" instead of "pdflatex"')
    p_build.add_argument('-c', '--clean', action = 'store_true', help='Remove .aux, .log'
        ' and other latex temporary files.')

    
    #SUMMARY SUBCOMMAND (not implemented)
    #p_summary = subparsers.add_parser('summary', help='summary help')
    #p_summary.add_argument('texfile')

    ns = parser.parse_args()
        
    # No logfile implemented
    configure_logger(screen_level='debug', name=__name__)
    logger.info('Namespace is: %s' % ns)
    
    reporter = Reporter(**ns.__dict__) # Is this ok?
    
    if ns.op == 'template':
        reporter.output_template(ns.outpath)
    
    elif ns.op == 'build':
        reporter.make_report(ns.texfile, ns.outpath)

        # If compiling, choose pdflatex or latex
        if not ns.nocompile:
         
            if not ns.nopdf:
                latex_type = 'pdflatex'

            else:
                latex_type = 'latex'
            
            # Run latex or pdflatex twice to ensure contents load    
            os.system('%s %s' % (latex_type, ns.outpath) )
            os.system('%s %s' % (latex_type, ns.outpath) )

            
        # Cleanup latex .toc/.log/.aux files of outfile
        if ns.clean:
            outdir, outname = op.split(op.abspath(ns.outpath))
            outname = op.splitext(outname)[0]
            for ext in ['toc', 'log', 'aux', 'out']:
                wastefile = op.join(outdir, outname + '.' + ext)
                if op.isfile(wastefile):
                    logger.info('Cleaning up file: "%s"' % wastefile)
                    os.remove(wastefile)
    
    else:
        NotImplemented