Example #1
0
    def _nglButtons(self, ngl_widget, statetype, states):
        # Adds buttons for enabling and disabling macrostate visualizations
        import IPython.html.widgets as widgets
        from IPython.display import display
        originalreps = ngl_widget.representations.copy()
        otherreps = originalreps[:-len(states)]
        originalreps = originalreps[-len(states):]

        container = []
        for s in states:
            w = widgets.Checkbox(description="{} {}".format(statetype, s))
            w.value = True
            container.append(w)

        def updateReps(name):
            ngl_widget.isClick = True
            reps = otherreps.copy()
            for i, w in enumerate(container):
                if w.value:
                    reps.append(originalreps[i])
            ngl_widget.representations = reps

        for w in container:
            w.on_trait_change(updateReps, "value")
        hb = widgets.HBox(container)
        display(hb)
Example #2
0
    def add_run(data, name, Z):
        run_count = frame.get_state_data("run_count")
        runs_data = frame.get_state_data("runs")
        widget_name = "runs_widget_#" + str(run_count)

        frame.add_io_object(widget_name)
        frame.set_state_attribute(widget_name, visible=True, description=name)
        frame.set_object(widget_name, widgets.Checkbox())

        runs_data.append((data, name, Z, widget_name))
        frame.set_state_children("runs", [widget_name])
        frame.set_state_data("runs", runs_data)
        run_count += 1
        frame.set_state_data("run_count", run_count)
Example #3
0
    def add_data_set(data, name):
        data_set_count = frame.get_state_data("data_set_count")
        data_sets = frame.get_state_data("data_sets")
        widget_name = "data_set_widget_#" + str(data_set_count)

        frame.add_io_object(widget_name)
        frame.set_state_attribute(widget_name, visible=True, description=name)
        frame.set_object(widget_name, widgets.Checkbox())

        data_sets.append((data, name, widget_name))
        frame.set_state_children("data_sets", [widget_name])
        frame.set_state_data("data_sets", data_sets)
        data_set_count += 1
        frame.set_state_data("data_set_count", data_set_count)
Example #4
0
 def add_run(state, data, name):
     run_count = frame.get_state_data("run_count")
     state_data = frame.get_state_data("runs",state)
     styles = frame.get_state_data("styles")
     style = styles.get_style()
     line_color = style["color"]
     line_style = style["shape"]
     
     widget_name = "runs_widget_#"+str(run_count)
     
     frame.add_io_object(widget_name)
     frame.set_state_attribute(widget_name, state, visible=True, description=name)
     frame.set_object(widget_name, widgets.Checkbox())
     
     state_data.append((data, name, line_style, line_color, widget_name))
     
     frame.set_state_children("runs", [widget_name], state=state)
     frame.set_state_data("runs", state_data, state)
Example #5
0
    def __init__(self, *args, **kwd):
        toggle_types = {'checkbox': widgets.Checkbox,
                        'button': widgets.ToggleButton}
        toggle_type = kwd.pop('toggle_type', 'checkbox')
        if toggle_type not in toggle_types:
            raise ValueError('toggle_type must be one of '
                             '{}'.format(toggle_type.keys()))
        super(ToggleContainer, self).__init__(*args, **kwd)
        self._toggle_container = widgets.Box(description='toggle holder')
        self._checkbox = toggle_types[toggle_type](description=self.description)
        self._toggle_container.children = [self._checkbox]
        self._container = widgets.Box(description="Toggle-able container")
        self._state_monitor = widgets.Checkbox(visible=False)

        self.children = [
            self._toggle_container,
            self._container,
            self._state_monitor
        ]

        self._link_children()
        self._child_notify_parent_on_change(self.toggle)
Example #6
0
def simulate(transitions,
             input='10101',
             unary=False,
             input_unary=12,
             pause=0.05,
             step_from=0,
             step_to=100,
             step_slack=100):
    """loads widget to simulate a given TM"""

    # widgets to specify the range of steps to simulate
    from_w = widgets.IntText(value=step_from, description="simulate from step")
    to_w = widgets.IntText(value=step_to, description="simulate to step")

    pause_w = widgets.FloatText(value=pause, description="pause between steps")

    # widget to indicate current step
    steps_w = widgets.IntSlider(min=0,
                                max=step_to + step_slack,
                                value=0,
                                description="current step")

    # subroutine to animate the simulation
    def animate(x):
        steps_w.max = to_w.value + step_slack
        for steps in range(from_w.value, to_w.value + 1):
            steps_w.value = steps
            sleep(pause_w.value)

    # button to start animated simulation
    simulate_w = widgets.Button(description='simulate')
    simulate_w.on_click(animate)

    input_w = widgets.Text(value=input, description="input")

    unary_w = widgets.Checkbox(value=unary, description='unary?')

    input_unary_w = widgets.IntText(value=input_unary,
                                    description='input number')

    def update():
        if unary_w.value:
            input_w.disabled = True
            input_unary_w.visible = True
            input_w.value = '1' * input_unary_w.value
        else:
            input_w.disabled = False
            input_unary_w.visible = False

    update()
    unary_w.on_trait_change(update)
    input_unary_w.on_trait_change(update)

    # display control widgets
    box = widgets.VBox(
        children=[simulate_w, from_w, to_w, pause_w, unary_w, input_unary_w])
    display(box)

    # widgets to display simulation
    interact(display_wrap(run),
             transitions=fixed(transitions),
             input=input_w,
             steps=steps_w)
Example #7
0
def start_SYGMA():
    frame = framework.framework()
    frame.set_default_display_style(padding="0.25em",
                                    background_color="white",
                                    border_color="LightGrey",
                                    border_radius="0.5em")
    frame.set_default_io_style(padding="0.25em",
                               margin="0.25em",
                               border_color="LightGrey",
                               border_radius="0.5em")

    tablist = ["sim_page", "plot_page", "custom_imf_page", "get_table_page"]
    yield_list = {
        "Analytic perscription": {
            "Delay":
            "yield_tables/isotope_yield_table_MESA_only_fryer12_delay.txt",
            "Rapid":
            "yield_tables/isotope_yield_table_MESA_only_fryer12_rapid.txt",
            "Exclude neutron-alpha rich freeze-out":
            "yield_tables/isotope_yield_table_MESA_only_fryer12_exclnalpha.txt"
        },
        "Ye=0.4982": {
            "Fallback at Ye":
            "yield_tables/isotope_yield_table_MESA_only_ye.txt",
            "Fallback motivated by GCE":
            "yield_tables/isotope_yield_table_MESA_only_ye_fallback.txt"
        }
    }
    group_style = {"border_style": "none", "border_radius": "0em"}
    text_box_style = {"width": "10em"}
    button_style = {"font_size": "1.25em", "font_weight": "bold"}
    first_tab_style = {"border_radius": "0em 0.5em 0.5em 0.5em"}

    custom_imf_dir = os.environ["SYGMADIR"] + "/SYGMA_widget_imfs/"
    default_custom_imf_text = "\n#File to define a custom IMF\n#Define your IMF in custom_imf\n#so that the return value represents\n#the chosen IMF value for the input mass\n\ndef custom_imf(mass):\n    #Salpeter IMF\n    return mass**-2.35\n"

    states_plot = [
        "plot_totmasses", "plot_mass", "plot_spectro", "plot_mass_range"
    ]
    states_sim_plot = ["run_sim"] + states_plot
    states_cimf = ["custom_imf", "load_custom_imf"]
    states = states_sim_plot + states_cimf
    frame.add_state(states)

    isotopes_all = [
        'H-1', 'H-2', 'He-3', 'He-4', 'Li-7', 'B-11', 'C-12', 'C-13', 'N-14',
        'N-15', 'O-16', 'O-17', 'O-18', 'F-19', 'Ne-20', 'Ne-21', 'Ne-22',
        'Na-23', 'Mg-24', 'Mg-25', 'Mg-26', 'Al-27', 'Si-28', 'Si-29', 'Si-30',
        'P-31', 'S-32', 'S-33', 'S-34', 'S-36', 'Cl-35', 'Cl-37', 'Ar-36',
        'Ar-38', 'Ar-40', 'K-39', 'K-40', 'K-41', 'Ca-40', 'Ca-42', 'Ca-43',
        'Ca-44', 'Ca-46', 'Ca-48', 'Sc-45', 'Ti-46', 'Ti-47', 'Ti-48', 'Ti-49',
        'Ti-50', 'V-50', 'V-51', 'Cr-50', 'Cr-52', 'Cr-53', 'Cr-54', 'Mn-55',
        'Fe-54', 'Fe-56', 'Fe-57', 'Fe-58', 'Co-59', 'Ni-58', 'Ni-60', 'Ni-61',
        'Ni-62', 'Ni-64'
    ]
    elements_all = [
        'H', 'He', 'Li', 'B', 'C', 'N', 'O', 'F', 'Ne', 'Na', 'Mg', 'Al', 'Si',
        'P', 'S', 'Cl', 'Ar', 'K', 'Ca', 'Sc', 'Ti', 'V', 'Cr', 'Mn', 'Fe',
        'Co', 'Ni'
    ]
    isotopes_sn1a = [
        'C-12', 'C-13', 'N-14', 'N-15', 'O-16', 'O-17', 'O-18', 'F-19',
        'Ne-20', 'Ne-21', 'Ne-22', 'Na-23', 'Mg-24', 'Mg-25', 'Mg-26', 'Al-27',
        'Si-28', 'Si-29', 'Si-30', 'P-31', 'S-32', 'S-33', 'S-34', 'S-36',
        'Cl-35', 'Cl-37', 'Ar-36', 'Ar-38', 'Ar-40', 'K-39', 'K-40', 'K-41',
        'Ca-40', 'Ca-42', 'Ca-43', 'Ca-44', 'Ca-46', 'Ca-48', 'Sc-45', 'Ti-46',
        'Ti-47', 'Ti-48', 'Ti-49', 'Ti-50', 'V-50', 'V-51', 'Cr-50', 'Cr-52',
        'Cr-53', 'Cr-54', 'Mn-55', 'Fe-54', 'Fe-56', 'Fe-57', 'Fe-58', 'Co-59',
        'Ni-58', 'Ni-60', 'Ni-61', 'Ni-62', 'Ni-64'
    ]
    elements_sn1a = [
        'C', 'N', 'O', 'F', 'Ne', 'Na', 'Mg', 'Al', 'Si', 'P', 'S', 'Cl', 'Ar',
        'K', 'Ca', 'Sc', 'Ti', 'V', 'Cr', 'Mn', 'Fe', 'Co', 'Ni'
    ]
    isotopes_sel_mult = ["All"] + isotopes_all
    elements_sel_mult = ["All"] + elements_all

    line_styles = ["-", "--", ":", "-."]
    #    line_colors=["k", "r", "g", "b", "c", "m", "y"]
    line_colors = ["k", "r", "b", "c", "m", "y"]  #remove "g"
    line_markers = ["o", "s", "x", "D", "v", "^", "<", ">", "p", "*", "+"]

    styles = auto_styles()
    styles.set_line_styles(line_styles)
    styles.set_line_colors(line_colors)
    styles.set_line_markers(line_markers)

    frame.set_state_data("elements", elements_all)
    frame.set_state_data("isotopes", isotopes_all)
    frame.set_state_data("over_plotting_data", [])
    frame.set_state_data("styles", styles)
    frame.set_state_data("old_state", None)

    frame.set_state_data("runs", [])
    frame.set_state_data("run_count", 0)

    def add_run(data, name, Z):
        run_count = frame.get_state_data("run_count")
        runs_data = frame.get_state_data("runs")
        widget_name = "runs_widget_#" + str(run_count)

        frame.add_io_object(widget_name)
        frame.set_state_attribute(widget_name, visible=True, description=name)
        frame.set_object(widget_name, widgets.Checkbox())

        runs_data.append((data, name, Z, widget_name))
        frame.set_state_children("runs", [widget_name])
        frame.set_state_data("runs", runs_data)
        run_count += 1
        frame.set_state_data("run_count", run_count)

    def remove_runs():
        data = frame.get_state_data("runs")
        children = ["runs_title"]
        tmp_data = []
        for i in xrange(len(data)):
            widget_name = data[i][3]
            if frame.get_attribute(widget_name, "value"):
                frame.remove_object(widget_name)
            else:
                children.append(widget_name)
                tmp_data.append(data[i])
        data = tmp_data
        frame.set_state_children("runs", children, append=False)
        frame.set_state_data("runs", data)

    def list_custom_imf():
        if os.path.isdir(custom_imf_dir):
            files_dirs = os.listdir(custom_imf_dir)
            imfs = []
            for file in files_dirs:
                file_full = custom_imf_dir + file
                if os.path.isfile(file_full):
                    file = file.rsplit(".", 1)
                    if file[1] == "py":
                        imfs.append(file[0])
            return imfs
        else:
            return []

    frame.add_display_object("window")
    frame.add_io_object("title")
    frame.add_display_object("widget_runs_group")
    frame.add_display_object("widget")

    frame.add_display_object("runs")
    frame.add_io_object("runs_title")

    ###Sim page###
    frame.add_display_object("sim_page")

    frame.add_display_object("mass_Z_group")
    frame.add_io_object("init_Z")
    frame.add_io_object("mass_gas")

    frame.add_display_object("time_group")
    frame.add_io_object("t_end")
    frame.add_io_object("dt")

    frame.add_display_object("imf_type_group")
    frame.add_io_object("imf_type")
    frame.add_io_object("imf_alpha")

    frame.add_display_object("imf_mass_group")
    frame.add_io_object("imf_mass_min")
    frame.add_io_object("imf_mass_max")

    frame.add_display_object("sn1a_group")
    frame.add_io_object("use_sn1a")
    frame.add_io_object("sn1a_rates")

    frame.add_display_object("yield_table_group")
    frame.add_io_object("yield_table_selection")
    frame.add_io_object("yield_table_list")

    frame.add_display_object("run_sim_remove_run_group")
    frame.add_io_object("run_sim")
    frame.add_io_object("remove_run")
    frame.add_io_object("run_name")

    frame.add_io_object("plot_type")
    frame.add_io_object("sim_responce")

    frame.set_state_children("window", ["title", "widget_runs_group"])
    frame.set_state_children("widget_runs_group", ["widget", "runs"])

    frame.set_state_children("widget", ["sim_page"], titles=["Simulation"])
    frame.set_state_children("sim_page", [
        "mass_Z_group", "time_group", "imf_type_group", "imf_mass_group",
        "sn1a_group", "yield_table_group", "run_sim_remove_run_group",
        "sim_responce"
    ])
    frame.set_state_children("mass_Z_group", ["mass_gas", "init_Z"])
    frame.set_state_children("time_group", ["t_end", "dt"])
    frame.set_state_children("imf_type_group", ["imf_type", "imf_alpha"])
    frame.set_state_children("imf_mass_group",
                             ["imf_mass_min", "imf_mass_max"])
    frame.set_state_children("sn1a_group", ["use_sn1a", "sn1a_rates"])
    frame.set_state_children("yield_table_group",
                             ["yield_table_selection", "yield_table_list"])
    frame.set_state_children("run_sim_remove_run_group",
                             ["run_sim", "remove_run", "run_name"])

    frame.set_state_children("runs", ["runs_title"])

    ###plotting page###
    frame.add_display_object("plot_page")

    frame.add_io_object("warning_msg")
    frame.add_io_object("plot_name")

    frame.add_display_object("source_over_plotting_group")
    frame.add_io_object("source")
    frame.add_io_object("over_plotting")
    frame.add_io_object("clear_plot")

    frame.add_display_object("species_group")
    frame.add_io_object("iso_or_elem")
    frame.add_io_object("species")

    frame.add_io_object("elem_numer")
    frame.add_io_object("elem_denom")
    frame.add_io_object("plot")

    frame.set_state_children("widget", ["plot_page"], titles=["Plotting"])
    frame.set_state_children("plot_page", [
        "warning_msg", "plot_type", "plot_name", "source_over_plotting_group",
        "species_group", "elem_numer", "elem_denom", "plot"
    ])
    frame.set_state_children("source_over_plotting_group",
                             ["source", "over_plotting", "clear_plot"])
    frame.set_state_children("species_group", ["iso_or_elem", "species"])

    ###Custom IMF page###
    frame.add_display_object("custom_imf_page")

    frame.add_display_object("load_save_imf_group")
    frame.add_io_object("load_imf")
    frame.add_io_object("list_imfs")
    frame.add_io_object("name_imf")
    frame.add_io_object("save_imf")
    frame.add_io_object("delete_imf")

    frame.add_io_object("text_imf")

    frame.add_io_object("test_imf")

    frame.set_state_children("widget", ["custom_imf_page"],
                             titles=["Custom IMF"])
    frame.set_state_children("custom_imf_page",
                             ["load_save_imf_group", "text_imf", "test_imf"])
    frame.set_state_children(
        "load_save_imf_group",
        ["load_imf", "list_imfs", "name_imf", "save_imf", "delete_imf"])

    ###plotting page###
    frame.add_display_object("get_table_page")

    frame.add_display_object("species_mult_group")
    frame.add_io_object("species_mult")

    frame.add_io_object("get_table")
    frame.add_io_object("table_links")

    frame.set_state_children("widget", ["get_table_page"],
                             titles=["Download Tables"])
    frame.set_state_children(
        "get_table_page",
        ["warning_msg", "species_mult_group", "get_table", "table_links"])
    frame.set_state_children("species_mult_group",
                             ["iso_or_elem", "species_mult"])

    frame.set_state_attribute('window', visible=True, **group_style)
    frame.set_state_attribute('title',
                              visible=True,
                              value="<center><h1>SYGMA</h1></center>")
    frame.set_state_attribute("widget_runs_group", visible=True, **group_style)
    frame.set_state_attribute('widget', visible=True, **group_style)
    frame.set_state_attribute("runs",
                              visible=True,
                              margin="3.15em 0em 0em 0em")
    frame.set_state_attribute("runs", states_cimf, visible=False)
    frame.set_state_attribute("runs_title",
                              visible=True,
                              value="<center><h2>Runs</h2></center>",
                              **group_style)

    frame.set_state_attribute('sim_page', visible=True, **first_tab_style)
    frame.set_state_attribute("mass_Z_group", visible=True, **group_style)
    frame.set_state_attribute("mass_gas",
                              visible=True,
                              description="Total stellar mass [$M_{\odot}$]:",
                              value="1.0",
                              **text_box_style)
    frame.set_state_attribute(
        'init_Z',
        visible=True,
        description="Initial metallicity: ",
        options=["0.02", "0.01", "0.006", "0.001", "0.0001", "0.0"])

    frame.set_state_attribute('time_group', visible=True, **group_style)
    frame.set_state_attribute('t_end',
                              visible=True,
                              description="Final time [yrs]: ",
                              value="1.0e10",
                              **text_box_style)
    frame.set_state_attribute('dt',
                              visible=True,
                              description="Time step [yrs]: ",
                              value="1.0e7",
                              **text_box_style)

    frame.set_state_attribute('imf_type_group', visible=True, **group_style)
    frame.set_state_attribute(
        'imf_type',
        visible=True,
        description="IMF type: ",
        options=['salpeter', 'chabrier', 'kroupa', 'alphaimf'] +
        list_custom_imf())
    frame.set_state_attribute('imf_alpha',
                              description="Set alpha: ",
                              min=0,
                              max=5)

    frame.set_state_attribute("imf_mass_group", visible=True, **group_style)
    frame.set_state_attribute('imf_mass_min',
                              visible=True,
                              description="IMF lower limit [$M_{\odot}$]: ",
                              value="1.0",
                              **text_box_style)
    frame.set_state_attribute('imf_mass_max',
                              visible=True,
                              description="IMF upper limit [$M_{\odot}$]: ",
                              value="30.0",
                              **text_box_style)

    frame.set_state_attribute('sn1a_group', visible=True, **group_style)
    frame.set_state_attribute('use_sn1a',
                              visible=True,
                              description="Include SNe Ia: ",
                              value=True)
    frame.set_state_attribute("yield_table_group", visible=True, **group_style)
    frame.set_state_attribute("yield_table_selection",
                              visible=True,
                              description="CCSN remnant prescription:",
                              options=["Analytic perscription", "Ye=0.4982"],
                              value="Ye=0.4982")
    frame.set_state_attribute('yield_table_list',
                              visible=True,
                              options=yield_list["Ye=0.4982"],
                              selected_label="Fallback at Ye")
    frame.set_state_links("sn1a_link", [("use_sn1a", "value"),
                                        ("sn1a_rates", "visible")],
                          directional=True)

    frame.set_state_attribute(
        'sn1a_rates',
        description="SNe Ia rates: ",
        options=['Power law', 'Exponential', 'Gaussian', 'Maoz12'])

    frame.set_state_attribute("run_sim_remove_run_group",
                              visible=True,
                              **group_style)
    frame.set_state_attribute('run_sim',
                              visible=True,
                              description="Run simulation",
                              **button_style)
    frame.set_state_attribute("remove_run",
                              visible=True,
                              description="Remove selected",
                              **button_style)
    frame.set_state_attribute("run_name",
                              visible=True,
                              description="Run name: ",
                              placeholder="Enter name",
                              value="",
                              **text_box_style)

    frame.set_state_attribute("sim_responce",
                              value="<p>Simulation data loaded.</p>",
                              **group_style)
    frame.set_state_attribute("sim_responce", states_sim_plot, visible=True)

    frame.set_state_attribute('plot_type',
                              states_sim_plot,
                              visible=True,
                              description="Plot type: ",
                              options=[
                                  "Total mass", "Species mass",
                                  "Species spectroscopic",
                                  "Mass range contributions"
                              ])

    def mass_gas_handler(name, value):
        frame.set_attributes("mass_gas", value=float_text(value))

    def t_end_handler(name, value):
        frame.set_attributes("t_end", value=float_text(value))

    def dt_handler(name, value):
        frame.set_attributes("dt", value=float_text(value))

    def imf_mass_min_handler(name, value):
        frame.set_attributes("imf_mass_min", value=float_text(value))

    def imf_mass_max_handler(name, value):
        frame.set_attributes("imf_mass_max", value=float_text(value))

    def sel_imf_type(attribute, value):
        if value == "alphaimf":
            frame.set_state_attribute("imf_alpha", visible=True)
            frame.set_attributes("imf_alpha", visible=True, value=2.35)
        else:
            frame.set_state_attribute("imf_alpha", visible=False)
            frame.set_attributes("imf_alpha", visible=False)

    def yield_table_selection_handler(name, value):
        frame.set_attributes("yield_table_list", options=yield_list[value])
        if value == "Analytic perscription":
            frame.set_attributes("yield_table_list", selected_label="Delay")
        elif value == "Ye=0.4982":
            frame.set_attributes("yield_table_list",
                                 selected_label="Fallback at Ye")

    def run_simulation(widget):
        frame.set_attributes("sim_responce", visible=False)
        clear_output()
        pyplot.close("all")

        sn1a_map = {
            "Power law": "power_law",
            "Gaussian": "gauss",
            "Exponential": "exp",
            "Maoz12": "maoz"
        }

        mgal = float(frame.get_attribute("mass_gas", "value"))
        iniZ = float(frame.get_attribute("init_Z", "value"))
        imf_type = frame.get_attribute("imf_type", "value")
        alphaimf = frame.get_attribute("imf_alpha", "value")
        mass_min = float(frame.get_attribute("imf_mass_min", "value"))
        mass_max = float(frame.get_attribute("imf_mass_max", "value"))
        imf_bdys = [mass_min, mass_max]
        sn1a_on = frame.get_attribute("use_sn1a", "value")
        sn1a_rate = sn1a_map[frame.get_attribute("sn1a_rates", "value")]
        dt = float(frame.get_attribute("dt", "value"))
        tend = float(frame.get_attribute("t_end", "value"))
        yield_table = frame.get_attribute("yield_table_list", "value")

        if not (imf_type in ['salpeter', 'chabrier', 'kroupa', 'alphaimf']):
            destination = os.environ["SYGMADIR"] + "/imf_input.py"
            shutil.copy(custom_imf_dir + imf_type + ".py", destination)
            imf_type = "input"

        run_count = frame.get_state_data("run_count")
        name = frame.get_attribute("run_name", "value")
        if name == "":
            name = "Run - " + "%03d" % (run_count + 1, )

        if iniZ == 0.0:
            data = s.sygma(mgal=mgal,
                           iniZ=iniZ,
                           imf_type=imf_type,
                           alphaimf=alphaimf,
                           imf_bdys=[10.1, 100.0],
                           imf_bdys_pop3=imf_bdys,
                           sn1a_on=sn1a_on,
                           sn1a_rate=sn1a_rate,
                           dt=dt,
                           tend=tend,
                           table=yield_table)
        else:
            data = s.sygma(mgal=mgal,
                           iniZ=iniZ,
                           imf_type=imf_type,
                           alphaimf=alphaimf,
                           imf_bdys=imf_bdys,
                           sn1a_on=sn1a_on,
                           sn1a_rate=sn1a_rate,
                           dt=dt,
                           tend=tend,
                           table=yield_table)
        frame.set_state("run_sim")
        ##force reset plottype
        frame.set_attributes("plot_type",
                             selected_label="Species mass",
                             value="Species mass")
        frame.set_attributes("plot_type",
                             selected_label="Total mass",
                             value="Total mass")

        add_run(data, name, iniZ)
        frame.update()

    def remove_simulation(widget):
        remove_runs()
        frame.update()

    def sel_tab(name, value):
        open_tab = tablist[value]

        if open_tab == "custom_imf_page":
            frame.set_state_data("old_state", frame.get_state())
            frame.set_state("custom_imf")
            if frame.get_attribute("name_imf", "value") == "":
                frame.set_attributes("text_imf", value=default_custom_imf_text)
        else:
            if frame.get_state() in states_cimf:
                old_state = frame.get_state_data("old_state")
                if old_state != None:
                    frame.set_state(old_state)
                else:
                    frame.set_state("default")
                frame.set_state_data("old_state", None)

    frame.set_state_callbacks("mass_gas", mass_gas_handler)
    frame.set_state_callbacks("t_end", t_end_handler)
    frame.set_state_callbacks("dt", dt_handler)
    frame.set_state_callbacks("imf_mass_min", imf_mass_min_handler)
    frame.set_state_callbacks("imf_mass_max", imf_mass_max_handler)
    frame.set_state_callbacks("imf_type", sel_imf_type)
    frame.set_state_callbacks("yield_table_selection",
                              yield_table_selection_handler)
    frame.set_state_callbacks("run_sim",
                              run_simulation,
                              attribute=None,
                              type="on_click")
    frame.set_state_callbacks("remove_run",
                              remove_simulation,
                              attribute=None,
                              type="on_click")
    frame.set_state_callbacks("widget", sel_tab, "selected_index")

    frame.set_object("window", widgets.Box())
    frame.set_object("title", widgets.HTML())
    frame.set_object("widget_runs_group", widgets.HBox())
    frame.set_object("widget", widgets.Tab())
    frame.set_object("runs", widgets.VBox())

    frame.set_object("runs_title", widgets.HTML())

    frame.set_object("sim_page", widgets.VBox())
    frame.set_object("mass_Z_group", widgets.HBox())
    frame.set_object("mass_gas", widgets.Text())
    frame.set_object("init_Z", widgets.Dropdown())

    frame.set_object("time_group", widgets.HBox())
    frame.set_object("t_end", widgets.Text())
    frame.set_object("dt", widgets.Text())

    frame.set_object("imf_type_group", widgets.HBox())
    frame.set_object("imf_type", widgets.Dropdown())
    frame.set_object("imf_alpha", widgets.FloatSlider())

    frame.set_object("imf_mass_group", widgets.HBox())
    frame.set_object("imf_mass_min", widgets.Text())
    frame.set_object("imf_mass_max", widgets.Text())

    frame.set_object("sn1a_group", widgets.HBox())
    frame.set_object("use_sn1a", widgets.Checkbox())
    frame.set_object("sn1a_rates", widgets.Dropdown())

    frame.set_object("yield_table_group", widgets.HBox())
    frame.set_object("yield_table_selection", widgets.ToggleButtons())
    frame.set_object("yield_table_list", widgets.Dropdown())

    frame.set_object("run_sim_remove_run_group", widgets.HBox())
    frame.set_object("run_sim", widgets.Button())
    frame.set_object("remove_run", widgets.Button())
    frame.set_object("run_name", widgets.Text())

    frame.set_object("sim_responce", widgets.HTML())

    frame.set_object("plot_type", widgets.Dropdown())

    frame.set_state_attribute("plot_page", visible=True)
    frame.set_state_attribute("warning_msg",
                              visible=True,
                              value="<h3>Error: No simulation data!</h3>",
                              **group_style)
    frame.set_state_attribute("warning_msg", states_plot, visible=False)
    frame.set_state_attribute("plot_name", **group_style)
    frame.set_state_attribute("plot_name",
                              "plot_totmasses",
                              visible=True,
                              value="<h2>Plot: Total mass evolution</h2>")
    frame.set_state_attribute("plot_name",
                              "plot_mass",
                              visible=True,
                              value="<h2>Plot: Species mass evolution</h2>")
    frame.set_state_attribute(
        "plot_name",
        "plot_spectro",
        visible=True,
        value="<h2>Plot: Spectroscopic Mass evolution</h2>")
    frame.set_state_attribute(
        "plot_name",
        "plot_mass_range",
        visible=True,
        value=
        "<h2>Plot: Mass range contributions</h2><p>Only ejecta from AGB and massive stars are considered.</p>"
    )

    frame.set_state_attribute("source_over_plotting_group",
                              states_plot,
                              visible=True,
                              **group_style)
    frame.set_state_attribute("source",
                              ["plot_totmasses", "plot_mass", "plot_spectro"],
                              visible=True,
                              description="Yield source: ",
                              options=["All", "AGB", "SNe Ia", "Massive"],
                              selected_label="All")
    frame.set_state_attribute("over_plotting",
                              visible=True,
                              description="Over plotting",
                              value=False,
                              **button_style)
    frame.set_state_attribute("clear_plot",
                              description="Clear plot",
                              **button_style)
    frame.set_state_links("clear_plot_link", [("over_plotting", "value"),
                                              ("clear_plot", "visible")],
                          directional=True)

    frame.set_state_attribute("species_group",
                              ["plot_mass", "plot_mass_range"],
                              visible=True,
                              **group_style)
    frame.set_state_attribute("iso_or_elem",
                              visible=True,
                              description="species type: ",
                              options=["Elements", "Isotopes"],
                              selected_label="Elements")
    frame.set_state_attribute("species",
                              visible=True,
                              description="Element: ",
                              options=elements_all,
                              **text_box_style)
    frame.set_state_attribute("elem_numer",
                              "plot_spectro",
                              visible=True,
                              description="Y-axis [X/Y], choose X: ",
                              options=elements_all,
                              **text_box_style)
    frame.set_state_attribute("elem_denom",
                              "plot_spectro",
                              visible=True,
                              description="Y-axis [X/Y], choose Y: ",
                              options=elements_all,
                              **text_box_style)
    frame.set_state_attribute("plot",
                              states_plot,
                              visible=True,
                              description="Generate Plot",
                              **button_style)

    def clear_plot_handler(widget):
        clear_output()
        pyplot.close("all")
        frame.set_state_data("over_plotting_data", [])

    def sel_plot_type(attribute, value):
        if value == "Total mass":
            frame.set_state("plot_totmasses")
        elif value == "Species mass":
            frame.set_state("plot_mass")
        elif value == "Species spectroscopic":
            frame.set_state("plot_spectro")
        elif value == "Mass range contributions":
            frame.set_state("plot_mass_range")

#        iniZ = float(frame.get_attribute("init_Z", "value"))
#        if iniZ==0.0:
#            frame.set_attributes("source", options=["All", "AGB", "Massive"])
#        else:
        frame.set_attributes("source",
                             options=["All", "AGB", "SNe Ia", "Massive"])
        frame.set_state_data("over_plotting_data", [])

    def sel_source(attribute, value):
        if value == "SNe Ia":
            frame.set_state_data("elements", elements_sn1a)
            frame.set_state_data("isotopes", isotopes_sn1a)
        else:
            frame.set_state_data("elements", elements_all)
            frame.set_state_data("isotopes", isotopes_all)
            frame.set_attributes("elem_numer", options=[])
            frame.set_attributes("elem_denom", options=[])
            frame.set_attributes("species", options=[])

        elements = frame.get_state_data("elements")
        isotopes = frame.get_state_data("isotopes")
        frame.set_attributes("elem_numer", options=elements)
        frame.set_attributes("elem_denom", options=elements)

        if frame.get_attribute("iso_or_elem", "value") == "Isotopes":
            frame.set_attributes("species",
                                 description="Isotope: ",
                                 options=isotopes)
        elif frame.get_attribute("iso_or_elem", "value") == "Elements":
            frame.set_attributes("species",
                                 description="Element: ",
                                 options=elements)

    def sel_iso_or_elem(attribute, value):
        elements = frame.get_state_data("elements")
        isotopes = frame.get_state_data("isotopes")
        if value == "Isotopes":
            frame.set_attributes("species",
                                 description="Isotope: ",
                                 options=isotopes)
            frame.set_attributes("species_mult",
                                 description="Isotope: ",
                                 options=isotopes_sel_mult)
        elif value == "Elements":
            frame.set_attributes("species",
                                 description="Element: ",
                                 options=elements)
            frame.set_attributes("species_mult",
                                 description="Element: ",
                                 options=elements_sel_mult)

    def run(widget):
        styles = frame.get_state_data("styles")
        styles.reset_line_count()

        clear_output()
        pyplot.close("all")

        over_plotting = frame.get_attribute("over_plotting", "value")
        source_map = {
            "All": "all",
            "AGB": "agb",
            "SNe Ia": "sn1a",
            "Massive": "massive"
        }
        label_map = {
            "All": "",
            "AGB": ", AGB",
            "SNe Ia": ", SNIa",
            "Massive": ", Massive"
        }
        tot_mass_labels = {
            "all": "All",
            "agb": "AGB",
            "sn1a": "SNIa",
            "massive": "Massive"
        }
        state = frame.get_state()
        runs = frame.get_state_data("runs")
        source = source_map[frame.get_attribute("source", "value")]
        label_source = label_map[frame.get_attribute("source", "value")]
        species = frame.get_attribute("species", "value")

        no_runs = True

        if state == "plot_totmasses":
            plot_data = frame.get_state_data("over_plotting_data")

            if not over_plotting:
                plot_data = []

            over_plot = [("source", source)]
            if not over_plot in plot_data:
                plot_data.append(over_plot)
                frame.set_state_data("over_plotting_data", plot_data)

            for data, name, Z, widget_name in runs:
                if frame.get_attribute(widget_name, "value"):
                    no_runs = False
                    for item in plot_data:
                        kwargs = dict(item)
                        label = name + ": " + tot_mass_labels[kwargs["source"]]
                        kwargs.update({"label": label})
                        kwargs.update(styles.get_style())
                        data.plot_totmasses(**kwargs)
        elif state == "plot_mass":
            plot_data = frame.get_state_data("over_plotting_data")

            if not over_plotting:
                plot_data = []

            over_plot = [("specie", species), ("source", source)]
            if not over_plot in plot_data:
                plot_data.append(over_plot)
                frame.set_state_data("over_plotting_data", plot_data)

            for data, name, Z, widget_name in runs:
                if frame.get_attribute(widget_name, "value"):
                    no_runs = False
                    for item in plot_data:
                        kwargs = dict(item)
                        label = name + ": " + kwargs["specie"]
                        if not kwargs["source"] == "all":
                            label = label + ", " + tot_mass_labels[
                                kwargs["source"]]
                        kwargs.update({"label": label})
                        kwargs.update(styles.get_style())
                        data.plot_mass(**kwargs)
        elif state == "plot_spectro":
            X = frame.get_attribute("elem_numer", "value")
            Y = frame.get_attribute("elem_denom", "value")
            yaxis = "[" + X + "/" + Y + "]"

            plot_data = frame.get_state_data("over_plotting_data")

            if not over_plotting:
                plot_data = []

            over_plot = [("yaxis", yaxis), ("source", source)]
            if not over_plot in plot_data:
                plot_data.append(over_plot)
                frame.set_state_data("over_plotting_data", plot_data)

            for data, name, Z, widget_name in runs:
                if frame.get_attribute(widget_name, "value"):
                    no_runs = False
                    for item in plot_data:
                        kwargs = dict(item)
                        label = name + ": " + kwargs[
                            "yaxis"] + ", " + tot_mass_labels[kwargs["source"]]
                        kwargs.update({"label": label})
                        kwargs.update(styles.get_style())
                        data.plot_spectro(**kwargs)
        elif state == "plot_mass_range":
            plot_data = frame.get_state_data("over_plotting_data")

            if not over_plotting:
                plot_data = []

            over_plot = [("specie", species)]
            if not over_plot in plot_data:
                plot_data.append(over_plot)
                frame.set_state_data("over_plotting_data", plot_data)

            for data, name, Z, widget_name in runs:
                if frame.get_attribute(widget_name, "value"):
                    no_runs = False
                    for item in plot_data:
                        kwargs = dict(item)
                        label = name + ": " + kwargs["specie"]
                        kwargs.update({"label": label})
                        kwargs.update(styles.get_style())
                        data.plot_mass_range_contributions(**kwargs)
        if no_runs:
            print "No runs selected."

    frame.set_state_callbacks("clear_plot",
                              clear_plot_handler,
                              attribute=None,
                              type="on_click")
    frame.set_state_callbacks("plot_type", sel_plot_type)
    frame.set_state_callbacks("source",
                              sel_source,
                              state=["plot_spectro", "plot_mass"])
    frame.set_state_callbacks("iso_or_elem", sel_iso_or_elem)
    frame.set_state_callbacks("plot", run, attribute=None, type="on_click")

    frame.set_object("plot_page", widgets.VBox())
    frame.set_object("warning_msg", widgets.HTML())
    frame.set_object("plot_name", widgets.HTML())
    frame.set_object("source_over_plotting_group", widgets.HBox())
    frame.set_object("source", widgets.Dropdown())
    frame.set_object("over_plotting", widgets.ToggleButton())
    frame.set_object("clear_plot", widgets.Button())
    frame.set_object("species_group", widgets.VBox())
    frame.set_object("iso_or_elem", widgets.RadioButtons())
    frame.set_object("species", widgets.Select())
    frame.set_object("elem_numer", widgets.Select())
    frame.set_object("elem_denom", widgets.Select())
    frame.set_object("plot", widgets.Button())

    frame.set_state_attribute("custom_imf_page", visible=True)
    frame.set_state_attribute("load_save_imf_group",
                              visible=True,
                              **group_style)
    frame.set_state_attribute("load_imf",
                              "custom_imf",
                              visible=True,
                              description="Load custom IMF",
                              **button_style)
    frame.set_state_attribute("list_imfs",
                              "load_custom_imf",
                              visible=True,
                              description="Select IMF")
    frame.set_state_attribute("name_imf",
                              "custom_imf",
                              visible=True,
                              description="IMF name",
                              **text_box_style)
    frame.set_state_attribute("save_imf",
                              "custom_imf",
                              visible=True,
                              description="Save IMF",
                              **button_style)
    frame.set_state_attribute("delete_imf",
                              "custom_imf",
                              visible=True,
                              description="Delete IMF",
                              **button_style)

    frame.set_state_attribute("text_imf", visible=True)

    frame.set_state_attribute("test_imf",
                              visible=True,
                              description="Test selected IMF file",
                              **button_style)

    def load_imf_handler(widget):
        frame.set_state("load_custom_imf")
        options = ["", "Preset: default"] + list_custom_imf()
        frame.set_attributes("list_imfs",
                             options=options,
                             value="",
                             selected_label="")

    def sel_custom_imf(name, value):
        if value != "":
            frame.set_state("custom_imf")
            if value == "Preset: default":
                frame.set_attributes("name_imf", value="")
                frame.set_attributes("text_imf", value=default_custom_imf_text)
            else:
                text = ""
                with open(custom_imf_dir + value + ".py", "r") as fin:
                    text = fin.read()
                frame.set_attributes("name_imf", value=value)
                frame.set_attributes("text_imf", value=text)

    def save_imf_handler(widget):
        clear_output()
        pyplot.close("all")
        imf_name = frame.get_attribute("name_imf", "value")

        if imf_name == "":
            print("Error: not IMF name given")
        else:

            if not os.path.isdir(custom_imf_dir):
                os.mkdir(custom_imf_dir)

            with open(custom_imf_dir + imf_name + ".py", "w") as fout:
                fout.write(frame.get_attribute("text_imf", "value"))
            print("Custom IMF saved to " + imf_name)

        frame.set_state_attribute(
            'imf_type',
            options=['salpeter', 'chabrier', 'kroupa', 'alphaimf'] +
            list_custom_imf())

    def delete_imf_handler(widget):
        clear_output()
        pyplot.close("all")
        imf_name = frame.get_attribute("name_imf", "value")

        if imf_name == "":
            print("Error: not IMF name given")
        else:

            if os.path.isdir(custom_imf_dir):
                if os.path.isfile(custom_imf_dir + imf_name + ".py"):
                    os.remove(custom_imf_dir + imf_name + ".py")
                    frame.set_attributes("name_imf", value="")
                    frame.set_attributes("text_imf",
                                         value=default_custom_imf_text)
                    print("Custom IMF " + imf_name + " deleted.")
                else:
                    print("Custom IMF, " + imf_name + ", not found!")

        frame.set_state_attribute(
            'imf_type',
            options=['salpeter', 'chabrier', 'kroupa', 'alphaimf'] +
            list_custom_imf())

    def test_imf_handler(widget):
        clear_output()
        pyplot.close("all")

        imf_name = frame.get_attribute("name_imf", "value")

        if imf_name == "":
            print("No IMF name given!")
            return

        try:
            ci = load_source("custom_imf", custom_imf_dir + imf_name + ".py")
        except IOError:
            print("Failed to load " + imf_name + ", no IMF file found.")
            return

        mass_min = 0.0
        mass_max = 30.0

        xaxis = numpy.linspace(mass_min, mass_max, 1000)[1:]
        yaxis = [0 for x in xaxis]
        for i, x in enumerate(xaxis):
            yaxis[i] = ci.custom_imf(x)
        pyplot.plot(xaxis, numpy.log10(yaxis))
        pyplot.title("IMF file test: " + imf_name)
        pyplot.xlabel("mass [$M_{\odot}$]")
        pyplot.ylabel("IMF")
        pyplot.show()

    frame.set_state_callbacks("load_imf",
                              load_imf_handler,
                              attribute=None,
                              type="on_click")
    frame.set_state_callbacks("list_imfs", sel_custom_imf)
    frame.set_state_callbacks("save_imf",
                              save_imf_handler,
                              attribute=None,
                              type="on_click")
    frame.set_state_callbacks("delete_imf",
                              delete_imf_handler,
                              attribute=None,
                              type="on_click")
    frame.set_state_callbacks("test_imf",
                              test_imf_handler,
                              attribute=None,
                              type="on_click")

    frame.set_object("custom_imf_page", widgets.VBox())

    frame.set_object("load_save_imf_group", widgets.HBox())
    frame.set_object("load_imf", widgets.Button())
    frame.set_object("list_imfs", widgets.Dropdown())
    frame.set_object("name_imf", widgets.Text())
    frame.set_object("save_imf", widgets.Button())
    frame.set_object("delete_imf", widgets.Button())

    frame.set_object("text_imf", widgets.Textarea())

    frame.set_object("test_imf", widgets.Button())

    frame.set_state_attribute("get_table_page", visible=True)

    frame.set_state_attribute("warning_msg",
                              visible=True,
                              value="<h3>Error: No simulation data!</h3>",
                              **group_style)
    frame.set_state_attribute("warning_msg", states_plot, visible=False)

    frame.set_state_attribute("species_mult_group",
                              states_sim_plot,
                              visible=True,
                              **group_style)
    frame.set_state_attribute("iso_or_elem",
                              visible=True,
                              description="species type: ",
                              options=["Elements", "Isotopes"],
                              selected_label="Elements")
    frame.set_state_attribute("species_mult",
                              visible=True,
                              description="Element: ",
                              options=elements_sel_mult,
                              **text_box_style)

    frame.set_state_attribute("get_table",
                              states_sim_plot,
                              visible=True,
                              description="Get table links",
                              **button_style)
    frame.set_state_attribute("table_links",
                              states_sim_plot,
                              visible=True,
                              value="",
                              **group_style)

    def species_mult_handler(name, value):
        if "All" in value:
            iso_or_elem = frame.get_attribute("iso_or_elem", "value")
            if iso_or_elem == "Elements":
                value = tuple(elements_all)
            elif iso_or_elem == "Isotopes":
                value = tuple(isotopes_all)
            frame.set_attributes("species_mult",
                                 value=value,
                                 selected_labels=value)
        frame.set_attributes("table_links", value="")

    def get_table_handler(widget):
        iso_or_elem = frame.get_attribute("iso_or_elem", "value")
        species = list(frame.get_attribute("species_mult", "value"))

        runs = frame.get_state_data("runs")
        title = "<h3>Data table links:</h3>"
        html = title

        if not os.path.isdir("./evol_tables"):
            os.mkdir("./evol_tables")

        for data, name, Z, widget_name in runs:
            if frame.get_attribute(widget_name, "value"):
                file = "evol_tables/" + widget_name.replace("#", "") + "file"
                if iso_or_elem == "Elements":
                    data.write_evol_table(species, [], file, "./")
                elif iso_or_elem == "Isotopes":
                    data.write_evol_table([], species, file, "./")
                html = html + "<p><a href=\"" + file + "\" target=\"_blank\" download>" + name + "</a></p>\n"

        if html == title:
            html = ""
            print("No runs selected.")

        frame.set_attributes("table_links", value=html)
        clear_output()
        pyplot.close("all")

    frame.set_state_callbacks("species_mult", species_mult_handler)
    frame.set_state_callbacks("get_table",
                              get_table_handler,
                              attribute=None,
                              type="on_click")

    frame.set_object("species_mult_group", widgets.VBox())
    frame.set_object("species_mult", widgets.SelectMultiple())
    frame.set_object("get_table_page", widgets.VBox())
    frame.set_object("get_table", widgets.Button())
    frame.set_object("table_links", widgets.HTML())

    ##start widget##
    frame.display_object("window")
def start_explorer(global_namespace, manual_data_select=False, dir="./"):
    frame = framework.framework()
    frame.set_default_display_style(padding="0.25em",
                                    background_color="white",
                                    border_color="LightGrey",
                                    border_radius="0.5em")
    frame.set_default_io_style(padding="0.25em",
                               margin="0.25em",
                               border_color="LightGrey",
                               border_radius="0.5em")

    group_style = {
        "border_style": "none",
        "border_radius": "0em",
        "width": "100%"
    }
    text_box_style = {"width": "10em"}
    button_style = {"font_size": "1.25em", "font_weight": "bold"}
    first_tab_style = {"border_radius": "0em 0.5em 0.5em 0.5em"}

    states_movie = ["movie", "movie_iso_abund", "movie_abu_chart"]
    states_nugrid = [
        "nugrid", "nugrid_w_data", "nugrid_get_data", "iso_abund", "abu_chart",
        "nugrid_plot"
    ] + states_movie
    states_mesa = [
        "mesa", "mesa_w_data", "get_data", "hrd", "plot", "kip_cont",
        "kippenhahn", "tcrhoc"
    ]
    states_plotting = states_nugrid[3:] + states_mesa[3:]

    frame.add_state(states_nugrid)
    frame.add_state(states_mesa)
    if manual_data_select:
        frame.set_state_data("model_data", (None, None))
    else:
        frame.set_state_data("model_data", (None, None, None))
    frame.set_state_data("variable_name_timer", None)
    frame.set_state_data("dir", os.path.abspath(dir))

    def update_dir_bar_list():
        dir = frame.get_state_data("dir")
        dirs = [".", ".."] + os.listdir(dir)

        frame.set_state_attribute("address_bar", value=dir)
        frame.set_state_attribute("directory_list", options=dirs)

    frame.add_display_object("window")
    frame.add_io_object("Title")
    frame.add_display_object("widget")

    ###Data page###
    frame.add_display_object("page_data")
    frame.add_io_object("mass")
    frame.add_io_object("Z")
    frame.add_io_object("select_nugrid_mesa")
    frame.add_io_object("address_bar")
    frame.add_io_object("directory_list")

    frame.add_display_object("contain_module_load")
    frame.add_io_object("select_module")
    frame.add_display_object("contain_model_select")
    frame.add_io_object("model_select")
    frame.add_io_object("load_data")

    frame.set_state_children("window", ["Title", "widget"])
    frame.set_state_children("widget", ["page_data"], titles=["Data"])
    frame.set_state_children("page_data", [
        "mass", "Z", "address_bar", "directory_list", "select_nugrid_mesa",
        "contain_module_load"
    ])
    frame.set_state_children(
        "contain_module_load",
        ["select_module", "contain_model_select", "load_data"])
    frame.set_state_children("contain_model_select", ["model_select"])

    ###Plotting page###
    frame.add_display_object("page_plotting")

    frame.add_io_object("select_plot")

    frame.add_io_object("warning_msg")

    frame.add_io_object("plot_name")

    frame.add_display_object("cycle_sparsity_group")
    frame.add_io_object("cycle")
    frame.add_io_object("cycle_range")
    frame.add_io_object("sparsity")

    frame.add_io_object("movie_type")

    frame.add_display_object("xax")
    frame.add_io_object("xaxis")
    frame.add_io_object("logx")
    frame.add_display_object("yax")
    frame.add_io_object("yaxis")
    frame.add_io_object("logy")

    frame.add_display_object("mass_settings")
    frame.add_io_object("set_amass")
    frame.add_io_object("amass_range")
    frame.add_io_object("set_mass")
    frame.add_io_object("mass_range")
    frame.add_io_object("lbound")

    frame.add_display_object("kipp_settings")
    frame.add_io_object("plot_star_mass")
    frame.add_io_object("plot_c12border")
    frame.add_io_object("plot_engminus")
    frame.add_io_object("plot_engplus")

    frame.add_io_object("ixaxis")
    frame.add_display_object("lim_settings")
    frame.add_io_object("set_lims")
    frame.add_io_object("ylim")
    frame.add_io_object("xlim")
    frame.add_io_object("yres")
    frame.add_io_object("xres")

    frame.add_io_object("stable")

    frame.add_display_object("abu_settings")
    frame.add_io_object("ilabel")
    frame.add_io_object("imlabel")
    frame.add_io_object("imagic")

    frame.add_io_object("variable_name")

    frame.add_io_object("generate_plot")

    frame.set_state_children("widget", ["page_plotting"], titles=["Plotting"])
    frame.set_state_children("page_plotting", [
        "select_plot", "warning_msg", "plot_name", "movie_type",
        "variable_name", "cycle_sparsity_group", "xax", "yax", "stable",
        "mass_settings", "kipp_settings", "lim_settings", "abu_settings",
        "stable", "generate_plot"
    ])
    frame.set_state_children("cycle_sparsity_group",
                             ["cycle", "cycle_range", "sparsity"])
    frame.set_state_children("xax", ["xaxis", "logx"])
    frame.set_state_children("yax", ["yaxis", "logy"])
    frame.set_state_children(
        "mass_settings",
        ["set_amass", "amass_range", "set_mass", "mass_range", "lbound"])
    frame.set_state_children(
        "lim_settings", ["ixaxis", "set_lims", "xlim", "ylim", "xres", "yres"])
    frame.set_state_children("abu_settings", ["ilabel", "imlabel", "imagic"])
    frame.set_state_children(
        "kipp_settings",
        ["plot_star_mass", "plot_c12border", "plot_engminus", "plot_engplus"])

    ###DEFAULT###

    frame.set_state_data("class_instance", None)

    frame.set_state_attribute('window', visible=True, **group_style)
    frame.set_state_attribute(
        'Title',
        visible=True,
        value=
        "<center><h1>NuGrid Set explorer</h1></center><p><center>This explorer allows you to investigate NuGrid stellar evolution and yields data sets.</center></p>"
    )
    frame.set_state_attribute('widget', visible=True, **group_style)

    frame.set_state_attribute("page_data", visible=True, **first_tab_style)
    frame.set_state_attribute('mass',
                              visible=not manual_data_select,
                              description="Mass: ",
                              options=[
                                  "1.0", "1.65", "2.0", "3.0", "4.0", "5.0",
                                  "6.0", "7.0", "12.0", "15.0", "20.0", "25.0",
                                  "32.0", "60.0"
                              ],
                              selected_label="2.0")
    frame.set_state_attribute('Z',
                              visible=not manual_data_select,
                              description="Z: ",
                              options=["1E-4", "1E-3", "6E-3", "1E-2", "2E-2"])
    frame.set_state_attribute("address_bar", visible=manual_data_select)
    frame.set_state_attribute("directory_list", visible=manual_data_select)
    frame.set_state_attribute("select_nugrid_mesa",
                              visible=True,
                              description="Select NuGrid or Mesa: ",
                              options=["", "NuGrid", "Mesa"])
    frame.set_state_attribute("contain_module_load",
                              visible=True,
                              **group_style)
    frame.set_state_attribute("select_module",
                              visible=True,
                              description="Select data type: ",
                              disabled=True)

    frame.set_state_attribute("contain_model_select",
                              border_style="none",
                              padding="0px",
                              margin="0px",
                              width="18em")
    frame.set_state_attribute("model_select",
                              visible=True,
                              description="Select model: ",
                              placeholder="1",
                              **text_box_style)

    frame.set_state_attribute("load_data",
                              visible=True,
                              description="Load Data",
                              disabled=True,
                              **button_style)

    ###NUGRID###
    frame.set_state_attribute("select_module",
                              states_nugrid,
                              options=["", "H5 out"],
                              disabled=False)
    frame.set_state_attribute("load_data", states_nugrid, disabled=False)

    ###MESA###
    frame.set_state_attribute("select_module",
                              states_mesa,
                              options=["", "History", "Profile"],
                              disabled=False)
    frame.set_state_attribute("load_data", states_mesa, disabled=False)

    ###CALLBACKS###
    def model_select_handler(name, value):
        frame.set_attributes("model_select", value=int_text(value))

    def mass_Z_handler(name, value):
        if frame.get_attribute("contain_model_select", "visible"):
            mass = float(frame.get_attribute("mass", "value"))
            Z = float(frame.get_attribute("Z", "value"))
            dir = frame.get_attribute("address_bar", "value")
            if manual_data_select:
                mdir, mmodel = frame.get_state_data("model_data")
                if (mdir != dir) or (mmodel == None):
                    clear_output()
                    pre_data = ms.mesa_profile(dir)
                    frame.set_state_data("model_data", (dir, pre_data.model))
            else:
                mmass, mZ, mmodel = frame.get_state_data("model_data")
                if (mmass != mass) or (mZ != Z) or (mmodel == None):
                    clear_output()
                    pre_data = ms.mesa_profile(mass=mass, Z=Z)
                    frame.set_state_data("model_data",
                                         (mass, Z, pre_data.model))

    def address_bar_handler(widget):
        dir = frame.get_attribute("address_bar", "value")
        if os.path.isdir(dir):
            dir = os.path.abspath(dir)
            frame.set_state_data("dir", dir)
            update_dir_bar_list()
            frame.update()
            frame.set_attributes("address_bar", value=dir)
            frame.set_attributes("directory_list",
                                 value=".",
                                 selected_label=u".")

    def directory_list_handler(name, value):
        dir = frame.get_state_data("dir")
        dir = dir + "/" + frame.get_attribute("directory_list", "value")
        if os.path.isdir(dir):
            dir = os.path.abspath(dir)
            frame.set_state_data("dir", dir)
            update_dir_bar_list()
            frame.update()
            frame.set_attributes("address_bar", value=dir)
            frame.set_attributes("directory_list",
                                 value=".",
                                 selected_label=u".")

    def sel_nugrid_mesa(name, value):
        if value == "NuGrid":
            frame.set_state("nugrid")
        elif value == "Mesa":
            frame.set_state("mesa")
        elif value == "":
            frame.set_state("default")

    def load(widget):
        clear_output()
        data = None
        mass = float(frame.get_attribute("mass", "value"))
        Z = float(frame.get_attribute("Z", "value"))
        dir = frame.get_attribute("address_bar", "value")
        if frame.get_attribute("model_select", "value") != "":
            model = int(frame.get_attribute("model_select", "value"))
        else:
            model = 1
        module = frame.get_attribute("select_module", "value")
        if module == "H5 out":
            if manual_data_select:
                data = mp.se(dir)
            else:
                data = mp.se(mass=mass, Z=Z)
            frame.set_state("nugrid_w_data")
            properties = ["mass", "radius", "rho", "temperature"]
            frame.set_attributes("xaxis",
                                 options=properties + data.se.isotopes)
            frame.set_attributes("yaxis",
                                 options=properties + data.se.isotopes)
        elif module == "History":
            if manual_data_select:
                data = ms.history_data(dir)
            else:
                data = ms.history_data(mass=mass, Z=Z)
            frame.set_state("mesa_w_data")
            frame.set_attributes("xaxis", options=sorted(data.cols.keys()))
            frame.set_attributes("yaxis", options=sorted(data.cols.keys()))
        elif module == "Profile":
            if manual_data_select:
                data = ms.mesa_profile(dir, num=model)
            else:
                data = ms.mesa_profile(mass=mass, Z=Z, num=model)
            frame.set_state("mesa_w_data")
            frame.set_attributes("xaxis", options=sorted(data.cols.keys()))
            frame.set_attributes("yaxis", options=sorted(data.cols.keys()))
        else:
            nugrid_or_mesa = frame.get_attribute("select_nugrid_mesa", 'value')
            if nugrid_or_mesa == "NuGrid":
                frame.set_state("nugrid")
            elif nugrid_or_mesa == "Mesa":
                frame.set_state("mesa")

        frame.set_state_data("class_instance", data)
        frame.set_attributes("select_plot", selected_label="")

    def change_module(widget, value):
        if value == "History":
            frame.set_state_attribute("select_plot",
                                      states_mesa[1:],
                                      options={
                                          "": "mesa_w_data",
                                          "HR-Diagram": "hrd",
                                          "Plot": "plot",
                                          "Kippenhahn": "kippenhahn",
                                          "Kippenhahan contour": "kip_cont",
                                          "TCRhoC plot": "tcrhoc",
                                          "Get data": "get_data"
                                      })
            frame.set_state_attribute("contain_model_select",
                                      states_mesa,
                                      visible=False)
            frame.set_attributes("contain_model_select", visible=False)
        elif value == "Profile":
            frame.set_attributes("load_data", disabled=True)
            frame.set_state_attribute("select_plot",
                                      states_mesa[1:],
                                      options={
                                          "": "mesa_w_data",
                                          "Plot": "plot",
                                          "Get data": "get_data"
                                      })

            mass = float(frame.get_attribute("mass", "value"))
            Z = float(frame.get_attribute("Z", "value"))
            dir = frame.get_attribute("address_bar", "value")
            if manual_data_select:
                mdir, mmodel = frame.get_state_data("model_data")
                if (mdir != dir) or (mmodel == None):
                    clear_output()
                    pre_data = ms.mesa_profile(dir)
                    mmodel = pre_data.model
                    frame.set_state_data("model_data", (dir, mmodel))
            else:
                mmass, mZ, mmodel = frame.get_state_data("model_data")
                if (mmass != mass) or (mZ != Z) or (mmodel == None):
                    clear_output()
                    pre_data = ms.mesa_profile(mass=mass, Z=Z)
                    mmodel = pre_data.model
                    frame.set_state_data("model_data", (mass, Z, mmodel))

            frame.set_state_attribute("contain_model_select",
                                      states_mesa,
                                      visible=True)
            frame.set_attributes("contain_model_select", visible=True)
            frame.set_attributes("model_select", value=str(mmodel[-1]))
            frame.set_attributes("load_data", disabled=False)
        else:
            frame.set_state_attribute("contain_model_select",
                                      states_mesa,
                                      visible=False)
            frame.set_attributes("contain_model_select", visible=False)

    frame.set_state_callbacks("model_select", model_select_handler)
    frame.set_state_callbacks("mass", mass_Z_handler)
    frame.set_state_callbacks("Z", mass_Z_handler)
    frame.set_state_callbacks("address_bar",
                              address_bar_handler,
                              attribute=None,
                              type="on_submit")
    frame.set_state_callbacks("directory_list", directory_list_handler)
    frame.set_state_callbacks("select_nugrid_mesa", sel_nugrid_mesa)
    frame.set_state_callbacks("select_module", change_module)
    frame.set_state_callbacks("load_data",
                              load,
                              attribute=None,
                              type="on_click")

    frame.set_object("window", widgets.Box())
    frame.set_object("Title", widgets.HTML())
    frame.set_object("widget", widgets.Tab())

    frame.set_object("page_data", widgets.VBox())
    frame.set_object("mass", widgets.Dropdown())
    frame.set_object("Z", widgets.ToggleButtons())
    frame.set_object("address_bar", widgets.Text())
    frame.set_object("directory_list", widgets.Select())

    frame.set_object("select_nugrid_mesa", widgets.Dropdown())
    frame.set_object("contain_module_load", widgets.HBox())
    frame.set_object("select_module", widgets.Dropdown())
    frame.set_object("contain_model_select", widgets.HBox())
    frame.set_object("model_select", widgets.Text())
    frame.set_object("load_data", widgets.Button())

    ###Plotting page###
    frame.set_state_attribute('page_plotting', visible=True)

    frame.set_state_attribute("select_plot",
                              visible=True,
                              description="Select plot type: ",
                              disabled=True)
    frame.set_state_attribute("select_plot",
                              states_nugrid[1:],
                              options={
                                  "": "nugrid_w_data",
                                  "Isotope abundance": "iso_abund",
                                  "Abundance chart": "abu_chart",
                                  "Movie": "movie",
                                  "Plot": "nugrid_plot",
                                  "Get data": "nugrid_get_data"
                              },
                              disabled=False)
    frame.set_state_attribute("select_plot",
                              states_mesa[1:],
                              options={
                                  "": "mesa_w_data",
                                  "HR-Diagram": "hrd",
                                  "Plot": "plot",
                                  "Kippenhahn": "kippenhahn",
                                  "Kippenhahan contour": "kip_cont",
                                  "TCRhoC": "tcrhoc",
                                  "Get data": "nugrid_get_data"
                              },
                              disabled=False)

    frame.set_state_attribute('warning_msg',
                              visible=True,
                              value="<h3>Error: No data loaded!</h3>",
                              **group_style)
    frame.set_state_attribute("warning_msg", ["nugrid_w_data", "mesa_w_data"],
                              value="<h2>Select plot.</h2>")
    frame.set_state_attribute("warning_msg",
                              states_plotting +
                              ["get_data", "nugrid_get_data"],
                              visible=False)

    frame.set_state_attribute("plot_name", **group_style)
    frame.set_state_attribute('plot_name',
                              "iso_abund",
                              visible=True,
                              value="<h2>Isotope abundance</h2>")
    frame.set_state_attribute('plot_name',
                              "abu_chart",
                              visible=True,
                              value="<h2>Abundance chart</h2>")
    frame.set_state_attribute('plot_name',
                              states_movie,
                              visible=True,
                              value="<h2>Movie</h2>")
    frame.set_state_attribute('plot_name',
                              "hrd",
                              visible=True,
                              value="<h2>HR-Diagram</h2>")
    frame.set_state_attribute('plot_name', ["plot", "nugrid_plot"],
                              visible=True,
                              value="<h2>Plot</h2>")
    frame.set_state_attribute('plot_name',
                              "kippenhahn",
                              visible=True,
                              value="<h2>Kippenhahn</h2>")
    frame.set_state_attribute('plot_name',
                              "kip_cont",
                              visible=True,
                              value="<h2>Kippenhahn contour</h2>")
    frame.set_state_attribute(
        'plot_name',
        "tcrhoc",
        visible=True,
        value="<h2>Central temperature vs central density</h2>")
    frame.set_state_attribute('plot_name', ["get_data", "nugrid_get_data"],
                              visible=True,
                              value="<h2>Get data</h2>")

    frame.set_state_attribute("variable_name", ["get_data", "nugrid_get_data"],
                              visible=True,
                              description="Variable name: ",
                              placeholder="Enter name.",
                              **text_box_style)

    frame.set_state_attribute('movie_type',
                              states_movie,
                              visible=True,
                              description="Movie Type: ",
                              options={
                                  "": "movie",
                                  "Isotope abundance": "movie_iso_abund",
                                  "Abundance chart": "movie_abu_chart"
                              })
    frame.set_state_attribute('cycle_sparsity_group',
                              states_nugrid[1:] + states_mesa[1:] +
                              states_movie,
                              visible=True,
                              **group_style)
    frame.set_state_attribute(
        'cycle', ["iso_abund", "abu_chart", "nugrid_plot", "nugrid_get_data"],
        visible=True,
        description="cycle: ")
    frame.set_state_attribute('cycle_range', states_movie[1:], visible=True)
    frame.set_state_attribute('sparsity',
                              states_movie[1:],
                              visible=True,
                              description="Sparsity: ",
                              value="1",
                              **text_box_style)

    frame.set_state_attribute(
        'xax', ["plot", "nugrid_plot", "get_data", "nugrid_get_data"],
        visible=True,
        **group_style)
    frame.set_state_attribute('xaxis',
                              visible=True,
                              description="select X-axis: ")
    frame.set_state_attribute('xaxis', ["get_data", "nugrid_get_data"],
                              description="select data: ")
    frame.set_state_attribute('logx', visible=True, description="log X-axis: ")
    frame.set_state_attribute('logx', ["get_data", "nugrid_get_data"],
                              visible=False)
    frame.set_state_attribute('yax', ["plot", "nugrid_plot"],
                              visible=True,
                              **group_style)
    frame.set_state_attribute('yaxis',
                              visible=True,
                              description="select Y-axis: ")
    frame.set_state_attribute('logy', visible=True, description="log Y-axis: ")

    frame.set_state_attribute("mass_settings",
                              ["iso_abund", "abu_chart"] + states_movie[1:],
                              visible=True,
                              **group_style)
    frame.set_state_attribute("set_amass", ["iso_abund", "movie_iso_abund"],
                              visible=True,
                              description="Set atomic mass: ")
    frame.set_state_attribute("amass_range", ["iso_abund", "movie_iso_abund"],
                              description="Atomi mass range: ",
                              min=0,
                              max=211,
                              value=(0, 211))
    frame.set_state_attribute("set_mass",
                              ["iso_abund", "abu_chart"] + states_movie[1:],
                              visible=True,
                              description="Set mass: ")
    frame.set_state_attribute("mass_range",
                              ["iso_abund", "abu_chart"] + states_movie[1:],
                              description="Mass range: ")
    frame.set_state_attribute("lbound",
                              "abu_chart",
                              visible=True,
                              description="lbound",
                              min=-12,
                              max=0,
                              step=0.05,
                              value=(-12, 0))

    frame.set_state_links("amass_link", [("set_amass", "value"),
                                         ("amass_range", "visible")],
                          ["iso_abund", "movie_iso_abund"], True)
    frame.set_state_links("mass_link", [("set_mass", "value"),
                                        ("mass_range", "visible")],
                          ["iso_abund", "abu_chart"] + states_movie[1:], True)

    frame.set_state_attribute(
        "lim_settings",
        ["iso_abund", "abu_chart", "kip_cont", "tcrhoc"] + states_movie[1:],
        visible=True,
        **group_style)
    frame.set_state_attribute(
        "set_lims",
        ["iso_abund", "abu_chart", "kip_cont", "tcrhoc"] + states_movie[1:],
        visible=True,
        description="Set axis limits: ")
    frame.set_state_attribute("xlim",
                              ["abu_chart", "movie_abu_chart", "kip_cont"],
                              description="x-axis limits: ",
                              min=0,
                              max=130,
                              value=(0, 130),
                              step=0.5)
    frame.set_state_attribute("xlim",
                              "tcrhoc",
                              description="x-axis limits: ",
                              min=3.0,
                              max=10.0,
                              value=(3.0, 10.0),
                              step=0.5)
    frame.set_state_attribute(
        "ylim",
        ["iso_abund", "abu_chart", "kip_cont", "tcrhoc"] + states_movie[1:],
        description="y-axis limits: ")
    frame.set_state_attribute("ylim", ["iso_abund", "movie_iso_abund"],
                              min=-13,
                              max=0,
                              step=0.05,
                              value=(-13, 0))
    frame.set_state_attribute("ylim", ["abu_chart", "movie_abu_chart"],
                              min=0,
                              max=130,
                              value=(0, 130),
                              step=0.5)
    frame.set_state_attribute("ylim",
                              "kip_cont",
                              min=0,
                              max=1,
                              value=(0, 1),
                              step=0.005)  #mass
    frame.set_state_attribute("ylim",
                              "tcrhoc",
                              min=8.0,
                              max=10.0,
                              value=(8.0, 10.0),
                              step=0.5)
    frame.set_state_attribute("ixaxis",
                              "kip_cont",
                              visible=True,
                              description="X axis format: ",
                              options={
                                  "Log time": "log_time_left",
                                  "Age": "age",
                                  "Model number": "model_number"
                              },
                              value="model_number")

    frame.set_state_links(
        "xlims_link", [("set_lims", "value"), ("xlim", "visible")],
        ["abu_chart", "movie_abu_chart", "kip_cont", "tcrhoc"], True)
    frame.set_state_links("ylims_link", [("set_lims", "value"),
                                         ("ylim", "visible")],
                          ["iso_abund", "abu_chart", "kip_cont", "tcrhoc"] +
                          states_movie[1:], True)

    frame.set_state_attribute("xres",
                              "kip_cont",
                              visible=True,
                              description="x resolution: ",
                              placeholder="1000",
                              **text_box_style)
    frame.set_state_attribute("yres",
                              "kip_cont",
                              visible=True,
                              description="y resolution: ",
                              placeholder="1000",
                              **text_box_style)

    frame.set_state_links("xres_link", [("set_lims", "value"),
                                        ("xres", "visible")], "kip_cont", True)
    frame.set_state_links("yres_link", [("set_lims", "value"),
                                        ("yres", "visible")], "kip_cont", True)

    frame.set_state_attribute("abu_settings", ["abu_chart", "movie_abu_chart"],
                              visible=True,
                              **group_style)
    frame.set_state_attribute("ilabel", ["abu_chart", "movie_abu_chart"],
                              visible=True,
                              description="Element label")
    frame.set_state_attribute("imlabel", ["abu_chart", "movie_abu_chart"],
                              visible=True,
                              description="Isotope label")
    frame.set_state_attribute("imagic", ["abu_chart", "movie_abu_chart"],
                              visible=True,
                              description="Magic numbers")

    frame.set_state_attribute("kipp_settings", ["kippenhahn", "kip_cont"],
                              visible=True,
                              **group_style)
    frame.set_state_attribute("plot_star_mass",
                              "kippenhahn",
                              visible=True,
                              description="Plot star mass: ")
    frame.set_state_attribute("plot_c12border", ["kippenhahn", "kip_cont"],
                              visible=True,
                              description="Show C-12 Border: ")
    frame.set_state_attribute(
        "plot_engminus",
        "kip_cont",
        visible=True,
        description="Energy generation contours (eps_nuc>0): ")
    frame.set_state_attribute(
        "plot_engplus",
        "kip_cont",
        visible=True,
        description="Energy generation contours (eos_nuc<0): ")

    frame.set_state_attribute("stable",
                              "iso_abund",
                              visible=True,
                              description="stable: ")

    frame.set_state_attribute('generate_plot',
                              states_plotting,
                              visible=True,
                              description="Generate Plot",
                              **button_style)
    frame.set_state_attribute('generate_plot', ["get_data", "nugrid_get_data"],
                              visible=True,
                              description="Get Data",
                              **button_style)

    def variable_name_full_validation(value):
        frame.set_attributes("variable_name",
                             value=token_text(value, strict=True))
        frame.set_state_data("variable_name_timer", None)

    def variable_name_handler(name, value):
        value = token_text(value)
        frame.set_attributes("variable_name", value=value)

        timer = frame.get_state_data("variable_name_timer")
        if (value != token_text(value, strict=True)):
            if timer != None:
                timer.cancel()
            timer = threading.Timer(1.0,
                                    variable_name_full_validation,
                                    kwargs={"value": value})
            timer.start()
        else:
            if timer != None:
                timer.cancel()
            timer = None
        frame.set_state_data("variable_name_timer", timer)

    def yres_handler(name, value):
        frame.set_attributes("yres", value=int_text(value))

    def xres_handler(name, value):
        frame.set_attributes("xres", value=int_text(value))

    def sel_plot(widget, value):
        data = frame.get_state_data("class_instance")

        if value in ["iso_abund", "abu_chart"]:
            cycle_list = data.se.cycles
            step = int(cycle_list[1]) - int(cycle_list[0])
            min = int(cycle_list[0])
            max = int(cycle_list[-1])

            mass_list = data.se.get(min, "mass")
            mass_min, mass_max = mass_list[0], mass_list[-1]
            mass_step = (mass_max - mass_min) / 200.0
            frame.set_state_attribute("mass_range", ["iso_abund", "abu_chart"],
                                      min=mass_min,
                                      max=mass_max,
                                      value=(mass_min, mass_max),
                                      step=mass_step)

            frame.set_state_attribute('cycle', ["iso_abund", "abu_chart"],
                                      min=min,
                                      max=max,
                                      step=step)

        if value == "kip_cont":
            min = 0
            max = len(data.data)
            mass = data.header_attr["initial_mass"]

            frame.set_state_attribute("xlim",
                                      "kip_cont",
                                      min=min,
                                      max=max,
                                      step=1,
                                      value=(min, max))
            frame.set_state_attribute("ylim",
                                      "kip_cont",
                                      min=0.0,
                                      max=mass,
                                      step=mass / 200.0,
                                      value=(0.0, mass))

        if value in ["nugrid_plot", "nugrid_get_data"]:
            cycle_list = data.se.cycles
            step = int(cycle_list[1]) - int(cycle_list[0])
            min = int(cycle_list[0])
            max = int(cycle_list[-1])

            frame.set_state_attribute('cycle',
                                      ["nugrid_plot", "nugrid_get_data"],
                                      min=min,
                                      max=max,
                                      step=step)

        frame.set_state(value)

    def sel_movie_plot(widget, value):
        data = frame.get_state_data("class_instance")

        if value in ["movie_iso_abund", "movie_abu_chart"]:
            cycle_list = data.se.cycles
            step = int(cycle_list[1]) - int(cycle_list[0])
            min = int(cycle_list[0])
            max = int(cycle_list[-1])

            mass_list = data.se.get(min, "mass")
            mass_min, mass_max = mass_list[0], mass_list[-1]
            mass_step = (mass_max - mass_min) / 200.0
            frame.set_state_attribute("mass_range",
                                      ["movie_iso_abund", "movie_abu_chart"],
                                      min=mass_min,
                                      max=mass_max,
                                      value=(mass_min, mass_max),
                                      step=mass_step)

            frame.set_state_attribute('cycle_range',
                                      ["movie_iso_abund", "movie_abu_chart"],
                                      min=min,
                                      max=max,
                                      step=step,
                                      value=(min, max))

        frame.set_state(value)

    def make_plot(widget):
        clear_output()
        pyplot.close("all")
        state = frame.get_state()

        data = frame.get_state_data("class_instance")
        variable_name = frame.get_attribute("variable_name", "value")
        cycle = frame.get_attribute("cycle", "value")
        cycle_range = frame.get_attribute("cycle_range", "value")
        if state in states_movie:
            sparsity = int(frame.get_attribute("sparsity", "value"))
        xax = frame.get_attribute("xaxis", "value")
        logx = frame.get_attribute("logx", "value")
        yax = frame.get_attribute("yaxis", "value")
        logy = frame.get_attribute("logy", "value")
        if frame.get_attribute("set_amass", "value"):
            amass = frame.get_attribute("amass_range", "value")
            amass = [amass[0], amass[1]]
        else:
            amass = None

        if frame.get_attribute("set_mass", "value"):
            mass = frame.get_attribute("mass_range", "value")
            mass = [mass[0], mass[1]]
        else:
            mass = None

        lbound = frame.get_attribute("lbound", "value")

        if frame.get_attribute("set_lims", "value"):
            xlim = frame.get_attribute("xlim", "value")
            ylim = frame.get_attribute("ylim", "value")
        else:
            xlim = [0, 0]
            ylim = [0, 0]

        xres = frame.get_attribute("xres", "value")
        if xres == "":
            xres = "1000"
        yres = frame.get_attribute("yres", "value")
        if yres == "":
            yres = "1000"

        xres = int(xres)
        yres = int(yres)

        ixaxis = frame.get_attribute("ixaxis", "value")

        stable = frame.get_attribute("stable", "value")
        ilabel = frame.get_attribute("ilabel", "value")
        imlabel = frame.get_attribute("imlabel", "value")
        imagic = frame.get_attribute("imagic", "value")

        plot_star_mass = frame.get_attribute("plot_star_mass", "value")
        plot_c12border = frame.get_attribute("plot_c12border", "value")
        plot_engminus = frame.get_attribute("plot_engminus", "value")
        plot_engplus = frame.get_attribute("plot_engplus", "value")

        if state == "iso_abund":
            data.iso_abund(cycle, stable, amass, mass, ylim)
        elif state == "abu_chart":
            plotaxis = [xlim[0], xlim[1], ylim[0], ylim[1]]
            data.abu_chart(cycle,
                           mass,
                           ilabel,
                           imlabel,
                           imagic=imagic,
                           lbound=lbound,
                           plotaxis=plotaxis,
                           ifig=1)
        elif state == "plot":
            if isinstance(yax, basestring):
                yax = [yax]
            for yaxis in yax:
                data.plot(xax, yaxis, logx=logx, logy=logy, shape="-")
        elif state == "nugrid_plot":
            if isinstance(yax, basestring):
                yax = [yax]
            for yaxis in yax:
                data.plot(xax,
                          yaxis,
                          logx=logx,
                          logy=logy,
                          shape="-",
                          fname=cycle,
                          numtype="time")
        elif state == "hrd":
            data.hrd_new()
        elif state == "kippenhahn":
            data.kippenhahn(0,
                            "model",
                            plot_star_mass=plot_star_mass,
                            c12_bm=plot_c12border)
        elif state == "kip_cont":
            xlims = [xlim[0], xlim[1]]
            ylims = [ylim[0], ylim[1]]
            if (xlims == [0, 0]) and (ylims == [0, 0]):
                xlim = frame.get_attribute("xlim", "value")
                ylim = frame.get_attribute("ylim", "value")
                xlims = [xlim[0], xlim[1]]
                ylims = [ylim[0], ylim[1]]
            data.kip_cont(modstart=xlims[0],
                          modstop=xlims[1],
                          ylims=ylims,
                          xres=xres,
                          yres=yres,
                          engenPlus=plot_engplus,
                          engenMinus=plot_engminus,
                          c12_boundary=plot_c12border,
                          ixaxis=ixaxis)
        elif state == "tcrhoc":
            lims = [xlim[0], xlim[1], ylim[0], ylim[1]]
            if lims == [0, 0, 0, 0]:
                lims = [3.0, 10.0, 8.0, 10.0]
            data.tcrhoc(lims=lims)
        elif state == "movie_iso_abund":
            cycles = data.se.cycles
            cyc_min = cycles.index("%010d" % (cycle_range[0], ))
            cyc_max = cycles.index("%010d" % (cycle_range[1], ))
            cycles = cycles[cyc_min:cyc_max:sparsity]
            display(
                data.movie(cycles,
                           "iso_abund",
                           amass_range=amass,
                           mass_range=mass,
                           ylim=ylim))
        elif state == "movie_abu_chart":
            cycles = data.se.cycles
            cyc_min = cycles.index("%010d" % (cycle_range[0], ))
            cyc_max = cycles.index("%010d" % (cycle_range[1], ))
            cycles = cycles[cyc_min:cyc_max:sparsity]
            plotaxis = [xlim[0], xlim[1], ylim[0], ylim[1]]
            display(
                data.movie(cycles,
                           "abu_chart",
                           mass_range=mass,
                           ilabel=ilabel,
                           imlabel=imlabel,
                           imagic=imagic,
                           plotaxis=plotaxis))
        elif state == "get_data":
            if variable_name == "":
                print("No variable name.")
            else:
                global_namespace[variable_name] = data.get(xax)
                print(
                    "\nThe data " + str(xax) +
                    " is loaded into the global namespace under the variable name \""
                    + str(variable_name) + "\".")
        elif state == "nugrid_get_data":
            if variable_name == "":
                print("No variable name.")
            else:
                global_namespace[variable_name] = data.se.get(cycle, xax)
                print(
                    "\nThe data " + str(xax) +
                    " is loaded into the global namespace under the variable name \""
                    + str(variable_name) + "\".")

    frame.set_state_callbacks("variable_name", variable_name_handler)
    frame.set_state_callbacks("yres", yres_handler)
    frame.set_state_callbacks("xres", xres_handler)
    frame.set_state_callbacks("select_plot", sel_plot)
    frame.set_state_callbacks("movie_type", sel_movie_plot)
    frame.set_state_callbacks("generate_plot",
                              make_plot,
                              attribute=None,
                              type="on_click")

    frame.set_object("page_plotting", widgets.VBox())
    frame.set_object("select_plot", widgets.Dropdown())
    frame.set_object("warning_msg", widgets.HTML())
    frame.set_object("plot_name", widgets.HTML())
    frame.set_object("movie_type", widgets.Dropdown())
    frame.set_object("variable_name", widgets.Text())

    frame.set_object("cycle_sparsity_group", widgets.HBox())
    frame.set_object("cycle", widgets.IntSlider())
    frame.set_object("cycle_range", widgets.IntRangeSlider())
    frame.set_object("sparsity", widgets.Text())

    frame.set_object("xax", widgets.HBox())
    frame.set_object("xaxis", widgets.Select())
    frame.set_object("logx", widgets.Checkbox())
    frame.set_object("yax", widgets.HBox())
    frame.set_object("yaxis", widgets.SelectMultiple())
    frame.set_object("logy", widgets.Checkbox())

    frame.set_object("mass_settings", widgets.VBox())
    frame.set_object("set_amass", widgets.Checkbox())
    frame.set_object("amass_range", widgets.IntRangeSlider())
    frame.set_object("set_mass", widgets.Checkbox())
    frame.set_object("mass_range", widgets.FloatRangeSlider())
    frame.set_object("lbound", widgets.FloatRangeSlider())

    frame.set_object("lim_settings", widgets.VBox())
    frame.set_object("set_lims", widgets.Checkbox())
    frame.set_object("ixaxis", widgets.Dropdown())
    frame.set_object("ylim", widgets.FloatRangeSlider())
    frame.set_object("xlim", widgets.FloatRangeSlider())
    frame.set_object("yres", widgets.Text())
    frame.set_object("xres", widgets.Text())

    frame.set_object("stable", widgets.Checkbox())

    frame.set_object("abu_settings", widgets.HBox())
    frame.set_object("ilabel", widgets.Checkbox())
    frame.set_object("imlabel", widgets.Checkbox())
    frame.set_object("imagic", widgets.Checkbox())

    frame.set_object("kipp_settings", widgets.HBox())
    frame.set_object("plot_star_mass", widgets.Checkbox())
    frame.set_object("plot_c12border", widgets.Checkbox())
    frame.set_object("plot_engminus", widgets.Checkbox())
    frame.set_object("plot_engplus", widgets.Checkbox())

    frame.set_object("generate_plot", widgets.Button())

    update_dir_bar_list()
    frame.display_object("window")
Example #9
0
def show3D_comparison(image,
                      gt,
                      pred,
                      bbox,
                      save_dir='paper_figs/',
                      show_all_legend=True):
    '''
    show 3d comparison plot of ground truth and prediction. 
    Four views: original CT image with zoomed in bbox, ground truth overlay on the image, 
                         prediction overlay on the image, gt and pred contour outline comparison

    image: CT image of dimension 3
    gt: a list of 2 elements, the first is ground truth mask and the second is ground truth contour
    pred: a list of 2 elements, the first is predicted mask and the second is predicted contour
    bbox: [start, end], plot zoomed in region (defined by this param) for view 2 - 4
    '''
    continuous_update = False
    #     n_img = 1 + sum([not img is None for img in masks])
    start, end = bbox
    params = {
        'z': 0,
        'level': 0,
        'width': 1000,
        'show_mask': True,
        'start': start,
        'end': end
    }
    z_slider = w.IntSlider(min=0,
                           max=image.shape[0] - 1,
                           step=1,
                           value=params['z'],
                           continuous_update=continuous_update,
                           description="z")
    level_slider = w.IntSlider(min=-1024,
                               max=1000,
                               step=1,
                               value=params['level'],
                               continuous_update=continuous_update,
                               description="level")
    width_slider = w.IntSlider(min=-1024,
                               max=2000,
                               step=1,
                               value=params['width'],
                               continuous_update=continuous_update,
                               description="width")
    mask_checkbox = w.Checkbox(value=True,
                               description='show mask',
                               disabled=False)

    N = 3
    plt.rcParams['legend.markerscale'] = 0.2
    fig, axes = plt.subplots(1, N)
    plt.subplots_adjust(hspace=0)
    for i in range(N):
        axes[i].set_axis_off()

    def on_z_value_change(change):
        params['z'] = change.new
        plot_compare_figure(image, gt, pred, params, save_dir, show_all_legend)

    def on_level_value_change(change):
        params['level'] = change.new
        plot_compare_figure(image, gt, pred, params, save_dir, show_all_legend)

    def on_width_value_change(change):
        params['width'] = change.new
        plot_compare_figure(image, gt, pred, params, save_dir, show_all_legend)

    def on_mask_value_change(change):
        params['show_mask'] = change.new
        plot_compare_figure(image, gt, pred, params, save_dir, show_all_legend)

    display(z_slider, level_slider, width_slider, mask_checkbox)

    z_slider.observe(on_z_value_change, names='value')
    level_slider.observe(on_level_value_change, names='value')
    width_slider.observe(on_width_value_change, names='value')
    mask_checkbox.observe(on_mask_value_change, names='value')

    plot_compare_figure(image, gt, pred, params, save_dir, show_all_legend)
Example #10
0
def show3Dimg2(image, *masks):
    '''
    Plot contour and mask on original CT image using matplotlib
    image: CT image of dimension 3.
    *masks: usually consists of [mask, contour], then contour 
            would be plot using alpha=1 and mask using alpha 0.5.
    '''
    continuous_update = False
    n_img = 1 + sum([not img is None for img in masks])
    params = {'z': 0, 'level': 0, 'width': 1000, 'show_mask': True}
    z_slider = w.IntSlider(min=0,
                           max=image.shape[0] - 1,
                           step=1,
                           value=params['z'],
                           continuous_update=continuous_update,
                           description="z")
    level_slider = w.IntSlider(min=-1024,
                               max=1000,
                               step=1,
                               value=params['level'],
                               continuous_update=continuous_update,
                               description="level")
    width_slider = w.IntSlider(min=-1024,
                               max=2000,
                               step=1,
                               value=params['width'],
                               continuous_update=continuous_update,
                               description="width")
    mask_checkbox = w.Checkbox(value=True,
                               description='show mask',
                               disabled=False)

    def plot_figure():
        z = params['z']
        level = params['level']
        width = params['width']
        show_mask = params['show_mask']

        plt.imshow(image[z],
                   cmap='gray',
                   vmin=level - width / 2,
                   vmax=level + width / 2)

        if show_mask:
            for i in range(len(masks)):
                mask = masks[i].astype(np.float32)
                mask[mask == 0] = np.nan
                plt.imshow(mask[z],
                           cmap=custom_cmap,
                           alpha=0.5 * (i + 1),
                           vmin=1,
                           vmax=28)

        plt.axis('off')
        plt.legend(handles=patches1,
                   bbox_to_anchor=(1.01, 1),
                   loc=2,
                   borderaxespad=0.)

        plt.show()

    def on_z_value_change(change):
        params['z'] = change.new
        plot_figure()

    def on_level_value_change(change):
        params['level'] = change.new
        plot_figure()

    def on_width_value_change(change):
        params['width'] = change.new
        plot_figure()

    def on_mask_value_change(change):
        params['show_mask'] = change.new
        plot_figure()

    display(z_slider, level_slider, width_slider, mask_checkbox)

    z_slider.observe(on_z_value_change, names='value')
    level_slider.observe(on_level_value_change, names='value')
    width_slider.observe(on_width_value_change, names='value')
    mask_checkbox.observe(on_mask_value_change, names='value')

    plot_figure()
Example #11
0
def four_panel_horizontal(var,
                          src_dir=WORK_DIR,
                          extract=True,
                          extr_kwargs={},
                          load=True,
                          load_kwargs={},
                          debug=False):

    var_name = var.varname

    # Extract the variables we want to plot, if necessary
    if extract:
        var.extract(src_dir,
                    act_cases=CASES_ACT,
                    aer_cases=CASES_AER,
                    **extr_kwargs)
    else:
        if debug: print("skipping extraction")

    # Load into memory
    if load:
        var.load_datasets(src_dir, act_cases=CASES_ACT, aer_cases=CASES_AER)
    else:
        if debug: print("skipping loading")

    # Coerce to DataArray
    sample = var.data[CASES_ACT[0], CASES_AER[0]]
    if isinstance(sample, Dataset):
        var.apply(lambda ds: ds[var.varname])
        if debug:
            print("converted to dataarray from %r" % type(sample))
    data_dict = var.data

    # Set up area grid for weighted global averages
    ds = data_dict[CASES_ACT[0], CASES_AER[0]]
    area = area_grid(ds.lon, ds.lat)
    total_area = np.sum(area.data)

    # Compute PD-PI difference
    max_diff = 0.
    max_level = 0.
    if debug: print("Reading...")
    for act in CASES_ACT:
        if debug: print("   ", act)
        exp_pd = data_dict[act, "F2000"]
        exp_pi = data_dict[act, "F1850"]
        abs_diff = exp_pi - exp_pd

        case_max_diff = np.max(abs_diff.data)
        if debug: print("   max diff", case_max_diff)
        if case_max_diff > max_diff:
            max_diff = case_max_diff

        _, case_max_level = min_max_cubes(exp_pd, exp_pi)
        if debug: print("   max level", case_max_level)
        if np.abs(case_max_level) > max_level:
            max_level = case_max_level

    if debug:
        print("Final max diff/level -", max_diff, max_level)

    #################################################################

    act_control = widgets.Dropdown(description="Activation Case",
                                   options=CASES_ACT)
    proj_control = widgets.Dropdown(description="Map Projection",
                                    options=["PlateCarree", "Robinson"])
    max_level_trunc = widgets.FloatText(description="Trunc level",
                                        value=max_level)

    abs_top = np.ceil(1.5 * max_diff)
    step = 0.01 if abs_top <= 1. else 0.1
    if debug:
        print("absolute slider range - ", 0., abs_top)
        print("                 step - ", step)
    abs_control = widgets.FloatSlider(description="Max Abs. Difference",
                                      value=abs_top,
                                      min=0.,
                                      max=abs_top,
                                      width=150.,
                                      step=step)
    rel_control = widgets.IntSlider(description="Max Rel. Difference",
                                    value=50,
                                    min=0,
                                    max=150,
                                    width=150.)
    reverse_cmap = widgets.Checkbox(description="Reverse colormap",
                                    value=False,
                                    width=150.)
    colormap_text = widgets.Text(description="Colormap on PD/PI",
                                 value="cubehelix_r")
    plot_button = widgets.Button(description="Make Plot")
    save_quality = widgets.Dropdown(description="Save quality",
                                    options=["quick", "production", "vector"])
    save_filename = widgets.Text(description="Save filename",
                                 value="%s_horiz_PD-PI" % var_name)
    save_button = widgets.Button(description="Save Figure")

    form = widgets.VBox(width=1000)
    hbox_make = widgets.HBox()
    hbox_make.children = [act_control, proj_control, plot_button]
    hbox_diff = widgets.HBox()
    hbox_diff.children = [abs_control, rel_control]
    hbox_cmap = widgets.HBox()
    hbox_cmap.children = [max_level_trunc, reverse_cmap, colormap_text]
    hbox_save = widgets.HBox()
    hbox_save.children = [save_quality, save_filename, save_button]
    form.children = [hbox_make, hbox_diff, hbox_cmap, hbox_save]

    def _driver(*args, **kwargs):
        if not debug: clear_output()

        # Save the fig for later reference
        global fig
        fig = plt.figure("4panel_PD-PI", figsize=(12, 8))
        fig.clf()
        fig.set_rasterized(True)

        exp_pd = data_dict[act_control.value, "F2000"]
        exp_pi = data_dict[act_control.value, "F1850"]
        pd_vs_pi_summary(exp_pd, exp_pi, area, max_level_trunc.value,
                         abs_control.value, rel_control.value,
                         reverse_cmap.value, colormap_text.value,
                         proj_control.value, fig)

    def _savefig(*args, **kwargs):
        global fig
        save_figure(save_filename.value + ".4panel",
                    fig=fig,
                    qual=save_quality.value)

    plot_button.on_click(_driver)
    save_button.on_click(_savefig)

    return display(form)
Example #12
0
def start_PPM(global_namespace, local_dir="./"):
    frame = framework.framework()
    frame.set_default_display_style(padding="0.25em",
                                    background_color="white",
                                    border_color="LightGrey",
                                    border_radius="0.5em")
    frame.set_default_io_style(padding="0.25em",
                               margin="0.25em",
                               border_color="LightGrey",
                               border_radius="0.5em")

    group_style = {
        "border_style": "none",
        "border_radius": "0em",
        "width": "100%"
    }
    text_box_style = {"width": "10em"}
    button_style = {"font_size": "1.25em", "font_weight": "bold"}
    first_tab_style = {"border_radius": "0em 0.5em 0.5em 0.5em"}

    states_plotting = ["plot_prof_time", "plot_tEkmax", "plot_vprofs", "get"]
    states_loaded = ["data_loaded"] + states_plotting
    states = states_loaded

    frame.add_state(states)

    frame.set_state_data("data_sets", [])
    frame.set_state_data("data_set_count", 0)
    frame.set_state_data("dir", os.path.abspath(local_dir))
    frame.set_state_data("yaxis_options", [""], "plot_prof_time")
    frame.set_state_data("yaxis_options", [""], "get")
    frame.set_state_data("cycles", [])
    frame.set_state_data("variable_name_timer", None)

    def add_data_set(data, name):
        data_set_count = frame.get_state_data("data_set_count")
        data_sets = frame.get_state_data("data_sets")
        widget_name = "data_set_widget_#" + str(data_set_count)

        frame.add_io_object(widget_name)
        frame.set_state_attribute(widget_name, visible=True, description=name)
        frame.set_object(widget_name, widgets.Checkbox())

        data_sets.append((data, name, widget_name))
        frame.set_state_children("data_sets", [widget_name])
        frame.set_state_data("data_sets", data_sets)
        data_set_count += 1
        frame.set_state_data("data_set_count", data_set_count)

    def remove_data_set():
        data_sets = frame.get_state_data("data_sets")
        children = ["data_sets_title"]
        tmp_data_sets = []
        for i in xrange(len(data_sets)):
            widget_name = data_sets[i][2]
            if frame.get_attribute(widget_name, "value"):
                frame.remove_object(widget_name)
            else:
                children.append(widget_name)
                tmp_data_sets.append(data_sets[i])
        data_sets = tmp_data_sets
        frame.set_state_children("data_sets", children, append=False)
        frame.set_state_data("data_sets", data_sets)

        if data_sets == []:
            frame.set_state()

    def update_dir_bar_list():
        dir = frame.get_state_data("dir")
        dirs = [".", ".."] + os.listdir(dir)

        frame.set_state_attribute("address_bar", value=dir)
        frame.set_state_attribute("directory_list", options=dirs)

    frame.add_display_object("window")
    frame.add_io_object("Title")

    frame.add_display_object("widget_data_set_group")
    frame.add_display_object("widget")

    frame.add_display_object("data_sets")
    frame.add_io_object("data_sets_title")

    ##data page
    frame.add_display_object("data_page")
    frame.add_display_object("file_system_group")
    frame.add_io_object("address_bar")
    frame.add_io_object("directory_list")

    frame.add_display_object("name_load_remove_group")
    frame.add_io_object("data_set_name")
    frame.add_io_object("data_set_load")
    frame.add_io_object("data_set_remove")

    ##plotting page
    frame.add_display_object("plotting_page")
    frame.add_io_object("select_plot")
    frame.add_io_object("plot_title")
    frame.add_io_object("warning_msg")

    frame.add_display_object("cycle_range_group")
    frame.add_io_object("cycle")
    frame.add_io_object("cycle_range")
    frame.add_io_object("cycle_sparsity")

    frame.add_io_object("variable_name")

    frame.add_display_object("yaxis_group")
    frame.add_io_object("yaxis")
    frame.add_io_object("logy")

    frame.add_io_object("plot")

    frame.set_state_children("window", ["Title", "widget_data_set_group"])
    frame.set_state_children("widget_data_set_group", ["widget", "data_sets"])

    frame.set_state_children("data_sets", ["data_sets_title"])
    frame.set_state_children("widget", ["data_page", "plotting_page"],
                             titles=["Data", "Plotting"])
    frame.set_state_children("data_page",
                             ["file_system_group", "name_load_remove_group"])
    frame.set_state_children("file_system_group",
                             ["address_bar", "directory_list"])
    frame.set_state_children(
        "name_load_remove_group",
        ["data_set_load", "data_set_remove", "data_set_name"])

    frame.set_state_children("plotting_page", [
        "select_plot", "warning_msg", "plot_title", "variable_name",
        "cycle_range_group", "yaxis_group", "plot"
    ])
    frame.set_state_children("cycle_range_group",
                             ["cycle", "cycle_range", "cycle_sparsity"])
    frame.set_state_children("yaxis_group", ["yaxis", "logy"])

    frame.set_state_attribute("window", visible=True, **group_style)
    frame.set_state_attribute("Title",
                              visible=True,
                              value="<center><h1>PPM explorer</h1></center>")
    frame.set_state_attribute("widget_data_set_group",
                              visible=True,
                              **group_style)
    frame.set_state_attribute("data_sets",
                              visible=True,
                              margin="3.15em 0em 0em 0em")
    frame.set_state_attribute("data_sets_title",
                              visible=True,
                              value="<center><h2>Data Sets</h2></center>",
                              **group_style)
    frame.set_state_attribute("widget", visible=True, **group_style)

    frame.set_state_attribute("data_page", visible=True, **first_tab_style)
    frame.set_state_attribute("file_system_group", visible=True, **group_style)
    frame.set_state_attribute("address_bar", visible=True)
    frame.set_state_attribute("directory_list", visible=True)
    frame.set_state_attribute("name_load_remove_group",
                              visible=True,
                              **group_style)
    frame.set_state_attribute("data_set_name",
                              visible=True,
                              description="Data set name:",
                              placeholder="Enter name",
                              **text_box_style)
    frame.set_state_attribute("data_set_load",
                              visible=True,
                              description="Load data set",
                              **button_style)
    frame.set_state_attribute("data_set_remove",
                              visible=True,
                              description="Remove data set",
                              **button_style)

    def address_bar_handler(widget):
        dir = frame.get_attribute("address_bar", "value")
        if os.path.isdir(dir):
            dir = os.path.abspath(dir)
            frame.set_state_data("dir", dir)
            update_dir_bar_list()
            frame.update()
            frame.set_attributes("address_bar", value=dir)
            frame.set_attributes("directory_list",
                                 value=".",
                                 selected_label=u".")

    def directory_list_handler(name, value):
        dir = frame.get_state_data("dir")
        dir = dir + "/" + frame.get_attribute("directory_list", "value")
        if os.path.isdir(dir):
            dir = os.path.abspath(dir)
            frame.set_state_data("dir", dir)
            update_dir_bar_list()
            frame.update()
            frame.set_attributes("address_bar", value=dir)
            frame.set_attributes("directory_list",
                                 value=".",
                                 selected_label=u".")

    def data_set_load_handler(widget):
        clear_output()
        pyplot.close("all")

        dir = frame.get_attribute("address_bar", "value")
        data_set_count = frame.get_state_data("data_set_count")
        name = frame.get_attribute("data_set_name", "value")
        if name == "":
            name = "Data set - " + "%03d" % (data_set_count + 1, )

        data = ppm.yprofile(dir)
        if data.files != []:
            frame.set_state("data_loaded")

            old_cycs = frame.get_state_data("cycles")
            cycs = data.cycles
            cycs = list(set(cycs) | set(old_cycs))
            cycs.sort()
            frame.set_state_data("cycles", cycs)
            frame.set_state_data("yaxis_options", data.dcols, "plot_prof_time")
            frame.set_state_data("yaxis_options", data.dcols + data.cattrs,
                                 "get")

            frame.set_state_attribute("cycle",
                                      min=cycs[0],
                                      max=cycs[-1],
                                      value=cycs[-1])
            frame.set_state_attribute("cycle_range",
                                      min=cycs[0],
                                      max=cycs[-1],
                                      value=(cycs[0], cycs[-1]))

            add_data_set(data, name)
            frame.update()

    def data_set_remove_handler(widget):
        remove_data_set()
        frame.update()

    frame.set_state_callbacks("address_bar",
                              address_bar_handler,
                              attribute=None,
                              type="on_submit")
    frame.set_state_callbacks("directory_list", directory_list_handler)
    frame.set_state_callbacks("data_set_load",
                              data_set_load_handler,
                              attribute=None,
                              type="on_click")
    frame.set_state_callbacks("data_set_remove",
                              data_set_remove_handler,
                              attribute=None,
                              type="on_click")

    frame.set_object("window", widgets.Box())
    frame.set_object("Title", widgets.HTML())

    frame.set_object("widget_data_set_group", widgets.HBox())
    frame.set_object("widget", widgets.Tab())
    frame.set_object("data_sets", widgets.VBox())
    frame.set_object("data_sets_title", widgets.HTML())

    frame.set_object("data_page", widgets.VBox())

    frame.set_object("file_system_group", widgets.VBox())
    frame.set_object("address_bar", widgets.Text())
    frame.set_object("directory_list", widgets.Select())

    frame.set_object("name_load_remove_group", widgets.HBox())
    frame.set_object("data_set_name", widgets.Text())
    frame.set_object("data_set_load", widgets.Button())
    frame.set_object("data_set_remove", widgets.Button())

    frame.set_state_attribute("plotting_page", visible=True)
    frame.set_state_attribute("select_plot",
                              states_loaded,
                              visible=True,
                              options={
                                  "": "data_loaded",
                                  "Profile time": "plot_prof_time",
                                  "Velocity Profile": "plot_vprofs",
                                  "tEkmax": "plot_tEkmax",
                                  "Get Data": "get"
                              })
    frame.set_state_attribute("warning_msg",
                              visible=True,
                              value="<h3>No data sets loaded!</h3>",
                              **group_style)
    frame.set_state_attribute("warning_msg",
                              "data_loaded",
                              value="<h3>Select plot.</h3>")
    frame.set_state_attribute("warning_msg", states_plotting, visible=False)
    frame.set_state_attribute("plot_title", visible=False, **group_style)
    frame.set_state_attribute("plot_title",
                              "plot_prof_time",
                              visible=True,
                              value="<h3>Prof_time</h3>")
    frame.set_state_attribute("plot_title",
                              "plot_vprofs",
                              visible=True,
                              value="<h3>Plot Velocity Profiles</h3>")
    frame.set_state_attribute("plot_title",
                              "plot_tEkmax",
                              visible=True,
                              value="<h3>tEkmax</h3>")
    frame.set_state_attribute("plot_title",
                              "get",
                              visible=True,
                              value="<h3>Get Data</h3>")

    frame.set_state_attribute("variable_name",
                              "get",
                              visible=True,
                              description="Variable name:",
                              placeholder="Enter name.",
                              **text_box_style)

    frame.set_state_attribute("cycle_range_group",
                              ["plot_prof_time", "plot_vprofs", "get"],
                              visible=True,
                              **group_style)
    frame.set_state_attribute("cycle",
                              "get",
                              visible=True,
                              description="Cycle:")
    frame.set_state_attribute("cycle_range", ["plot_prof_time", "plot_vprofs"],
                              visible=True,
                              description="Cycle range:")
    frame.set_state_attribute("cycle_sparsity",
                              ["plot_prof_time", "plot_vprofs"],
                              visible=True,
                              description="Cycle sparsity",
                              value=1)

    frame.set_state_attribute("yaxis_group",
                              ["plot_prof_time", "plot_vprofs", "get"],
                              visible=True,
                              **group_style)
    frame.set_state_attribute("yaxis", ["plot_prof_time", "get"],
                              visible=True,
                              description="Yaxis:",
                              options=[""])
    frame.set_state_attribute("logy", ["plot_prof_time", "plot_vprofs"],
                              visible=True,
                              description="Log Y axis:")

    frame.set_state_attribute("plot",
                              states_loaded,
                              visible=True,
                              description="Generate Plot",
                              **button_style)
    frame.set_state_attribute("plot", "get", description="Get Data")

    def variable_name_full_validation(value):
        frame.set_attributes("variable_name",
                             value=token_text(value, strict=True))
        frame.set_state_data("variable_name_timer", None)

    def variable_name_handler(name, value):
        value = token_text(value)
        frame.set_attributes("variable_name", value=value)

        timer = frame.get_state_data("variable_name_timer")
        if (value != token_text(value, strict=True)):
            if timer != None:
                timer.cancel()
            timer = threading.Timer(1.0,
                                    variable_name_full_validation,
                                    kwargs={"value": value})
            timer.start()
        else:
            if timer != None:
                timer.cancel()
            timer = None
        frame.set_state_data("variable_name_timer", timer)

    def select_plot_handler(name, value):
        if value in ["plot_prof_time", "get"]:
            frame.set_state_attribute("yaxis",
                                      value,
                                      options=frame.get_state_data(
                                          "yaxis_options", value))
        frame.set_state(value)

    def plot_handler(widget):
        clear_output()
        pyplot.close("all")

        state = frame.get_state()
        data_sets = frame.get_state_data("data_sets")

        variable_name = frame.get_attribute("variable_name", "value")
        cycle = frame.get_attribute("cycle", "value")
        cycle_min, cycle_max = frame.get_attribute("cycle_range", "value")
        cycle_sparsity = int(frame.get_attribute("cycle_sparsity", "value"))
        if state in ["plot_prof_time", "plot_vprofs"]:
            cycles = range(cycle_min, cycle_max, cycle_sparsity)

        yaxis = frame.get_attribute("yaxis", "value")
        logy = frame.get_attribute("logy", "value")

        no_runs = True

        if state == "plot_prof_time":
            for data, name, widget_name in data_sets:
                if frame.get_attribute(widget_name, "value"):
                    cycs = data.cycles
                    cycs = list(set(cycs) & set(cycles))
                    cycs.sort()
                    no_runs = False
                    data.prof_time(cycs, yaxis_thing=yaxis, logy=logy)
        elif state == "plot_vprofs":
            for data, name, widget_name in data_sets:
                if frame.get_attribute(widget_name, "value"):
                    cycs = data.cycles
                    cycs = list(set(cycs) & set(cycles))
                    cycs.sort()
                    no_runs = False
                    data.vprofs(cycs, log_logic=logy)
        elif state == "plot_tEkmax":
            i = 0
            for data, name, widget_name in data_sets:
                if frame.get_attribute(widget_name, "value"):
                    no_runs = False
                    data.tEkmax(ifig=1, label=name, id=i)
                    i += 1
        elif state == "get":
            data_out = []
            i = 0
            for data, name, widget_name in data_sets:
                if frame.get_attribute(widget_name, "value"):
                    if cycle in data.cycles:
                        i += 1
                        no_runs = False
                        if yaxis in data.cattrs:
                            data_out.append(data.get(attri=yaxis))
                        else:
                            data_out.append(data.get(attri=yaxis, fname=cycle))
                    else:
                        print("cycle out of range for " + name)
            if data_out != []:
                if i == 1:
                    data_out = data_out[0]

                if variable_name == "":
                    print("No variable name.")
                else:
                    global_namespace[variable_name] = data_out
                    print(
                        "\nThe selected data is now loaded into the global namespace under the variable name \""
                        + variable_name + "\".")

        if no_runs:
            print "No data sets selected."

    frame.set_state_callbacks("variable_name", variable_name_handler)
    frame.set_state_callbacks("select_plot", select_plot_handler)
    frame.set_state_callbacks("plot",
                              plot_handler,
                              attribute=None,
                              type="on_click")

    frame.set_object("plotting_page", widgets.VBox())
    frame.set_object("select_plot", widgets.Dropdown())
    frame.set_object("warning_msg", widgets.HTML())
    frame.set_object("plot_title", widgets.HTML())
    frame.set_object("variable_name", widgets.Text())
    frame.set_object("cycle_range_group", widgets.HBox())
    frame.set_object("cycle", widgets.IntSlider())
    frame.set_object("cycle_range", widgets.IntRangeSlider())
    frame.set_object("cycle_sparsity", widgets.IntText())

    frame.set_object("yaxis_group", widgets.HBox())
    frame.set_object("yaxis", widgets.Select())
    frame.set_object("logy", widgets.Checkbox())
    frame.set_object("plot", widgets.Button())

    update_dir_bar_list()
    frame.display_object("window")