コード例 #1
0
def slider(aoi, pid, chipsize=512, extend=512, tms=['Google']):

    workdir = config.get_value(['paths', 'temp'])
    path = f'{workdir}/{aoi}/{pid}/'
    bg_path = f'{path}/backgrounds/'

    for t in tms:
        if not os.path.isfile(f'{bg_path}{t.lower()}.tif'):
            bg.by_pid(aoi, pid, chipsize, extend, t, True)

    with open(f'{path}info.json', "r") as f:
        json_data = json.load(f)

    def overlay_parcel(img, geom):
        patche = [
            PolygonPatch(feature,
                         edgecolor="yellow",
                         facecolor="none",
                         linewidth=2) for feature in geom['geom']
        ]
        return patche

    with rasterio.open(f'{bg_path}{tms[0].lower()}.tif') as img:
        img_epsg = img.crs.to_epsg()
        geom = spatial_utils.transform_geometry(json_data, img_epsg)
        patches = overlay_parcel(img, geom)

    selection = SelectionSlider(options=tms,
                                value=tms[0],
                                disabled=False,
                                continuous_update=False,
                                orientation='horizontal',
                                readout=True)
    output = Output()

    fig, ax = plt.subplots(figsize=(10, 10))
    with output:
        with rasterio.open(f'{bg_path}{selection.value.lower()}.tif') as img:
            for patch in patches:
                ax.add_patch(copy(patch))
            show(img, ax=ax)
        plt.show()

    def on_value_change(change):
        with output:
            output.clear_output()
            fig, ax = plt.subplots(figsize=(10, 10))
            with rasterio.open(
                    f'{bg_path}{selection.value.lower()}.tif') as im:
                for patch in patches:
                    ax.add_patch(copy(patch))
                show(im, ax=ax)
            plt.show()

    selection.observe(on_value_change, names='value')
    return VBox([selection, output])
コード例 #2
0
 def test_index_trigger(self):
     slider = SelectionSlider(options=['a', 'b', 'c'])
     observations = []
     def f(change):
         observations.append(change.new)
     slider.observe(f, 'index')
     assert slider.index == 0
     slider.options = [4, 5, 6]
     assert slider.index == 0
     assert slider.value == 4
     assert slider.label == '4'
     assert observations == [0]
コード例 #3
0
 def test_index_trigger(self):
     slider = SelectionSlider(options=['a', 'b', 'c'])
     observations = []
     def f(change):
         observations.append(change.new)
     slider.observe(f, 'index')
     assert slider.index == 0
     slider.options = [4, 5, 6]
     assert slider.index == 0
     assert slider.value == 4
     assert slider.label == '4'
     assert observations == [0]
コード例 #4
0
ファイル: common.py プロジェクト: kingjr/mous_annot
def modify_tree(doc, distance=80):
    """Interactive plotting: expect spacy doc structure
    e.g.
    doc = nlp('He is here')
    modify_tree(doc)
    """
    def get_html(doc, init=False):
        html = displacy.render(doc,
                               style="dep",
                               jupyter=False,
                               options=dict(distance=distance))
        # add preview of compressed tree
        html += '\n\n\n' + str(spacy_to_tree(next(doc.sents).root))
        return html

    # Init parse widgets
    html = widgets.HTML(values=get_html(doc, init=True))
    out = widgets.Output()
    edges = [
        SelectionSlider(options=[w.text + '_%i' % w.i for w in doc],
                        value=str(word.head) + '_%i' % word.head.i,
                        description=str(word)) for word in doc
    ]
    dep = ('ROOT', 'acl', 'acomp', 'advcl', 'advmod', 'agent', 'amod', 'appos',
           'attr', 'aux', 'auxpass', 'case', 'cc', 'ccomp', 'compound',
           'compound:prt', 'conj', 'cop', 'csubj', 'dative', 'dep', 'det',
           'det:nummod', 'dobj', 'expl', 'expl:pv', 'flat', 'intj', 'iobj',
           'mark', 'meta', 'neg', 'nmod', 'npadvmod', 'nsubj', 'nsubjpass',
           'nummod', 'obj', 'obl', 'oprd', 'parataxis', 'pcomp', 'pobj',
           'poss', 'preconj', 'predet', 'prep', 'prt', 'punct', 'quantmod',
           'relcl', 'subtok', 'xcomp')

    dep = [
        Dropdown(options=dep, value=str(word.dep_), description=' ')
        for word in doc
    ]

    def plot_tree(*args, **kwargs):
        # Update values
        for word, c in zip(doc, edges):
            word.head = [w for w in doc][c.index]

        for word, value in zip(doc, dep):
            word.dep_ = value.value

        html.value = get_html(doc)

    # interaction controls
    controls = np.ravel([z for z in zip(edges, dep)])
    interact(plot_tree, **dict(('w%i' % i, v) for i, v in enumerate(controls)))
    clear_output(wait=True)

    # plot
    display(VBox([HBox([VBox(edges), VBox(dep)]), html]))
コード例 #5
0
ファイル: common.py プロジェクト: kingjr/mous_annot
    def __init__(self, sentences, nlp, data_path='./', distance=80):
        self.sentences = sentences
        self.nlp = nlp
        self.data_path = data_path

        self.select = SelectionSlider(options=sentences.index,
                                      description='sentence id')
        self.select.on_trait_change(self.load)

        self.save_button = widgets.Button(description='save')
        self.save_button.on_click(self.save)

        self.reset_button = widgets.Button(description='reset')
        self.reset_button.on_click(self.reset)

        self.load_button = widgets.Button(description='load')
        self.load_button.on_click(self.load)
        self.distance = distance

        self.load()
        self.update()
コード例 #6
0
def _dashboard(datadir,
               *,
               nodes,
               continuous_sender=False,
               node_legend="node",
               node_key='node_id'):
    """
    some contorsions with ipywidgets to show controls in
    a compact way
    create and display a dashboard
    return a dictionary name->widget suitable for interactive_output

    """
    show_node_slider = len(nodes) > 1

    lfull = Layout(width='100%')
    lsmall = Layout(width='25%')
    llarge = Layout(width='75%')

    # no longer possible to choose datadir here
    w_datadir = fixed(datadir)

    interference_options = available_interference_options(datadir)
    default = 'None' if 'None' in interference_options \
              else list(interference_options.keys())[0]
    w_interference = Dropdown(options=interference_options,
                              value=default,
                              description="Interference amplitude in % : ",
                              layout=lsmall if show_node_slider else lfull)
    row = [w_interference]
    mapping = dict(datadir=w_datadir, interference=w_interference)

    if not show_node_slider:
        w_node = fixed(nodes[0])
    else:
        w_node = SelectionSlider(description=node_legend,
                                 options=nodes,
                                 continuous_update=continuous_sender,
                                 layout=llarge)
        row.append(w_node)
    mapping[node_key] = w_node

    #def update_interferences(info):
    #    # info is a dict with fields like
    #    # 'old', 'new' and 'owner'
    #    new_datadir = info['new']
    #    w_interference.options = available_interference_options(new_datadir)
    #w_datadir.observe(update_interferences, 'value')

    dashboard_widget = HBox(row)
    display(dashboard_widget)
    return mapping
コード例 #7
0
ファイル: dashboard.py プロジェクト: JawaGL/r2lab-demos
def dashboard(datadir, onnodes,continuous_sender = False):
    """
    some contorsions with ipywidgets to show controls in 
    a compact way
    create and display a dashboard 
    return a dictionary name->widget suitable for interactive_output
    """
    # dashboard pieces as widgets
    l75 = Layout(width='75%')
    l50 = Layout(width='50%')
    l32 = Layout(width='32%')
    l25 = Layout(width='25%')
    # all space
    w_datadir = Text(description="run name", value=datadir,
                     layout=l25)
    w_sender = SelectionSlider(description="sender node",
                                options = onnodes,
                                continuous_update=continuous_sender, layout=l75)
    w_power = Dropdown(options=list(range(1, 15)),
                       value=1, description="tx power in dBm", layout=l32)
    w_rate = Dropdown(options=[54], value=54,
                      description="phy rate", layout=l32)
    # yeah, this is a little weird all right
    w_antenna_mask = Dropdown(options=OrderedDict([("1", 1), ("2", 3), ("3", 7)]),
                              value=1,
                              description="number of antennas: ", layout=l50)
    w_channel = Dropdown(options=channel_options,
                         value=10, description="channel", layout=l32)
    w_interference = Dropdown(
                               options = OrderedDict([("-12", -12),("-11", -11)
                                                      ,("-10", -10)
                                                    ,("-9", -9),("-8", -8)
                                                      ,("-7", -7)
                                                      ,("None", "None")
                                                      , ("1", 1)
                                                      , ("2", 2), ("3", 3)
                                                      , ("4", 4)
                                                      , ("5", 5)
                                                      , ("6", 6)
                                                      , ("7", 7)])
                                , value="None",
                                description="Interference power in dBm: ", layout=l50)
    # make up a dashboard
    dashboard = VBox([HBox([w_datadir, w_sender]),
                      HBox([w_power, w_rate, w_channel]),
                      HBox([w_antenna_mask, w_interference])])
    display(dashboard)
    return dict(datadir=w_datadir,
                tx_power=w_power, phy_rate=w_rate, channel=w_channel,
                antenna_mask=w_antenna_mask,
                interference=w_interference,
                source=w_sender)
コード例 #8
0
    def visualize(self, interactive=False):
        """
        This method simply serves as a quick visualization of the portfolio performance, comparing it with the returns
        of the S&P 500 as a benchmark. If interactive is True, and if running in an iPython notebook environment,
        a slider for a date selection appears. This slider allows the user to view the news of the dataset closest to
        such date, as well as the predictor's response to the news.
        """

        if self.portfolio.index.name != 'Date':
            self.portfolio['Date'] = pd.to_datetime(self.portfolio['Date'],
                                                    utc=True)
            self.portfolio.set_index('Date', inplace=True)

        self.market_benchmark = yf.download(
            '^GSPC',
            start=self.data['release_date'].min() - timedelta(days=1),
            end=self.data['release_date'].max())
        self.market_benchmark = (self.market_benchmark[self.price] - self.market_benchmark[self.price][0]) * 100 / \
            self.market_benchmark[self.price][0]

        self.portfolio_benchmark = self.portfolio[self.price_cols].bfill(axis=0).sum(axis=1) * self.starting_amount + \
            self.starting_cash
        self.portfolio_benchmark = (self.portfolio_benchmark - self.portfolio_benchmark[0]) * 100 / \
            self.portfolio_benchmark[0]

        if interactive:
            dates = self.portfolio.index
            options = [(date.strftime(' %d %b %Y '), date) for date in dates]

            selection_range_slider = SelectionSlider(
                value=dates[0],
                options=options,
                description='Select a Date:',
                style={'description_width': 'initial'},
                orientation='horizontal',
                layout={
                    'width': '750px',
                    'height': '50px'
                })
            _ = interact(self.return_selected_date,
                         date=selection_range_slider)
        else:
            _, _ = self.plot_single_frame()
            plt.show()
コード例 #9
0
 def display_result(self):
     if len(self.result) == 2:
         orig = self.result[0][1]
         solv = self.result[1][1]
         display(Label('Problem:'))
         display(orig)
         display(Label('Solution:'))
         display(solv)
     else:
         interact(
             self.result.f,
             i=SelectionSlider(
                 options={
                     iteration: i
                     for i, (iteration, _) in enumerate(self.result.data)
                 },
                 description='Iteration',
             ),
         )
コード例 #10
0
 def test_construction(self):
     SelectionSlider(options=['a', 'b', 'c'])
コード例 #11
0
    def plot_interactive(self, axis=None, rc_params=None, **kwargs):
        """
        Plot map with interactive widgets to explore the non spatial axes.

        Parameters
        ----------
        axis : str
            Axis name to slide through, with the interactive slider. By default
            the first non-spatial axis is used.
        rc_params : dict
            Passed to ``matplotlib.rc_context(rc=rc_params)`` to style the plot.
        **kwargs : dict
            Keyword arguments passed to `WcsNDMap.plot`.

        Examples
        --------
        You can try this out e.g. using a Fermi-LAT diffuse model cube with an energy axis::

            from gammapy.maps import Map

            m = Map.read("$GAMMAPY_EXTRA/datasets/vela_region/gll_iem_v05_rev1_cutout.fits")
            m.plot_interactive(cmap='gnuplot2')

        If you would like to adjust the figure size you can use the ``rc_params`` argument::

            rc_params = {'figure.figsize': (12, 6), 'font.size': 12}
            m.plot_interactive(rc_params=rc_params)
        """
        import matplotlib as mpl
        import matplotlib.pyplot as plt
        from ipywidgets.widgets.interaction import interact
        from ipywidgets import SelectionSlider, RadioButtons

        kwargs.setdefault('interpolation', 'nearest')
        kwargs.setdefault('origin', 'lower')
        kwargs.setdefault('cmap', 'afmhot')

        rc_params = rc_params or {}
        stretch = kwargs.pop('stretch', 'sqrt')

        if self.geom.is_image:
            raise TypeError('Use .plot() for 2D Maps')

        axis = axis or self.geom.axes[0].name
        map_axis = self.geom.get_axis_by_name(axis)

        if map_axis.node_type == 'edge':
            edges = map_axis.edges
            options = ['{:.0f} - {:.0f} {}'.format(val_min, val_max, map_axis.unit) for
                       val_min, val_max in zip(edges[:-1], edges[1:])]
        else:
            center = map_axis.center
            options = ['{:.0f} {}'.format(val, map_axis.unit) for val in center]

        @interact(
            val=SelectionSlider(options=options, description='Select {}:'.format(axis),
                                continuous_update=False, style={'description_width': 'initial'},
                                layout={'width': '36%'}),
            stretch=RadioButtons(options=['linear', 'sqrt', 'log'], value=stretch,
                                 description='Select stretch:', style={'description_width': 'initial'}),
        )
        def _plot_interactive(val, stretch):
            idx = options.index(val)
            img = self.get_image_by_idx([idx])
            with mpl.rc_context(rc=rc_params):
                fig, ax, cbar = img.plot(stretch=stretch, **kwargs)
                plt.show()
コード例 #12
0
ファイル: 62-covariance.py プロジェクト: flotpython/slides
# %%
loopback_el_datasets = OrderedDict()
loopback_el_datasets['pi_6'] = (3, 1, 5, 10, pi / 6, 100)
loopback_el_datasets['pi_4'] = (5, 1, 20, 30, pi / 4, 50)
loopback_el_datasets['pi_3'] = (10, 1, 100, 200, pi / 3, 25)
loopback_el_datasets['pi_2'] = (1.2, 1, 100, 200, pi / 2, 100)


def loopback_el_wrap(k):
    args = loopback_el_datasets[k]
    print("args = ", args)
    loopback_el(*args)


interact(loopback_el_wrap,
         k=SelectionSlider(options=list(loopback_el_datasets.keys()),
                           continuous_update=False))

# %% [markdown]
# ### Gaussian distribs


# %%
def loopback_ra(cx, cy, sdx, sdy, alpha, n):
    raw = random_points(sdx, sdy, n)
    points = translate(rotate(raw, alpha), (cx, cy))
    loopback(points, alpha, [(alpha, 3 * max(sdx, sdy))])


# %% [markdown]
# #### More and more points
コード例 #13
0
    def __init__(self):

        # размерность задачи
        items_layout = Layout (flex = '1 1 auto', width = 'auto')

        self.w_title = HTML('<h3>Параметры задачи</h3>')
        self.w_l_dim = Label('Размерность задачи:')
        self.w_dim = ToggleButtons(
            options=['2', '3'],
            value = '2',
            #description=' ',
            disabled=False,
            button_style='', # 'success', 'info', 'warning', 'danger' or ''
            tooltips=['Плоская двухмерная задача', 'Трехмерная осесимметричная задача'],
            layout=items_layout
            )

        chg.r0=1e-6
        self.w_l_r0 = Label('Радиус заряда:')
        self.w_r0 =SelectionSlider(
            options=['1e-6', '1e-5', '1e-4', '1e-3', '1e-2'],
            value='1e-6',
            #description=' ',
            disabled=False,
            continuous_update=False,
            orientation='horizontal',
            readout=True, layout=items_layout
        )   

        chg.alpha = 0
        self.w_l_alpha = Label(r"Параметр регуляризации ($\alpha$):")
        self.w_alpha =SelectionSlider(
            options=['0', '1e-6', '1e-4', '1e-2', '1e-1', '0.5', '1.0'],
            value='0',
            #description=' ',
            disabled=False,
            continuous_update=False,
            orientation='horizontal',
            readout=True, layout=items_layout
        ) 

        chg.n = 100
        self.w_l_n = Label('Число разбиений области:')
        self.w_n = SelectionSlider(
            options=['20', '50', '100', '200', '400', '500', '1000'],
            value='100',
            #description=' ',
            disabled=False,
            continuous_update=False,
            orientation='horizontal',
            readout=True, layout=items_layout
        )

        chg.minmaxxy=(0., 0, 1.,1.)
        self.w_l_minmaxxy = Label('Область для расчета и отображения потенциала (x, y):')
        self.w_minmaxx = FloatRangeSlider(value=[0.,1.],
            min=0,
            max=2.0,
            #description='xmin, xmax',
            step=0.01,    
            disabled=False,
            continuous_update=False,
            orientation='horizontal',
            readout=True,
            readout_format='.2f', layout=items_layout)
        self.w_minmaxy = FloatRangeSlider(value=[0.,1.],
            min=0,
            max=2.0,
            #description='ymin, ymax',
            step=0.02,    
            disabled=False,
            continuous_update=False,
            orientation='horizontal',
            readout=True,
            readout_format='.2f', layout=items_layout)

        chg.minmaxarea=(0.2, 0.2, 0.9,0.9)
        self.w_l_minmaxarea = Label('Область для расчета напряженности (x, y):')
        self.w_minmaxxarea = FloatRangeSlider(value=[0.2,0.9],
            min=0,
            max=1.0,
            #description='xmin, xmax',
            step=0.01,    
            disabled=False,
            continuous_update=False,
            orientation='horizontal',
            readout=True,
            readout_format='.2f', layout=items_layout)
        self.w_minmaxyarea = FloatRangeSlider(value=[0.2,0.9],
            min=0,
            max=1.2,
            #description='ymin, ymax',
            step=0.005,    
            disabled=False,
            continuous_update=False,
            orientation='horizontal',
            readout=True,
            readout_format='.3f', layout=items_layout)            
        
        self.w_l_na = Label('Разбиений для аппроксимации электродов:')
        chg.na = 50
        self.w_na = IntSlider(
            value=chg.na,
            min=20,
            max=250,
            step=2,
            #description=' ',
            disabled=False,
            continuous_update=False,
            orientation='horizontal',
            readout=True,
            readout_format='d', layout=items_layout
        )

        chg.c = None
        self.l_c = Label('')
        self.update_label('cond', chg.c, self.l_c)

        chg.err = None
        self.l_err = Label('')
        self.update_label('err', chg.err, self.l_err)

        chg.E = None
        self.l_E = Label('')
        self.update_label('E', chg.E, self.l_E)

        chg.t = None
        self.l_t = Label('')
        self.update_label('t', chg.t, self.l_t)

        self.l_msg=HTML('<b></b>')

        self.l_var = Label('Вариант:')
        self.w_dsc = Textarea(value='',
                placeholder='Введите пояснения по варианту расчета',
                description='',
                disabled=False
        )
        

        self.btn0 = Button(description ='Пересчитать поле', button_style='primary')
        self.btn01 = Button(description ='Emax/Emin', button_style='primary', disabled=True)
        self.out0 = Output()
        self.btn02 = Button(description='Сохранить', disabled=False)
        vb01= VBox([self.w_l_dim, self.w_dim,
                    self.w_l_r0, self.w_r0,
                    self.w_l_alpha, self.w_alpha,
                    self.w_l_n, self.w_n,
                    self.w_l_minmaxxy, self.w_minmaxx, self.w_minmaxy,
                    self.w_l_minmaxarea, self.w_minmaxxarea, self.w_minmaxyarea], 
                    layout=Layout(width='47%'))
        vb02 = VBox([self.w_l_na, self.w_na, self.l_var, self.w_dsc,
                     self.l_c, self.l_err, self.l_E , self.l_t, self.l_msg ], layout=Layout(width='47%'))
       
        hbox =HBox([vb01, vb02], 
                          layout=Layout(justify_content='space-between'))
        hbox2 = HBox([self.btn0, self.btn01, self.btn02])                  
        self.layout = VBox([self.w_title, hbox, hbox2, self.out0], layout=Layout(width='100%'))
        # инициализация
        self.get_data()
コード例 #14
0
ファイル: common.py プロジェクト: kingjr/mous_annot
class InteractiveTree():
    def __init__(self, sentences, nlp, data_path='./', distance=80):
        self.sentences = sentences
        self.nlp = nlp
        self.data_path = data_path

        self.select = SelectionSlider(options=sentences.index,
                                      description='sentence id')
        self.select.on_trait_change(self.load)

        self.save_button = widgets.Button(description='save')
        self.save_button.on_click(self.save)

        self.reset_button = widgets.Button(description='reset')
        self.reset_button.on_click(self.reset)

        self.load_button = widgets.Button(description='load')
        self.load_button.on_click(self.load)
        self.distance = distance

        self.load()
        self.update()

    def update(self, ):
        interact(modify_tree(self.doc_, distance=self.distance),
                 index=self.select,
                 load=self.load_button,
                 reset=self.reset_button)
        display(
            HBox([
                self.select, self.save_button, self.load_button,
                self.reset_button
            ]))

    def reset(self, *args, **kwargs):
        self.doc_ = self.nlp(self.sentences.loc[self.select.value])
        self.update()

    def load(self, *args, **kwargs):
        try:
            fname = os.path.join(self.data_path,
                                 '%i_parsed.json' % self.select.value)
            with open(fname, 'r') as f:
                json = literal_eval(f.readlines()[0])
            doc = self.nlp(json['text'])
            for w, token in zip(doc, json['tokens']):
                w.pos_ = token['pos']
                w.head = doc[token['head']]
                w.dep_ = token['dep']
            print(str(spacy_to_tree(next(doc.sents).root)))
            self.doc_ = doc
        except Exception:
            print('default parsing!')
            self.reset()
        self.update()
        return self.doc_

    def save(self, *args, **kwargs):
        fname = os.path.join(self.data_path,
                             '%i_parsed.json' % self.select.value)
        with open(fname, 'w') as f:
            f.write(str(self.doc_.to_json()))
        print('saving %s' % fname)
        print(str(spacy_to_tree(next(self.doc_.sents).root)))
コード例 #15
0
    def plot(self):
        """Interactive plot of self. Supported in two dimensions (so far)."""

        if self.M[0, 0].parent() == sage.all.SR:
            free_variables = list(sum(sum(self.M)).free_variables())
        else:
            free_variables = list()

        var_sliders = {str(var): SelectionSlider(options=SoLE.SLIDER_RANGE, continuous_update=False, value=0)
                       for var in free_variables}

        def f(**_var_sliders):
            M = self.M.subs({sage.all.var(v): _var_sliders[v] for v in _var_sliders})

            avg_y = 0
            """Average y-value of subsystems consisting of two equations."""

            """Determine x- and y- range of the plot."""
            for i, j in combinations(range(M.nrows()), 2):
                solution = sage.all.solve([self._equation(M[i]), self._equation(M[j])],
                                          *self.var_sr, solution_dict=True)
                if solution:
                    solution = solution[0]
                    if solution[self.var_sr[0]].free_variables() or solution[self.var_sr[1]].free_variables():
                        continue

                    avg_y += solution[self.var_sr[1]]

                    if self.x_min is None or solution[self.var_sr[0]] - 1 < self.x_min:
                        self.x_min = solution[self.var_sr[0]] - 1

                    if self.x_max is None or solution[self.var_sr[0]] + 1 > self.x_max:
                        self.x_max = solution[self.var_sr[0]] + 1

            if self.x_min is None:
                self.x_min = -10.0

            if self.x_max is None:
                self.x_max = 10.0

            avg_y = avg_y / M.nrows()
            self.y_max = avg_y + SoLE.MAX_ASPECT_RATIO * (self.x_max - self.x_min) / 2
            self.y_min = avg_y - SoLE.MAX_ASPECT_RATIO * (self.x_max - self.x_min) / 2

            x = np.arange(self.x_min, self.x_max, sage.all.QQ((self.x_max - self.x_min)/100))

            fig, ax = plt.subplots()

            for i in range(M.nrows()):
                if M[i][-2] == 0.0:
                    # vertical line
                    if M[i][0] != 0.0:
                        xv = M[i][-1] / M[i][0]
                        ax.plot([xv, xv], [self.y_min, self.y_max], label=self._format_equation(M[i]))
                else:
                    row_f = SoLE._row_to_function(M[i])
                    y = [row_f(_x) for _x in x]

                    x_clip, y_clip = list(), list()

                    for _x, _y in zip(x, y):
                        if self.y_min <= _y <= self.y_max:
                            x_clip.append(_x)
                            y_clip.append(_y)

                    ax.plot(x_clip, y_clip, label=self._format_equation(M[i]))

            ax.set(xlabel=self.var[0], ylabel=self.var[1])
            ax.grid()

            plt.legend()
            plt.show()

        w = sage_interactive(f, **var_sliders)
        # output = w.children[-1]
        # output.layout.height = '600px'

        default_dpi = plt.rcParamsDefault['figure.dpi']
        plt.rcParams['figure.dpi'] = default_dpi * 1.5

        display(w)
コード例 #16
0
def z1_interact(box_z, indz, nb_d, z_d, sigr_d, sigz_d, nb_w, sigr_w, z1_w,
                z2_w, use_fixed_length, use_theory):

    if nb_w > 0 and not (z1_w > np.pi / 2.0 and z1_w < np.pi):
        sys.exit('Error: trying to load beam in the wrong region')

    if nb_w < 0 and not (z1_w > 1.5 * np.pi and z1_w < 2.0 * np.pi):
        sys.exit('Error: trying to load beam in the wrong region')

    R0th = float(sigr_d**2 / 2.0 * np.exp(sigr_d**2 / 2.0) *
                 mp.gammainc(0, sigr_d**2 / 2.0))
    R0thw = float(sigr_w**2 / 2.0 * np.exp(sigr_w**2 / 2.0) *
                  mp.gammainc(0, sigr_w**2 / 2.0))

    olength = z2_w - z1_w
    nb_w0 = nb_w

    ximin = box_z[0]
    ximax = box_z[1]

    shape_alpha = 0.9

    def plot_wakes(z1_w):

        nb_wlocal = 0.0
        z2_wlocal = 0.0
        if use_theory == True:
            z2_wlocal = z1_w - np.tan(z1_w)
            nb_wlocal = nb_d * np.sqrt(2.0 * np.pi) * sigz_d * np.exp(
                -sigz_d**2 / 2.) * np.sin(z1_w) * R0th / R0thw
        else:
            nb_wlocal = nb_w
            if use_fixed_length == True:
                z2_wlocal = z1_w + olength
            else:
                z2_wlocal = z2_w

        figure_title = '$E_z$'
        xlabel_bottom = r'$\xi = ct-z\;[c/\omega_p]$'
        ylabel_left = '$eE_z/mc\omega_p$'
        ylabel_right = '$n_b/n_p$'
        datamin = -1.0
        datamax = 1.0
        xi = np.linspace(ximin, ximax, 2**indz)

        fig, ax1 = plt.subplots(figsize=(8, 5))
        #plt.axis([ xi.min(), xi.max(),datamin, datamax])
        plt.title(figure_title)
        ax1.set_xlabel(xlabel_bottom)
        ax1.set_ylabel(ylabel_left, color='k')
        ax1.tick_params('y', colors='k')
        ax1.set_xlim([xi.min(), xi.max()])

        ax2 = ax1.twinx()
        ax2.set_ylabel(ylabel_right, color='b')
        ax2.tick_params('y', colors='b')
        nbmax = np.max(np.array([nb_d, nb_wlocal]))
        ax2.set_ylim([-2.0 * nbmax, 2.0 * nbmax])

        temp = xi[xi < z_d + 3.0 * sigr_d]
        xid = temp[temp > z_d - 3.0 * sigr_d]
        d_profile = nb_d * np.exp(-(xid - z_d)**2 / (2.0 * sigz_d**2))
        ax2.fill_between(xid, 0, d_profile, alpha=shape_alpha)

        temp = xi[xi > z1_w + z_d]
        xiw = temp[temp < z2_wlocal + z_d]
        w_profile = nb_wlocal * (z2_wlocal + z_d - xiw) / (z2_wlocal - z1_w)
        ax2.fill_between(xiw, 0, w_profile, alpha=shape_alpha)

        def Zpth(kpxi):
            return nb_d * np.sqrt(2. * np.pi) * sigz_d * np.exp(
                -sigz_d**2 / 2.) * np.cos(kpxi)

        def Ezth(kpxi):
            return Zpth(kpxi) * R0th

        def Zpthw(kpxi):
            if kpxi < z2_wlocal:
                return nb_wlocal / (z2_wlocal - z1_w) * (
                    (z2_wlocal - z1_w) * np.sin(kpxi - z1_w) +
                    np.cos(kpxi - z1_w) - 1.0)
            else:
                return nb_wlocal / (z2_wlocal - z1_w) * (
                    (z2_wlocal - z1_w) * np.sin(kpxi - z1_w) +
                    np.cos(kpxi - z1_w) - np.cos(kpxi - z2_wlocal))

        def Ezthw(kpxi):
            return [Zpthw(i) * R0thw for i in kpxi]

        ezmaxd = np.max(np.abs(Ezth(xi[xi > z_d] - z_d)))
        ezmaxw = np.max(np.abs(Ezthw(xi[xi > z1_w + z_d] - z_d)))
        ezmaxt = np.max(
            np.abs(
                Ezthw(xi[xi > z1_w + z_d] - z_d) +
                Ezth(xi[xi > z1_w + z_d] - z_d)))
        ezmax = np.max(np.array([float(ezmaxd), float(ezmaxw), float(ezmaxt)]))
        ax1.set_ylim([-1.1 * ezmax, 1.1 * ezmax])

        Eztot = np.copy(Ezth(xi - z_d))
        Ezw = np.copy(Ezthw(xi - z_d))
        Eztot[xi > z1_w + z_d] = np.add(Eztot[xi > z1_w + z_d],
                                        Ezw[xi > z1_w + z_d])
        ax1.plot(xi[xi > z_d],
                 Ezth(xi[xi > z_d] - z_d),
                 'C0',
                 label='wake from driver')
        ax1.plot(xi[xi > z1_w + z_d],
                 Ezthw(xi[xi > z1_w + z_d] - z_d),
                 'k',
                 linewidth=1.5)
        ax1.plot(xi[xi > z1_w + z_d],
                 Ezthw(xi[xi > z1_w + z_d] - z_d),
                 'C1',
                 linewidth=1.4,
                 label='wake from witness beam')
        ax1.plot(xi[xi > z_d], Eztot[xi > z_d], 'r--', label='total wake')
        #ax1.plot(xi[xi>z1_w+z_d],Ezthw(xi[xi>z1_w+z_d]-z_d)+Ezth(xi[xi>z1_w+z_d]-z_d),'r',label='total wake')

        #ax1.plot(xi,Ezth(xi-z_d),label='wake from driver')
        #ax1.plot(xi,Ezthw(xi-z_d),label='wake from witness beam')
        #ax1.plot(xi,Ezthw(xi-z_d)+Ezth(xi-z_d),'r--',label='total wake')
        ax1.legend(loc=3)
        ax1.set_zorder(ax2.get_zorder() + 1)
        ax1.patch.set_visible(False)

        fig.tight_layout()

        if use_theory == True:
            print('Tail location = ', '%.3f' % z2_wlocal)
            print('Beam density = ', '%.3e' % nb_wlocal)

    def plot_wakes_nb(nb_w):

        if nb_w0 < 0:
            nb_w = -nb_w

        #if use_theory==True:
        #    z1_w=np.pi+np.arcsin(R0thw/R0th*nb_w/(nb_d*np.sqrt(2.0*np.pi)*sigz_d*np.exp(-sigz_d**2/2.)))
        #    z2_w=z1_w+np.tan(z1_w)

        z1_wlocal = 0.0
        z2_wlocal = 0.0
        if use_theory == True:
            z1_wlocal = np.pi - np.arcsin(R0thw / R0th * nb_w /
                                          (nb_d * np.sqrt(2.0 * np.pi) *
                                           sigz_d * np.exp(-sigz_d**2 / 2.)))
            z2_wlocal = z1_wlocal - np.tan(z1_wlocal)
            if nb_w0 < 0:
                z1_wlocal = 2.0 * np.pi - np.arcsin(
                    -R0thw / R0th * nb_w / (nb_d * np.sqrt(2.0 * np.pi) *
                                            sigz_d * np.exp(-sigz_d**2 / 2.)))
                z2_wlocal = z1_wlocal - np.tan(z1_wlocal)
        else:
            z1_wlocal = z1_w
            z2_wlocal = z2_w

        figure_title = '$E_z$'
        xlabel_bottom = r'$\xi = ct-z\;[c/\omega_p]$'
        ylabel_left = '$eE_z/mc\omega_p$'
        ylabel_right = '$n_b/n_p$'
        datamin = -1.0
        datamax = 1.0
        xi = np.linspace(ximin, ximax, 2**indz)

        fig, ax1 = plt.subplots(figsize=(8, 5))
        #plt.axis([ xi.min(), xi.max(),datamin, datamax])
        plt.title(figure_title)
        ax1.set_xlabel(xlabel_bottom)
        ax1.set_ylabel(ylabel_left, color='k')
        ax1.tick_params('y', colors='k')
        ax1.set_xlim([xi.min(), xi.max()])

        def Zpth(kpxi):
            return nb_d * np.sqrt(2. * np.pi) * sigz_d * np.exp(
                -sigz_d**2 / 2.) * np.cos(kpxi)

        def Ezth(kpxi):
            return Zpth(kpxi) * R0th

        def Zpthw(kpxi):
            if kpxi < z2_wlocal:
                return nb_w / (z2_wlocal - z1_wlocal) * (
                    (z2_wlocal - z1_wlocal) * np.sin(kpxi - z1_wlocal) +
                    np.cos(kpxi - z1_wlocal) - 1.0)
            else:
                return nb_w / (z2_wlocal - z1_wlocal) * (
                    (z2_wlocal - z1_wlocal) * np.sin(kpxi - z1_wlocal) +
                    np.cos(kpxi - z1_wlocal) - np.cos(kpxi - z2_wlocal))

        def Ezthw(kpxi):
            return [Zpthw(i) * R0thw for i in kpxi]

        ezmaxd = np.max(np.abs(Ezth(xi[xi > z_d] - z_d)))
        ezmaxw = np.max(np.abs(Ezthw(xi[xi > z1_wlocal + z_d] - z_d)))
        ezmaxt = np.max(
            np.abs(
                Ezthw(xi[xi > z1_wlocal + z_d] - z_d) +
                Ezth(xi[xi > z1_wlocal + z_d] - z_d)))
        ezmax = np.max(np.array([float(ezmaxd), float(ezmaxw), float(ezmaxt)]))
        ax1.set_ylim([-1.1 * ezmax, 1.1 * ezmax])

        Eztot = np.copy(Ezth(xi - z_d))
        Ezw = np.copy(Ezthw(xi - z_d))
        Eztot[xi > z1_wlocal + z_d] = np.add(Eztot[xi > z1_wlocal + z_d],
                                             Ezw[xi > z1_wlocal + z_d])
        ax1.plot(xi[xi > z_d],
                 Ezth(xi[xi > z_d] - z_d),
                 'C0',
                 label='wake from driver')
        ax1.plot(xi[xi > z1_wlocal + z_d],
                 Ezthw(xi[xi > z1_wlocal + z_d] - z_d),
                 'k',
                 linewidth=1.5)
        ax1.plot(xi[xi > z1_wlocal + z_d],
                 Ezthw(xi[xi > z1_wlocal + z_d] - z_d),
                 'C1',
                 linewidth=1.4,
                 label='wake from witness beam')
        ax1.plot(xi[xi > z_d], Eztot[xi > z_d], 'r--', label='total wake')
        #ax1.plot(xi[xi>z1_w+z_d],Ezthw(xi[xi>z1_w+z_d]-z_d)+Ezth(xi[xi>z1_w+z_d]-z_d),'r',label='total wake')

        #ax1.plot(xi,Ezth(xi-z_d),label='wake from driver')
        #ax1.plot(xi,Ezthw(xi-z_d),label='wake from witness beam')
        #ax1.plot(xi,Ezthw(xi-z_d)+Ezth(xi-z_d),'r--',label='total wake')
        ax1.legend(loc=3)

        ax2 = ax1.twinx()
        ax2.set_ylabel(ylabel_right, color='b')
        ax2.tick_params('y', colors='b')
        nbmax = np.max(np.array([nb_d, nb_w]))
        ax2.set_ylim([-2.0 * nbmax, 2.0 * nbmax])

        temp = xi[xi < z_d + 3.0 * sigr_d]
        xid = temp[temp > z_d - 3.0 * sigr_d]
        d_profile = nb_d * np.exp(-(xid - z_d)**2 / (2.0 * sigz_d**2))
        ax2.fill_between(xid, 0, d_profile, alpha=shape_alpha)

        temp = xi[xi > z1_wlocal + z_d]
        xiw = temp[temp < z2_wlocal + z_d]
        w_profile = nb_w * (z2_wlocal + z_d - xiw) / (z2_wlocal - z1_wlocal)
        ax2.fill_between(xiw, 0, w_profile, alpha=shape_alpha)

        ax1.set_zorder(ax2.get_zorder() + 1)
        ax1.patch.set_visible(False)

        fig.tight_layout()

        if use_theory == True:
            print('Head location = ', '%.3f' % z1_wlocal)
            print('Tail location = ', '%.3f' % z2_wlocal)

    z1_wmin = 1.6
    z1_wmax = 3.1
    if nb_w < 0:
        z1_wmin += np.pi
        z1_wmax += np.pi
    i1 = interact(plot_wakes,
                  z1_w=FloatSlider(min=z1_wmin,
                                   max=z1_wmax,
                                   step=0.05,
                                   value=z1_w,
                                   continuous_update=False))

    nb_wmax = nb_d * np.sqrt(2.0 * np.pi) * sigz_d * np.exp(
        -sigz_d**2 / 2.) * R0th / R0thw * 0.99

    #if nb_w0>0:
    #    i2=interact(plot_wakes_nb,nb_w=FloatSlider(min=nb_wmax/10.0,max=nb_wmax,step=nb_wmax/10.0,value=nb_w0,continuous_update=False))
    #else:
    #    i2=interact(plot_wakes_nb,nb_w=FloatSlider(min=nb_wmax/10.0,max=nb_wmax,step=nb_wmax/10.0,value=-nb_w0,continuous_update=False))

    values = np.arange(nb_wmax / 10.0, 1.01 * nb_wmax, nb_wmax / 10.0)
    i2 = interact(plot_wakes_nb,
                  nb_w=SelectionSlider(options=[("%.3e" % i, i)
                                                for i in values],
                                       continuous_update=False))
コード例 #17
0
ファイル: base.py プロジェクト: faruk0509/gammapy
    def plot_interactive(self, rc_params=None, **kwargs):
        """
        Plot map with interactive widgets to explore the non spatial axes.

        Parameters
        ----------
        rc_params : dict
            Passed to ``matplotlib.rc_context(rc=rc_params)`` to style the plot.
        **kwargs : dict
            Keyword arguments passed to `WcsNDMap.plot`.

        Examples
        --------
        You can try this out e.g. using a Fermi-LAT diffuse model cube with an energy axis::

            from gammapy.maps import Map

            m = Map.read("$GAMMAPY_DATA/fermi_3fhl/gll_iem_v06_cutout.fits")
            m.plot_interactive(add_cbar=True, stretch="sqrt")

        If you would like to adjust the figure size you can use the ``rc_params`` argument::

            rc_params = {'figure.figsize': (12, 6), 'font.size': 12}
            m.plot_interactive(rc_params=rc_params)
        """
        import matplotlib as mpl
        import matplotlib.pyplot as plt
        from ipywidgets.widgets.interaction import interact, fixed
        from ipywidgets import SelectionSlider, RadioButtons

        if self.geom.is_image:
            raise TypeError("Use .plot() for 2D Maps")

        kwargs.setdefault("interpolation", "nearest")
        kwargs.setdefault("origin", "lower")
        kwargs.setdefault("cmap", "afmhot")

        rc_params = rc_params or {}
        stretch = kwargs.pop("stretch", "sqrt")

        interact_kwargs = {}

        for axis in self.geom.axes:
            if axis.node_type == "edges":
                options = [
                    "{:.2e} - {:.2e} {}".format(val_min, val_max, axis.unit)
                    for val_min, val_max in zip(axis.edges[:-1], axis.edges[1:])
                ]
            else:
                options = ["{:.2e} {}".format(val, axis.unit) for val in axis.center]

            interact_kwargs[axis.name] = SelectionSlider(
                options=options,
                description="Select {}:".format(axis.name),
                continuous_update=False,
                style={"description_width": "initial"},
                layout={"width": "50%"},
            )
            interact_kwargs[axis.name + "_options"] = fixed(options)

        interact_kwargs["stretch"] = RadioButtons(
            options=["linear", "sqrt", "log"],
            value=stretch,
            description="Select stretch:",
            style={"description_width": "initial"},
        )

        @interact(**interact_kwargs)
        def _plot_interactive(**ikwargs):
            idx = [
                ikwargs[ax.name + "_options"].index(ikwargs[ax.name])
                for ax in self.geom.axes
            ]
            img = self.get_image_by_idx(idx)
            stretch = ikwargs["stretch"]
            with mpl.rc_context(rc=rc_params):
                fig, ax, cbar = img.plot(stretch=stretch, **kwargs)
                plt.show()
コード例 #18
0
def show():
    df = SelectionSlider(options=[1, 3, 10, 30, 100],
                         description='自由度',
                         continuous_update=False)
    interact(plot, df=df)