Commit 74259aed authored by Robert Izzard's avatar Robert Izzard
Browse files

readd examples

parent b3f71c17
Loading
Loading
Loading
Loading
+985 −0

File added.

Preview size limit exceeded, changes collapsed.

examples/Bokeh_HRD.py

deleted100755 → 0
+0 −278
Original line number Diff line number Diff line
#!/usr/bin/env python3

############################################################
#
# Make interactive Hertzsprung-Russell diagram using binary_c
# ensemble data made with binary_c and libcdict.
#
############################################################

from binarycpython.utils.ensemble import load_ensemble
import bokeh
import ensemble_bokeh
import math
import traceback

vb = True # verbose output flag

############################################################
# set up plots
############################################################
plots = {
    'main' :
    {
        'name' : 'HRD',
        'xcol' : 'logTeff',
        'xlabel_html' : r'log<sub>10</sub>(<i>T</i><sub>eff</sub>/K)',
        'ycol' : 'logL',
        'ylabel_html' : r'log<sub>10</sub>(<i>L</i>/L<sub>&#9737;</sub>)',
        'zcol' : 'probability',
        'title' : "Hertzsprung-Russell diagram",
        'font' : 'Helvetica',
        'width' : 800,
        'height' : 800,
        'xaxis' : {
            'axis_label' : r'$$\log_{10}(T_\mathrm{eff}/K)$$',
        },
        'yaxis' :{
            'axis_label' : r'$$\log_{10}(L/\mathrm{L}_\odot)$$',
            },
        'x_axis_location' : "below",
        'x_range_flipped' : True,
        'logzdata' : True,
        'tooltips' : """<div>log<sub>10</sub>(<i>T</i><sub>eff</sub>/K)=$x, log<sub>10</sub>(<i>L</i>/L<sub>&#9737;</sub>)=$y, log<sub>10</sub>(<i>p</i>)=@formatted_probability, <i>f</i><sub>bin</sub>=@binfrac</div>""",
        'output_mode' : 'inline', # 'inline' (all local, larger file) or 'cdn' (loads javascript from remote source)
        #'zdex' : 6, # show only top 6 dex (requires logzdata)
        'subplots' : True,
        'ZAMS' : True,
        'radii' : True,
        'rebin' : [0.5,0.5], # rebin logTeff, logL to these binwidths
    },
    'm1dist' :
    {
        'name' : 'm1dist',
        'title' : 'log(Primary mass) distribution',
        'width' : 400,
        'height' : 400,
        'x_range' : (-2,+2.3),
        'xlabel' : r'$$\log_{10}(M_1/\mathrm{M}_\odot)$$',
        'ylabel' : r'$$\mathrm{d}p/\mathrm{d}log_{10}(M_1/\mathrm{M}_\odot)$$',
        'tooltips' : None,
        'dx' : 0.1,
        'disttype' : 'float',
    },
    'm2dist' :
    {
        'name' : 'm2dist',
        'title' : 'log(Secondary mass) distribution',
        'width' : 400,
        'height' : 400,
        'x_range' : (-2,+2.3),
        #'y_range' : (0,2),
        'xlabel' : r'$$\log_{10}(M_2/\mathrm{M}_\odot)$$',
        'ylabel' : r'$$\mathrm{d}p/\mathrm{d}log_{10}(M_2/\mathrm{M}_\odot)$$',
        'tooltips' : None,
        'dx' : 0.1,
        'disttype' : 'float',
    },
    'pdist' :
    {
        'name' : 'pdist',
        'title' : 'log(Orbital period) distribution',
        'width' : 400,
        'height' : 400,
        'x_range' : (math.log10(1e-3),math.log10(1e6)),
        'xlabel' : r'$$\log_{10}(P_\mathrm{orb}/\mathrm{d})$$',
        'ylabel' : r'$$\mathrm{d}p/\mathrm{d}\log_{10}(P_\mathrm{orb}/\mathrm{d})$$',
        'tooltips' : None,
        'dx' : 0.1,
        'rebinx' : 0.5,
        'disttype' : 'float',
    },
    'edist' :
    {
        'name' : 'edist',
        'title' : 'eccentricity distribution',
        'width' : 400,
        'height' : 400,
        'x_range' : (0.05,1),
        'xlabel' : r'Eccentricity',
        'ylabel' : r'$$\mathrm{d}p/\mathrm{d}e$$',
        'tooltips' : None,
        'dx' : 0.1,
        'disttype' : 'float',
    },
    'st1dist' :
    {
        'name' : 'st1dist',
        'title' : 'Primary stellar type distribution',
        'width' : 400,
        'height' : 400,
        'x_range' : (0,15),
        'xlabel' : r'Stellar type',
        'ylabel' : r'$$\mathrm{d}p/\mathrm{d\,(Stellar\,type)}$$',
        'tooltips' : None,
        'dx' : 1,
        'disttype' : 'int',
        'xaxis':{
            'major_label_overrides' : ensemble_bokeh.stellar_type_label_dict(),
            'major_label_orientation' : 'vertical',
            'major_label_text_font_size' : '10px',
            'major_label_policy' : bokeh.models.AllLabels(),
            'ticker' : bokeh.models.FixedTicker(ticks=list(range(0,16)))
        },
    },
    'st2dist' :
    {
        'name' : 'st2dist',
        'title' : 'Secondary Stellar type distribution',
        'width' : 400,
        'height' : 400,
        'x_range' : (0,15),
        'xlabel' : r'Stellar type',
        'ylabel' : r'$$\mathrm{d}p/\mathrm{d\,(Stellar\,type)}$$',
        'tooltips' : None,
        'dx' : 1,
        'disttype' : 'int',
        'xaxis':{
            'major_label_overrides' : ensemble_bokeh.stellar_type_label_dict(),
            'major_label_orientation' : 'vertical',
            'major_label_text_font_size' : '10px',
            'major_label_policy' : bokeh.models.AllLabels(),
            'ticker' : bokeh.models.FixedTicker(ticks=list(range(0,16)))
        },
    },
}

############################################################
# make and save list of subplots
############################################################
if plots['main'].get('subplots',True):
    plots['main']['subplots'] = list(k for k in plots.keys() if k != 'main')
else:
    plots['main']['subplots'] = []

############################################################
# Load in ensemble data and map to Bokeh ColumnDataSource
#
if vb:
    print("Load ensemble")
ensemble_file = 'data/ensemble_Bokeh.json.bz2'
hrd = load_ensemble(ensemble_file,quiet=True)['ensemble']['HRD Bokeh']

if plots['main'].get('rebin',False):
    if vb:
        print("Rebin ensemble")
    r = plots['main']['rebin']
    hrd = ensemble_bokeh.rebin_4D(plots=plots,
                                  data=hrd,
                                  dx=r[0],
                                  dy=r[1])

if vb:
    print("Analyse ensemble data")
analysis = ensemble_bokeh.analyse(hrd)

try:
    if vb:
        print("Map 4D to CDS")
    (datasource,zstats) = ensemble_bokeh.remap_4D_to_ColumnDataSource(
        hrd,
        plots = plots,
        analysis = analysis,
    )
except Exception as e:
    print("\nFailed to load datasource")
    s,r = getattr(e, 'message', str(e)), getattr(e, 'message', repr(e))
    print ('s:', s, 'len(s):', len(s))
    print ('r:', r, 'len(r):', len(r))
    print(traceback.format_exc())
    exit()

if vb:
    print("Make figures")
# make figures and renderers dict
(figures,renderers) = ensemble_bokeh.make_bokeh_figures(plots)

############################################################
# make HR diagram in the main plot
#
# first, make a colour bar and add it
if vb:
    print("Make colourbar")
(colour_bars,colour_mapper) = ensemble_bokeh.bokeh_colourbar(
    zdata = datasource.data[plots['main']['zcol']],
    zstats = zstats)
for c in colour_bars:
    figures['HRD'].add_layout(c,'right')

if vb:
    print("Add HRD")
# secondly, add the data as a map ("rect" type)
renderers['HRD'] = figures['HRD'].rect(
    x=plots['main']['xcol'], # x column
    y=plots['main']['ycol'], # y column
    fill_color={ # fill with colour_mapper (see above)
        'field' : plots['main']['zcol'],
        'transform' : colour_mapper
    },
    # "pixel" size in the HRD : you might want to increase these?
    width=analysis['dx'],
    height=analysis['dy'][plots['main']['ycol']],
    width_units='data',
    height_units='data',
    source=datasource, # data source
    line_color=None,
    dilate=True,
    name='HRD',
)


############################################################
# make the subplots and link their data to the main plot
if plots['main'].get('subplots',True):
    if vb:
        print("Make subplots")
    (renderers,linkdatas) = ensemble_bokeh.make_subplots(plots=plots,
                                                         figures=figures,
                                                         renderers=renderers,
                                                         datasource=datasource)
else:
    renderers = []
############################################################
# add a ZAMS track
if plots['main'].get('ZAMS',True):
    if vb:
        print("Make ZAMS")
    ensemble_bokeh.ZAMS_plot(figures)

############################################################
# add constant radius lines
if plots['main'].get('radii',True):
    if vb:
        print("Make radii")
    ensemble_bokeh.constant_radius_lines(plots,
                                         figures,
                                         analysis)
figures['HRD'].legend.location='bottom_left'
############################################################
# make custom javascript to update the sub plot
# when hovering over the main plot
#
# Here we assume one renderer is the main (here, 'HRD')
# and the others are subordinates
if plots['main'].get('subplots',True):
    if vb:
        print("Link plots")
    ensemble_bokeh.link_plots(
        main_figure = figures['HRD'],
        main_renderer = 'HRD',
        renderers = renderers,
        linkdatas = linkdatas
        )

# output HTML
if vb:
    print("Write to HRD.html")
ensemble_bokeh.output_plot(figures,
                           'HRD.html')