#!/usr/bin/env python"""Module containing the tools for plotting of results"""importosfrombilby.core.utilsimportcheck_directory_exists_and_if_not_mkdirfrombilby.gw.resultimportCBCResultfrombilby.gw.sourceimport(binary_black_hole_frequency_sequence,binary_black_hole_roq,binary_neutron_star_frequency_sequence,binary_neutron_star_roq,lal_binary_black_hole,lal_binary_neutron_star,)from.bilbyargparserimportBilbyArgParserfrom.utilsimportDataDump,get_command_line_arguments,logger,parse_args# fmt: offimportmatplotlib# isort:skipmatplotlib.use("agg")# noqaimportmatplotlib.pyplotasplt# noqa isort:skip# fmt: on
[docs]defcreate_parser():"""Generate a parser for the plot script Returns ------- parser: BilbyArgParser A parser with all the default options already added """parser=BilbyArgParser(ignore_unknown_config_file_keys=True)parser.add("--result",type=str,required=True,help="The result file")parser.add("--calibration",action="store_true",help="Generate calibration plot")parser.add("--corner",action="store_true",help="Generate corner plots")parser.add("--marginal",action="store_true",help="Generate marginal plots")parser.add("--skymap",action="store_true",help="Generate skymap")parser.add("--waveform",action="store_true",help="Generate waveform")parser.add("--outdir",type=str,required=False,help="The directory to save the plots in")parser.add("--format",type=str,default="png",help="Format for making bilby_pipe plots, can be [png, pdf, html]. ""If specified format is not supported, will default to png.",)returnparser
[docs]def_parse_and_load():args,unknown_args=parse_args(get_command_line_arguments(),create_parser())logger.info(f"Generating plots for results file {args.result}")extension=os.path.splitext(args.result)[-1][1:]ifextension=="json":result=CBCResult.from_json(args.result)elifextension=="hdf5":result=CBCResult.from_hdf5(args.result)elifextension=="pkl":result=CBCResult.from_pickle(args.result)else:raiseValueError(f"Result format {extension} not understood.")if"data_dump"inresult.meta_dataandos.path.exists(result.meta_data["data_dump"]):data_dump=DataDump.from_pickle(result.meta_data["data_dump"])logger.info(f"Loaded data from {result.meta_data['data_dump']}")else:data_dump=Nonelogger.info("Failed to load data dump file")ifhasattr(args,"webdir"):outdir=os.path.join(args.webdir,"bilby")elifhasattr(args,"outdir"):outdir=args.outdirelse:outdir=result.outdirlogger.info(f"Plots will be made in {outdir}")check_directory_exists_and_if_not_mkdir(outdir)result.outdir=outdirreturnargs,result,data_dump
[docs]defplot_calibration():args,result,_=_parse_and_load()logger.info("Generating calibration posterior")allowed_formats=list(plt.gcf().canvas.get_supported_filetypes())ifargs.formatinallowed_formats:_format=args.formatelse:logger.info(f"Requested format '{args.format}' not recognised. Falling back to png.")_format="png"result.plot_calibration_posterior(format=_format)
[docs]defplot_skymap():_,result,_=_parse_and_load()logger.info("Generating skymap")try:result.plot_skymap(maxpts=5000)exceptExceptionase:logger.info(f"Unable to generate skymap: error {e}")
[docs]defplot_waveform():args,result,data_dump=_parse_and_load()interferometers=getattr(data_dump,"interferometers",None)ifresult.frequency_domain_source_modelin[binary_black_hole_roq,binary_black_hole_frequency_sequence,]:ifresult.frequency_domain_source_model==binary_black_hole_roq:model="binary_black_hole_roq"else:model="binary_black_hole_frequency_sequence"logger.info(f"Sampling used the {model} source model, using ""the lal_binary_black_hole_model for the waveform plot.")result.meta_data["likelihood"]["frequency_domain_source_model"]=lal_binary_black_holeelifresult.frequency_domain_source_modelin[binary_neutron_star_roq,binary_neutron_star_frequency_sequence,]:ifresult.frequency_domain_source_model==binary_neutron_star_roq:model="binary_neutron_star_roq"else:model="binary_neutron_star_frequency_sequence"logger.info(f"Sampling used the {model} source model, using ""the lal_binary_neutron_star_model for the waveform plot.")result.meta_data["likelihood"]["frequency_domain_source_model"]=lal_binary_neutron_starlogger.info("Generating waveform posterior")allowed_formats=list(plt.gcf().canvas.get_supported_filetypes())+["html"]ifargs.formatinallowed_formats:_format=args.formatelse:logger.info(f"Requested format '{args.format}' not recognised. Falling back to png.")_format="png"result.plot_waveform_posterior(interferometers=interferometers,n_samples=1000,format=_format)
[docs]defmain():"""Top-level interface for bilby_pipe"""args,result,data_dump=_parse_and_load()ifargs.skymap:plot_skymap()ifargs.marginal:plot_marginal()ifargs.corner:plot_corner()ifargs.calibration:plot_calibration()ifargs.waveform:plot_waveform()