コード例 #1
0
    def fig(self, ix, raw=False, alt_df=None):
        """Generate interactive plot of a specified target.

        alt_df: df to use for fig; None if using self.pbb
        ix: index of the dataframe to plot
        raw: slider for raw image
        """

        if alt_df is None:
            df = self.pbbs
        else:
            df = alt_df

        row = df.loc[ix]
        print row
        pid, z, y, x, d = row['pid'], row['z'],\
                          row['y'],row['x'],row['d']

        import IPython.html.widgets as w
        if not raw:
            img = np.load(os.path.join(self.PREP, pid + '_clean.npy'))
        else:
            img, origin, spacing = utils.load_itk_image(os.path.join(self.RAW,pid + '.mhd'))

            # convert z,y,x,d to raw voxel coordinates
            v = np.array([z,y,x])
            ebox_origin = np.load(os.path.join(self.PREP,pid+'_ebox_origin.npy'))
            v = v + ebox_origin
            prep_spacing = np.load(os.path.join(self.PREP,pid+'_spacing.npy'))
            v = utils.voxelToWorldCoord(v, origin, prep_spacing)
            v = utils.worldToVoxelCoord(v, origin, spacing)
            z, y, x = v[0], v[1], v[2]
            d = d * prep_spacing[1] / spacing[1]

            # convert title
            row = row.copy()
            row['z'] = z
            row['y'] = y
            row['x'] = x
            row['d'] = d

        def fz(k):
            utils.showTargetImgComp(img, [k,y,x], plt, d=d, t=str(row))
        def fy(k):
            utils.showTargetImgComp(np.swapaxes(img,0,1), [k,z,x], plt, d=d, t=str(row))
        def fx(k):
            utils.showTargetImgComp(np.swapaxes(img,0,2), [k,y,z], plt, d=d, t=str(row))
        w.interact(fz, k=w.IntSlider(min=0,max=img.shape[0]-1,step=1,value=z))
        w.interact(fy, k=w.IntSlider(min=0,max=img.shape[1]-1,step=1,value=y))
        w.interact(fx, k=w.IntSlider(min=0,max=img.shape[2]-1,step=1,value=x))
コード例 #2
0
ファイル: visualize.py プロジェクト: yangsenwxy/UaNet
def show_image_and_mask(img):
    """
    Given CT img, produce interactive jupyter notebook slider across axial slice
    img: [D,H,W] or [D,H,W,3]
    """
    def fz(k):
        plt.imshow(img[k], vmin=img.min(), vmax=img.max() + 1)
        plt.show()

    w.interact(fz, k=w.IntSlider(min=0, max=img.shape[0] - 1, step=1, value=0))
コード例 #3
0
ファイル: visualize.py プロジェクト: yangsenwxy/UaNet
def show3Dimg(image, *imgs):
    n_img = 1 + sum([not img is None for img in imgs])

    def fz(k):
        plt.subplot(1, n_img, 1)
        colorbar(plt.imshow(image[k]))

        for i in range(len(imgs)):
            plt.subplot(1, n_img, 2 + i)
            colorbar(plt.imshow(imgs[i][k], vmin=0, vmax=30))

        plt.show()

    w.interact(fz,
               k=w.IntSlider(min=0, max=image.shape[0] - 1, step=1, value=0))
コード例 #4
0
def create_linewidth_slider(desc, *args, **kwargs):
    """ Creates a slider for linewidth-type settings
    in `matplotlib.rcParams`.

    :param desc: The description label of the widget.

    :returns: The configured slider.
    """
    from_rc = mpl.rcParams[desc]

    val = 0

    # TODO deal with strings
    if not isinstance(from_rc, str):
        val = from_rc

    return widgets.IntSlider(min=0,
                             max=9,
                             value=val,
                             description=desc,
                             *args,
                             **kwargs)
コード例 #5
0
ファイル: turing.py プロジェクト: dsteurer/cs4814fa15
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)
コード例 #6
0
Fs = 2.**12

options = {
    "sine": 0,
    "cosine": 1,
    "sinc": 2,
    "block": 3,
    "impulse": 4,
    "blocktrain": 5,
    "damped oscillation": 6,
    "carrier + signal": 7
}

# Extra options for sine
select_sine_amplitude = widgets.IntSlider(min=1,
                                          max=5,
                                          description="Amplitude:")
select_sine_frequency = widgets.IntSlider(min=1.,
                                          max=200.,
                                          step=20.,
                                          description="Frequency:")
box_sine = widgets.Box(children=[select_sine_amplitude, select_sine_frequency],
                       visible=True)
# Extra options for cosine
select_cosine_amplitude = widgets.IntSlider(min=1,
                                            max=5,
                                            description="Amplitude:")
select_cosine_frequency = widgets.IntSlider(min=1.0,
                                            max=200.0,
                                            step=20.0,
                                            description="Frequency:")
コード例 #7
0
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")
コード例 #8
0

# Graph object
g = GraphWidget(foodmap(1961))


# Definition of a class that will update the graph object
class z_data:
    def __init__(self):
        self.z = food[str(int(1961))]

    def on_z_change(self, name, old_value, new_value):
        self.z = food[str(int(new_value))]
        self.title = "Food Supply (kcal per capita) in " + str(new_value)
        self.replot()

    def replot(self):
        g.restyle({'z': [self.z]})
        g.relayout({'title': self.title})


# Interactive object
edu_slider = widgets.IntSlider(min=1961, max=2011, value=1961, step=1)
edu_slider.description = 'Year'
edu_slider.value = 1961

z_state = z_data()
edu_slider.on_trait_change(z_state.on_z_change, 'value')

display(edu_slider)
display(g)
コード例 #9
0
ファイル: visualize.py プロジェクト: yangsenwxy/UaNet
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)
コード例 #10
0
ファイル: visualize.py プロジェクト: yangsenwxy/UaNet
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()
コード例 #11
0
def plot_pulse_files(fileNames, firstSeqNum=0):
    '''
    plot_pulse_files(fileNames, firstSeqNum=0)

    Helper function to plot a list of AWG files.  In an iPython notebook the plots will be in line with
    dynamic updating.  For iPython consoles a static html file will be generated with the firstSeqNum.
    '''
    #If we only go one filename turn it into a list
    if isinstance(fileNames, str):
        fileNames = [fileNames]

    wfs = {}
    dataDict = {}
    lineNames = []
    title = ""

    for fileName in sorted(fileNames):

        #Assume a naming convention path/to/file/SequenceName-AWGName.h5
        AWGName = (os.path.split(
            os.path.splitext(fileName)[0])[1]).split('-')[1]
        #Strip any _ suffix
        if '_' in AWGName:
            AWGName = AWGName[:AWGName.index('_')]

        title += os.path.split(os.path.splitext(fileName)[0])[1] + "; "

        wfs[AWGName] = read_sequence_file(Libraries.instrumentLib[AWGName],
                                          fileName)

        for (k, seqs) in sorted(wfs[AWGName].items()):
            if not all_zero_seqs(seqs):
                lineNames.append(AWGName + '-' + k)
                dataDict[lineNames[-1] + "_x"] = np.arange(
                    len(seqs[firstSeqNum]))
                dataDict[lineNames[-1]] = seqs[firstSeqNum] + 2 * (
                    len(lineNames) - 1)

    #Remove trailing semicolon from title
    title = title[:-2]

    source = bk.ColumnDataSource(data=dataDict)
    figH = bk.figure(title=title,
                     plot_width=1000,
                     y_range=(-1, len(dataDict) + 1))

    #Colorbrewer2 qualitative Set3 (http://colorbrewer2.org)
    colours = [
        "#8dd3c7", "#ffffb3", "#bebada", "#fb8072", "#80b1d3", "#fdb462",
        "#b3de69", "#fccde5", "#d9d9d9", "#bc80bd", "#ccebc5", "#ffed6f"
    ]

    for ct, k in enumerate(lineNames):
        figH.line(k + "_x",
                  k,
                  source=source,
                  color=colours[ct % len(colours)],
                  line_width=2,
                  legend=k)

    if in_ipynb():
        #Setup inline plotting with slider updating of data

        def update_plot(_, seqNum):
            for ct, k in enumerate(lineNames):
                AWGName, chName = k.split('-')
                source.data[k + "_x"] = np.arange(
                    len(wfs[AWGName][chName][seqNum - 1]))
                source.data[k] = wfs[AWGName][chName][seqNum - 1] + 2 * ct
            source.push_notebook()

        #widgets.interact(update_plot, seqNum=(1, len(wfs[AWGName]["ch1"])), div=widgets.HTMLWidget(value=notebook_div(figH)))

        slider = widgets.IntSlider(value=firstSeqNum + 1,
                                   min=1,
                                   max=len(wfs[AWGName]["ch1"]),
                                   step=1,
                                   description="Sequence (of {}):".format(
                                       len(seqs)))
        slider.on_trait_change(update_plot, 'value')
        plotBox = widgets.HTML(value=notebook_div(figH))
        appBox = widgets.Box()
        appBox.children = [slider, plotBox]
        display(appBox)

    else:
        #Otherwise dump to a static file
        bk.show(figH)
コード例 #12
0
ファイル: widgets.py プロジェクト: darothen/darpy
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)
コード例 #13
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")