Exemplo n.º 1
0
def connected_kernel(**kwargs):
    """Connect to another kernel running in
       the current process

    This only works on IPython v1.0 and above

    Parameters
    ----------
    kwargs : Extra variables to put into the namespace
    """
    kernel_info = {}

    shell = get_ipython()
    if shell is None:
        raise RuntimeError("There is no IPython kernel in this process")

    try:
        client = QtKernelClient(connection_file=get_connection_file())
        client.load_connection_file()
        client.start_channels()
        kernel_info['client'] = client
        kernel_info['shell'] = shell
    except Exception:
        print('Detected running from an ipython interpreter.\n'
              'The GUI console will be disabled.')
        kernel_info['client'] = None
        kernel_info['shell'] = None

    return kernel_info
Exemplo n.º 2
0
def connected_kernel(**kwargs):
    """Connect to another kernel running in
       the current process

    This only works on IPython v1.0 and above

    Parameters
    ----------
    kwargs : Extra variables to put into the namespace
    """
    kernel_info = {}

    shell = get_ipython()
    if shell is None:
        raise RuntimeError("There is no IPython kernel in this process")

    try:
        client = QtKernelClient(connection_file=get_connection_file())
        client.load_connection_file()
        client.start_channels()
        kernel_info['client'] = client
        kernel_info['shell'] = shell
    except Exception:
        print ('Detected running from an ipython interpreter.\n'
               'The GUI console will be disabled.')
        kernel_info['client'] = None
        kernel_info['shell'] = None

    return kernel_info
Exemplo n.º 3
0
def test_get_connection_file():
    cfg = Config()
    with TemporaryWorkingDirectory() as d:
        cfg.ProfileDir.location = d
        cf = 'kernel.json'
        app = DummyConsoleApp(config=cfg, connection_file=cf)
        app.initialize(argv=[])
        
        profile_cf = os.path.join(app.profile_dir.location, 'security', cf)
        nt.assert_equal(profile_cf, app.connection_file)
        with open(profile_cf, 'w') as f:
            f.write("{}")
        nt.assert_true(os.path.exists(profile_cf))
        nt.assert_equal(connect.get_connection_file(app), profile_cf)
        
        app.connection_file = cf
        nt.assert_equal(connect.get_connection_file(app), profile_cf)
Exemplo n.º 4
0
def test_get_connection_file():
    cfg = Config()
    with TemporaryWorkingDirectory() as d:
        cfg.ProfileDir.location = d
        cf = 'kernel.json'
        app = DummyConsoleApp(config=cfg, connection_file=cf)
        app.initialize(argv=[])
        
        profile_cf = os.path.join(app.profile_dir.location, 'security', cf)
        nt.assert_equal(profile_cf, app.connection_file)
        with open(profile_cf, 'w') as f:
            f.write("{}")
        nt.assert_true(os.path.exists(profile_cf))
        nt.assert_equal(connect.get_connection_file(app), profile_cf)
        
        app.connection_file = cf
        nt.assert_equal(connect.get_connection_file(app), profile_cf)
Exemplo n.º 5
0
def connected_console(console_class=RichIPythonWidget, **kwargs):
    """Create a console widget, connected to another kernel running in
       the current process

    This only works on IPython v1.0 and above

    Parameters
    ----------
    console_class : The class of the console widget to create
    kwargs : Extra variables to put into the namespace
    """
    shell = get_ipython()
    if shell is None:
        raise RuntimeError("There is no IPython kernel in this process")

    client = QtKernelClient(connection_file=get_connection_file())
    client.load_connection_file()
    client.start_channels()

    control = console_class()
    control.kernel_client = client
    control.shell = shell
    control.shell.user_ns.update(**kwargs)
    return control
Exemplo n.º 6
0
    def plot_plotly(self,
                    plotly_filename=None,
                    mpl_type=False,
                    xlim=None,
                    ylim=None,
                    title=None,
                    figsize=None,
                    xlabel=None,
                    ylabel=None,
                    fontsize=None,
                    show_legend=True,
                    grid=False):
        """
        Plot data using plotly library in IPython

        :param plotly_filename: name for resulting plot file on server (use unique name, else the same plot will be showen)
        :type plotly_filename: None or str
        :param bool mpl_type: use or not plotly converter from matplotlib (experimental parameter)
        :param xlim: x-axis range
        :param ylim: y-axis range
        :type xlim: None or tuple(x_min, x_max)
        :type ylim: None or tuple(y_min, y_max)
        :param title: title
        :type title: None or str
        :param figsize: figure size
        :type figsize: None or tuple(weight, height)
        :param xlabel: x-axis name
        :type xlabel: None or str
        :param ylabel: y-axis name
        :type ylabel: None or str
        :param fontsize: font size
        :type fontsize: None or int
        :param bool show_legend: show or not labels for plots
        :param bool grid: show grid or not
        """
        import plotly.plotly as py
        from plotly import graph_objs
        from IPython.kernel import connect

        plotly_filename = self.plotly_filename if plotly_filename is None else plotly_filename
        connection_file_path = connect.get_connection_file()
        connection_file = os.path.basename(connection_file_path)
        if '-' in connection_file:
            kernel_id = connection_file.split('-', 1)[1].split('.')[0]
        else:
            kernel_id = connection_file.split('.')[0]
        PLOTLY_API_USER, PLOTLY_API_KEY, PLOTLY_USER = self._plotly_config()
        save_name = '{user}_{id}:{name}'.format(user=PLOTLY_USER,
                                                id=kernel_id,
                                                name=plotly_filename)
        py.sign_in(PLOTLY_API_USER, PLOTLY_API_KEY)

        if mpl_type:
            self.plot(new_plot=True,
                      xlim=xlim,
                      ylim=ylim,
                      title=title,
                      figsize=figsize,
                      xlabel=xlabel,
                      ylabel=ylabel,
                      fontsize=fontsize,
                      grid=grid)
            mpl_fig = plt.gcf()
            update = dict(layout=dict(showlegend=show_legend),
                          data=[dict(name=leg) for leg in mpl_fig.legends])

            return py.iplot_mpl(mpl_fig,
                                width=self.figsize[0] * 60,
                                update=update,
                                height=self.figsize[1] * 60,
                                filename=save_name,
                                fileopt='overwrite')

        xlabel = self.xlabel if xlabel is None else xlabel
        ylabel = self.ylabel if ylabel is None else ylabel
        title = self.title if title is None else title
        figsize = self.figsize if figsize is None else figsize
        fontsize = self.fontsize if fontsize is None else fontsize

        layout = graph_objs.Layout(yaxis={
            'title': ylabel,
            'ticks': ''
        },
                                   xaxis={
                                       'title': xlabel,
                                       'ticks': ''
                                   },
                                   showlegend=show_legend,
                                   title=title,
                                   font=graph_objs.Font(
                                       family='Courier New, monospace',
                                       size=fontsize),
                                   width=figsize[0] * self.PLOTLY_RESIZE,
                                   height=figsize[1] * self.PLOTLY_RESIZE)

        fig = self._plot_plotly(layout)

        return py.iplot(fig,
                        width=figsize[0] * self.PLOTLY_RESIZE,
                        height=figsize[1] * self.PLOTLY_RESIZE,
                        filename=save_name)
Exemplo n.º 7
0
    def plot_plotly(self, plotly_filename=None, mpl_type=False, xlim=None, ylim=None, title=None, figsize=None,
                    xlabel=None, ylabel=None, fontsize=None, show_legend=True, grid=False):
        """
        Plot data using plotly library in IPython

        :param plotly_filename: name for resulting plot file on server (use unique name, else the same plot will be showen)
        :type plotly_filename: None or str
        :param bool mpl_type: use or not plotly converter from matplotlib (experimental parameter)
        :param xlim: x-axis range
        :param ylim: y-axis range
        :type xlim: None or tuple(x_min, x_max)
        :type ylim: None or tuple(y_min, y_max)
        :param title: title
        :type title: None or str
        :param figsize: figure size
        :type figsize: None or tuple(weight, height)
        :param xlabel: x-axis name
        :type xlabel: None or str
        :param ylabel: y-axis name
        :type ylabel: None or str
        :param fontsize: font size
        :type fontsize: None or int
        :param bool show_legend: show or not labels for plots
        :param bool grid: show grid or not
        """
        import plotly.plotly as py
        from plotly import graph_objs
        from IPython.kernel import connect

        plotly_filename = self.plotly_filename if plotly_filename is None else plotly_filename
        connection_file_path = connect.get_connection_file()
        connection_file = os.path.basename(connection_file_path)
        if '-' in connection_file:
            kernel_id = connection_file.split('-', 1)[1].split('.')[0]
        else:
            kernel_id = connection_file.split('.')[0]
        PLOTLY_API_USER, PLOTLY_API_KEY, PLOTLY_USER = self._plotly_config()
        save_name = '{user}_{id}:{name}'.format(user=PLOTLY_USER, id=kernel_id, name=plotly_filename)
        py.sign_in(PLOTLY_API_USER, PLOTLY_API_KEY)

        if mpl_type:
            self.plot(new_plot=True, xlim=xlim, ylim=ylim, title=title, figsize=figsize, xlabel=xlabel, ylabel=ylabel,
                      fontsize=fontsize, grid=grid)
            mpl_fig = plt.gcf()
            update = dict(
                layout=dict(
                    showlegend=show_legend
                ),
                data=[dict(name=leg) for leg in mpl_fig.legends]
            )

            return py.iplot_mpl(mpl_fig, width=self.figsize[0] * 60,
                                update=update,
                                height=self.figsize[1] * 60,
                                filename=save_name,
                                fileopt='overwrite')

        xlabel = self.xlabel if xlabel is None else xlabel
        ylabel = self.ylabel if ylabel is None else ylabel
        title = self.title if title is None else title
        figsize = self.figsize if figsize is None else figsize
        fontsize = self.fontsize if fontsize is None else fontsize

        layout = graph_objs.Layout(yaxis={'title': ylabel, 'ticks': ''}, xaxis={'title': xlabel, 'ticks': ''},
                                   showlegend=show_legend, title=title,
                                   font=graph_objs.Font(family='Courier New, monospace', size=fontsize),
                                   width=figsize[0] * self.PLOTLY_RESIZE,
                                   height=figsize[1] * self.PLOTLY_RESIZE
        )

        fig = self._plot_plotly(layout)

        return py.iplot(fig, width=figsize[0] * self.PLOTLY_RESIZE, height=figsize[1] * self.PLOTLY_RESIZE,
                        filename=save_name)