Display a single analysis.
17084
def analysis(analysis_id):
    """"""
    analysis_obj = store.analysis(analysis_id)
    if analysis_obj is None:
        return abort(404)

    if request.method == 'PUT':
        analysis_obj.update(request.json)
        store.commit()

    data = analysis_obj.to_dict()
    data['failed_jobs'] = [job_obj.to_dict() for job_obj in analysis_obj.failed_jobs]
    data['user'] = analysis_obj.user.to_dict() if analysis_obj.user else None
    return jsonify(**data)
930969
def check(context: click.Context, family: str):
    """"""
    analysis_obj = context.obj['store'].analyses(family=family).first()
    if analysis_obj is None:
        LOG.error('no analysis found')
        context.abort()

    config_path = Path(analysis_obj.config_path)
    if not config_path.exists():
        LOG.error(f"analysis config not found: {config_path}")
        context.abort()
    config_raw = ruamel.yaml.safe_load(config_path.open())
    config_data = files.parse_config(config_raw)

    sampleinfo_raw = ruamel.yaml.safe_load(Path(config_data['sampleinfo_path']).open())
    sampleinfo_data = files.parse_sampleinfo(sampleinfo_raw)

    qcmetrics_path = Path(sampleinfo_data['qcmetrics_path'])
    if not qcmetrics_path.exists():
        LOG.error(f"qc metrics not found: {str(qcmetrics_path)}")
        context.abort()
    qcmetrics_raw = ruamel.yaml.safe_load(qcmetrics_path.open())
    qcmetrics_data = files.parse_qcmetrics(qcmetrics_raw)

    samples = {
        'sample': [],
        'type': [],
        'ped': [],
        'chanjo': [],
        'peddy': [],
        'plink': [],
        'duplicates': [],
    }
    for sample_data in config_data['samples']:
        LOG.debug(f"{sample_data['id']}: parse analysis config")
        samples['sample'].append(sample_data['id'])
        samples['type'].append(sample_data['type'])

    for sample_data in sampleinfo_data['samples']:
        LOG.debug(f"{sample_data['id']}: parse sample info")
        samples['ped'].append(sample_data['sex'])

        with Path(sample_data['chanjo_sexcheck']).open() as chanjo_handle:
            sexcheck_data = files.parse_chanjo_sexcheck(chanjo_handle)

        predicted_sex = sexcheck_data['predicted_sex']
        xy_ratio = sexcheck_data['y_coverage'] / sexcheck_data['x_coverage']
        samples['chanjo'].append(f"{predicted_sex} ({xy_ratio:.3f})")

    for sample_data in qcmetrics_data['samples']:
        LOG.debug(f"{sample_data['id']}: parse qc metrics")
        samples['plink'].append(sample_data['plink_sex'])
        duplicates_percent = sample_data['duplicates'] * 100
        samples['duplicates'].append(f"{duplicates_percent:.3f}%")

    peddy_path = Path(sampleinfo_data['peddy']['sex_check'])
    if peddy_path.exists():
        with peddy_path.open() as sexcheck_handle:
            peddy_data = files.parse_peddy_sexcheck(sexcheck_handle)

        for sample_id in samples['sample']:
            LOG.debug(f"{sample_id}: parse peddy")
            predicted_sex = peddy_data[sample_id]['predicted_sex']
            het_ratio = peddy_data[sample_id]['het_ratio']
            samples['peddy'].append(f"{predicted_sex} ({het_ratio})")
    else:
        LOG.warning(f"missing peddy output: {peddy_path}")

    print(tabulate(samples, headers='keys', tablefmt='psql'))
1140234
def before_render(self):
        
        # If the current user is a client contact, display those analysis
        # requests that belong to same client only
        super(AnalysisRequestsView, self).before_render()
        client = api.get_current_client()
        if client:
            self.contentFilter['path'] = {
                "query": "/".join(client.getPhysicalPath()),
                "level": 0}
            # No need to display the Client column
            self.remove_column('Client')
384413
def display(self):
        
        print('Stats for %s from %s - %s' % (self.name, self.start, self.end))
        if type(self.rf) is float:
            print('Annual risk-free rate considered: %s' % (fmtp(self.rf)))
        print('Summary:')
        data = [[fmtp(self.total_return), fmtn(self.daily_sharpe),
                 fmtp(self.cagr), fmtp(self.max_drawdown)]]
        print(tabulate(data, headers=['Total Return', 'Sharpe',
                                      'CAGR', 'Max Drawdown']))

        print('\nAnnualized Returns:')
        data = [[fmtp(self.mtd), fmtp(self.three_month), fmtp(self.six_month),
                 fmtp(self.ytd), fmtp(self.one_year), fmtp(self.three_year),
                 fmtp(self.five_year), fmtp(self.ten_year),
                 fmtp(self.incep)]]
        print(tabulate(data,
                       headers=['mtd', '3m', '6m', 'ytd', '1y',
                                '3y', '5y', '10y', 'incep.']))

        print('\nPeriodic:')
        data = [
            ['sharpe', fmtn(self.daily_sharpe), fmtn(self.monthly_sharpe),
             fmtn(self.yearly_sharpe)],
            ['mean', fmtp(self.daily_mean), fmtp(self.monthly_mean),
             fmtp(self.yearly_mean)],
            ['vol', fmtp(self.daily_vol), fmtp(self.monthly_vol),
             fmtp(self.yearly_vol)],
            ['skew', fmtn(self.daily_skew), fmtn(self.monthly_skew),
             fmtn(self.yearly_skew)],
            ['kurt', fmtn(self.daily_kurt), fmtn(self.monthly_kurt),
             fmtn(self.yearly_kurt)],
            ['best', fmtp(self.best_day), fmtp(self.best_month),
             fmtp(self.best_year)],
            ['worst', fmtp(self.worst_day), fmtp(self.worst_month),
             fmtp(self.worst_year)]]
        print(tabulate(data, headers=['daily', 'monthly', 'yearly']))

        print('\nDrawdowns:')
        data = [
            [fmtp(self.max_drawdown), fmtp(self.avg_drawdown),
             fmtn(self.avg_drawdown_days)]]
        print(tabulate(data, headers=['max', 'avg', '# days']))

        print('\nMisc:')
        data = [['avg. up month', fmtp(self.avg_up_month)],
                ['avg. down month', fmtp(self.avg_down_month)],
                ['up year %', fmtp(self.win_year_perc)],
                ['12m up %', fmtp(self.twelve_month_win_perc)]]
        print(tabulate(data))
1264330
def display(self, content = None, **settings):
        
        sys.stdout.write("\r")
        sys.stdout.write(self.render(content, **settings))
        sys.stdout.flush()
1241120
def from_analysis_period(cls, analysis_period, tau_b, tau_d,
                             daylight_savings_indicator='No'):
        """""""
        _check_analysis_period(analysis_period)
        return cls(analysis_period.st_month, analysis_period.st_day, tau_b, tau_d,
                   daylight_savings_indicator)
1268822
def _ipython_display_(self):
        """"""
        contents = self.describe()
        display({  # noqa: F821
            'application/json': contents,
            'text/plain': pretty_describe(contents)
        }, metadata={
            'application/json': {'root': contents["name"]}
        }, raw=True)
157196
def _display_data(self, index):
        """"""
        return to_qvariant(self._data[index.row()][index.column()])
1225301
def run_analysis(self, argv):
        """"""
        args = self._parser.parse_args(argv)

        name_keys = dict(target_type=args.ttype,
                         target_name=args.target,
                         sim_name=args.sim,
                         fullpath=True)

        orig_dir = NAME_FACTORY.targetdir(**name_keys)
        dest_dir = NAME_FACTORY.sim_targetdir(**name_keys)
        self.copy_target_dir(orig_dir, dest_dir,
                             args.roi_baseline, args.extracopy)
1337966
def run_analysis(self, argv):
        """"""
        args = self._parser.parse_args(argv)
        obs = BinnedAnalysis.BinnedObs(irfs=args.irfs,
                                       expCube=args.expcube,
                                       srcMaps=args.cmap,
                                       binnedExpMap=args.bexpmap)

        like = BinnedAnalysis.BinnedAnalysis(obs,
                                             optimizer='MINUIT',
                                             srcModel=GtSrcmapsCatalog.NULL_MODEL,
                                             wmap=None)

        source_factory = pyLike.SourceFactory(obs.observation)
        source_factory.readXml(args.srcmdl, BinnedAnalysis._funcFactory,
                               False, True, True)

        srcNames = pyLike.StringVector()
        source_factory.fetchSrcNames(srcNames)

        min_idx = args.srcmin
        max_idx = args.srcmax
        if max_idx < 0:
            max_idx = srcNames.size()

        for i in xrange(min_idx, max_idx):
            if i == min_idx:
                like.logLike.saveSourceMaps(args.outfile)
                pyLike.CountsMapBase.copyAndUpdateDssKeywords(args.cmap,
                                                              args.outfile,
                                                              None,
                                                              args.irfs)

            srcName = srcNames[i]
            source = source_factory.releaseSource(srcName)
            like.logLike.addSource(source, False)
            like.logLike.saveSourceMap_partial(args.outfile, source)
            like.logLike.deleteSource(srcName)

        if args.gzip:
            os.system("gzip -9 %s" % args.outfile)
723050
def render_analyses_table(self, table="lab"):
        
        if table not in ["lab", "field", "qc"]:
            raise KeyError("Table '{}' does not exist".format(table))
        view_name = "table_{}_analyses".format(table)
        view = api.get_view(
            view_name, context=self.context, request=self.request)
        # Call listing hooks
        view.update()
        view.before_render()
        return view.ajax_contents_table()
493403
def display(self):
        '''
        
        '''
        w, h = (0, 0)
        for line in self.shell('dumpsys', 'display').splitlines():
            m = _DISPLAY_RE.search(line, 0)
            if not m:
                continue
            w = int(m.group('width'))
            h = int(m.group('height'))
            o = int(m.group('orientation'))
            w, h = min(w, h), max(w, h)
            return self.Display(w, h, o)

        output = self.shell('LD_LIBRARY_PATH=/data/local/tmp', self.__minicap, '-i')
        try:
            data = json.loads(output)
            (w, h, o) = (data['width'], data['height'], data['rotation']/90)
            return self.Display(w, h, o)            
        except ValueError:
            pass
618844
def display_view(self):
        """"""
        self.idx_start.setText(str(self.parent.value('window_start')))
        self.idx_length.setText(str(self.parent.value('window_length')))
        self.idx_scaling.setText(str(self.parent.value('y_scale')))
        self.idx_distance.setText(str(self.parent.value('y_distance')))
1355096
def analyze_multiple(
            benchmark_runs,
            analysis_sets = [],
            # Singleton arguments
            analysis_directory = None,
            remove_existing_analysis_directory = True,
            quick_plots = False,
            use_multiprocessing = True,
            verbose = True,
            compile_pdf = True,
            limit_to_complete_presence = True,
            all_by_all_comparisons = False,
    ):
        ''''''
        if remove_existing_analysis_directory and os.path.isdir(analysis_directory):
            shutil.rmtree(analysis_directory)

        unique_ajps = BenchmarkRun.get_unique_ajps( benchmark_runs )

        if limit_to_complete_presence:
            BenchmarkRun.get_common_subset( benchmark_runs, verbose = not use_multiprocessing )

        unique_ajps = BenchmarkRun.get_unique_ajps( benchmark_runs )

        ###  Process each benchmark run object individually
        if use_multiprocessing:
            pool = mp.Pool()
        singleton_chapters = []
        calculated_brs = []
        def save_latex_report(t):
            br, unique_name, latex_report = t
            latex_report.set_title_page( title = unique_name )
            singleton_chapters.append( latex_report )
            calculated_brs.append( br )
        for br in benchmark_runs:
            for analysis_set in analysis_sets:
                unique_name = br.get_definitive_name(unique_ajps, join_character = '\n')
                filepath_unique_name = br.get_definitive_name(unique_ajps, join_character = '-')
                subdir = os.path.join(analysis_directory, os.path.join('analysis_sets', os.path.join(analysis_set, filepath_unique_name) ) )
                if use_multiprocessing:
                    pool.apply_async( _full_analysis_mp_alias, ( br, analysis_set, subdir, unique_name, False, quick_plots ), callback = save_latex_report )
                else:
                    print 'Individual report saving in:', subdir
                    save_latex_report( _full_analysis_mp_alias( br, analysis_set, subdir, unique_name, True, quick_plots ) )
        if use_multiprocessing:
            pool.close()
            pool.join()
        benchmark_runs = calculated_brs

        ### Pointwise all-by-all comparison
        comparison_chapters = []
        if all_by_all_comparisons:
            if use_multiprocessing:
                pool = mp.Pool()
            def save_latex_report(t):
                latex_report = t
                comparison_chapters.append( latex_report )
            comparisons_subdir = os.path.join(analysis_directory, 'comparison_analysis_sets')
            for analysis_set in analysis_sets:
                analysis_set_subdir = os.path.join(comparisons_subdir, analysis_set)
                for i, br_i in enumerate(benchmark_runs):
                    for j, br_j in enumerate(benchmark_runs):
                        if i > j:
                            if use_multiprocessing:
                                br_i_copy = copy.deepcopy( br_i )
                                br_j_copy = copy.deepcopy( br_j )
                                pool.apply_async( _compare_mp_alias, (br_i_copy, br_j_copy, analysis_set, analysis_set_subdir, unique_ajps, False), callback = save_latex_report )
                            else:
                                save_latex_report( _compare_mp_alias(br_i, br_j, analysis_set, analysis_set_subdir, unique_ajps, True) )
            if use_multiprocessing:
                pool.close()
                pool.join()

        intro_report = lr.LatexReport()
        intro_report.set_title_page('All data comparison')
        # All data series comparison
        # Get joined stats comparison dataframe
        stats_df = BenchmarkRun.get_stats_comparison_dataframe(
            benchmark_runs, unique_ajps,
            output_csv = os.path.join(analysis_directory, 'analysis_metrics.csv'),
        )
        intro_report.add_section_page( title = 'Case comparison tables' )
        intro_report.content.extend( BenchmarkRun.make_case_description_tables( stats_df ) )

        intro_report.add_section_page('All data plots')
        subplot_directory = os.path.join(analysis_directory, 'subplots')
        if not os.path.isdir( subplot_directory ):
            os.makedirs(subplot_directory)
        runtime_df = benchmark_runs[0]._get_dataframe_columns( ['RunTime'] )
        runtime_df.columns = [ benchmark_runs[0].get_definitive_name(unique_ajps, join_character = '\n', prepend_label = False) ]
        for br in benchmark_runs[1:]:
            inner_runtime_df = br._get_dataframe_columns( ['RunTime'] )
            inner_runtime_df.columns = [ br.get_definitive_name(unique_ajps, join_character = '\n', prepend_label = False) ]
            runtime_df = runtime_df.merge(
                inner_runtime_df,
                left_index = True,
                right_index = True,
            )

        intro_report.add_plot(
            general_matplotlib.plot_box(
                runtime_df,
                output_directory = subplot_directory,
                plot_title = 'Prediction Run Times',
                output_name = 'runtimes',
                fig_height = 6.7,
                fig_width = 10,
                ylabel = 'Run time (minutes)',
                xlabel = 'Prediction Set',
                verbose = verbose,
                xtick_fontsize = 4,
                log_y = True,
                label_n = False,
                rotation_angle = 45,
            ),
            plot_title = 'Run times'
        )

        # Report concatenation
        main_latex_report = lr.LatexReport()
        main_latex_report.set_title_page('$\Delta\Delta G$ Report')
        main_latex_report.add_chapter(intro_report)
        for chapter in comparison_chapters:
            main_latex_report.add_chapter(chapter)
        for chapter in singleton_chapters:
            main_latex_report.add_chapter(chapter)
        main_latex_report.generate_pdf_report(
            os.path.join( analysis_directory, 'report.pdf' ),
            verbose = verbose,
            compile_pdf = compile_pdf,
        )
        print os.path.join( analysis_directory, 'report.pdf' )
477618
def display(self, sink=None, detail='phrase'):
        
        if not isinstance(detail, int):
            detail = detailNum[detail]

        if detail >= detailNum['line'] and self.size is not None:
            size = " (%s%s)" % (
                humanize(self.size),
                "" if self.exclusiveSize is None else (
                    " %s exclusive" % (humanize(self.exclusiveSize))
                )
            )
        else:
            size = ""

        vol = "%s %s" % (
            _printUUID(self._uuid, detail - 1),
            sink.getSendPath(self) if sink else "",
        )

        return vol + size
20050
def _full_analysis_mp_alias(br_obj, analysis_set, output_directory, unique_name, verbose, quick_plots):
    
    return (br_obj, unique_name, br_obj.full_analysis(analysis_set, output_directory, verbose = verbose, compile_pdf = verbose, quick_plots = quick_plots))
77769
def show(format, full):
    
    # load asset allocation
    app = AppAggregate()
    app.logger = logger
    model = app.get_asset_allocation()

    if format == "ascii":
        formatter = AsciiFormatter()
    elif format == "html":
        formatter = HtmlFormatter
    else:
        raise ValueError(f"Unknown formatter {format}")

    # formatters can display stock information with --full
    output = formatter.format(model, full=full)
    print(output)