Esempio n. 1
0
def turn_code_on_off_html():
    string  = '''<script type="text/javascript">
code_hide=true;
function code_toggle() {
 if (code_hide){
 $('div.output_prompt').css("color","#FFFFFF");
 $('div.input').hide();
 } else {
 $('div.output_prompt').css("color","#8b0000");
 $('div.input').show();
 }
 code_hide = !code_hide
}
$( document ).ready(code_toggle)
</script>
<script>
// define a handler
function doc_keyUp(e) {
    // this would test for the 'h' key, the 'ctrl' key and the 'shift' key at the same time
    if (e.altKey && e.ctrlKey && e.keyCode == 72) {
        code_toggle();
    }
}
// register the handler
// document.removeEventListener('keyup', doc_keyUp, false);
document.addEventListener('keyup', doc_keyUp, false);
</script>
The raw code for this IPython notebook is by default hidden for easier reading.
<form action="javascript:code_toggle()"><input type="submit"
value="Click here or press CRTL+ALT+H to toggle the code on/off."></form>'''
    return _HTML(string)
Esempio n. 2
0
def publish_to_datasette(df, name='this', table_name='table', db_root=datasette_path):
    db_path = tools.pandas_to_sqlite(df, name, table_name, db_root)
    _display(_HTML(f'''<div class="alert alert-info">DataFrame sent to Jupyter Datasette folder as:
    <ul>
        <li><b>db</b>: {name}</li>
        <li><b>table</b>: {table_name}</li>
    </ul>
        <i>Reload Datasette to pick up new files</i></div>'''))
Esempio n. 3
0
def start_datasette(db_path, jupyter, **kwargs):
    '''
        Pass in cmdline flags as kwargs: port=8080, reload=True
    '''
    port = kwargs.get('port',kwargs.get('p',None))
    host = _socket.gethostbyname(_socket.gethostname())

    # keep the kwargs alive
    flags = [f'--{key}' if value is True else f'--{key} {value}' for key,value in kwargs.items()]
    flags = ' '.join(flags)
    cmd = f'datasette {db_path} {flags}'
    cmd = re.sub(' +', ' ', cmd)

    if jupyter:
        _display(_HTML(f'''<div class="alert alert-info><b>Datasette Launching at <a target="_blank" href="http://{host}:{port}">http://{host}:{port}</a></b><br/>
            <pre>{cmd}</pre></div>'''))
    try:
        process = _subprocess.Popen(cmd.split(' '), stderr=_subprocess.PIPE, stdout=_subprocess.PIPE)
        return process
    except: #catch KeyboardInterrupt and whatever other calamity might befall our process
        process.terminate()
Esempio n. 4
0
def _create_animation(od, time, plot_func, func_kwargs, display, **kwargs):
    """
    Create animation using oceanspy plot functions.

    Parameters
    ----------
    od: OceanDataset
        oceandataset used to plot.
    time: DataArray
        DataArray corresponding to time.
    plot_func: function
        Alias referring to the plot function.
    func_kwargs:
        Keyword arguments for plot_func.
    display: bool
        If True, display the animation.
    **kwargs:
        Keyword arguments for py:class:`matplotlib.animation.FuncAnimation`

    Returns
    -------
    anim: matplotlib.animation.FuncAnimation
        Animation object

    References
    ----------
    https://matplotlib.org/api/_as_gen/matplotlib.animation.FuncAnimation.html
    """

    # Check parameters
    _check_instance(
        {
            "od": od,
            "time": time,
            "func_kwargs": func_kwargs,
            "display": display
        },
        {
            "od": "oceanspy.OceanDataset",
            "time": "xarray.DataArray",
            "func_kwargs": ["type(None)", "dict"],
            "display": ["bool"],
        },
    )

    # Handle kwargs
    if func_kwargs is None:
        func_kwargs = {}
    func_kwargs = dict(func_kwargs)

    # Animate function
    def animate(i):
        _plt.clf()
        func_kwargs["cutout_kwargs"] = {
            "timeRange": time.isel({
                time.dims[0]: i
            }).values,
            "dropAxes": "time",
        }
        with _io.capture_output() as captured:
            plot_func(od, **func_kwargs)
        if "pbar" in locals():
            pbar.update(1)

    # Create animation object
    anim = _FuncAnimation(**{
        "fig": _plt.gcf(),
        "func": animate,
        "frames": len(time),
        **kwargs
    })

    # Display
    if display is True:
        pbar = _tqdm(total=len(time))
        _display(_HTML(anim.to_html5_video()))
        pbar.close()
        del pbar

    return anim
Esempio n. 5
0
    def write(self, filename=None, f="gb"):
        """Writes the Dseqrecord to a file using the format f, which must
        be a format supported by Biopython SeqIO for writing [#]_. Default
        is "gb" which is short for Genbank. Note that Biopython SeqIO reads
        more formats than it writes.

        Filename is the path to the file where the sequece is to be
        written. The filename is optional, if it is not given, the
        description property (string) is used together with the format.

        If obj is the Dseqrecord object, the default file name will be:

        ``<obj.locus>.<f>``

        Where <f> is "gb" by default. If the filename already exists and
        AND the sequence it contains is different, a new file name will be
        used so that the old file is not lost:

        ``<obj.locus>_NEW.<f>``

        References
        ----------
        .. [#] http://biopython.org/wiki/SeqIO

        """
        msg = ""
        if not filename:
            filename = "{name}.{type}".format(name=self.locus, type=f)
            # generate a name if no name was given
        if not isinstance(filename, str):  # is filename a string???
            raise ValueError("filename has to be a string, got",
                             type(filename))
        name, ext = _os.path.splitext(filename)
        msg = "<font face=monospace><a href='{filename}' target='_blank'>{filename}</a></font><br>".format(
            filename=filename)
        if not _os.path.isfile(filename):
            with open(filename, "w") as fp:
                fp.write(self.format(f))
        else:
            from pydna.readers import read

            old_file = read(filename)
            if self.seq != old_file.seq:
                # If new sequence is different, the old file is renamed with "_OLD" suffix:
                # TODO: add this timestamp so that all old versions are stored
                # int(time.time() * 1000000)  = 1512035297658778
                old_filename = "{}_OLD{}".format(name, ext)
                _os.rename(filename, old_filename)
                msg = (
                    "<font color='DarkOrange ' face=monospace>"
                    "Sequence changed.<br>"
                    "</font>"
                    "<font color='red' face=monospace>"
                    "new: <a href='{filename}' target='_blank'>{filename}</a> &nbsp&nbsp&nbsp size: {nlen}bp topology: {ntop} SEGUID: {ns}<br>"
                    "</font>"
                    "<font color='green' face=monospace>"
                    "old: <a href='{oldfname}' target='_blank'>{oldfname}</a> size: {olen}bp topology: {otop} SEGUID: {os}<br>"
                    "</font>").format(
                        filename=filename,
                        oldfname=old_filename,
                        nlen=len(self),
                        olen=len(old_file),
                        ns=self.seguid(),
                        os=old_file.seguid(),
                        ntop={
                            True: "-",
                            False: "o"
                        }[self.linear],
                        otop={
                            True: "-",
                            False: "o"
                        }[old_file.linear],
                    )
                with open(filename, "w") as fp:
                    fp.write(self.format(f))
            elif "SEGUID" in old_file.description:
                pattern = r"(lSEGUID|cSEGUID|SEGUID)_(\S{27})(_[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}\.[0-9]{6}){0,1}"
                oldstamp = _re.search(pattern, old_file.description)
                newstamp = _re.search(pattern, self.description)
                newdescription = self.description
                # print(oldstamp, newstamp)
                if oldstamp and newstamp:
                    if oldstamp.group(0)[:35] == newstamp.group(0)[:35]:
                        newdescription = newdescription.replace(
                            newstamp.group(0), oldstamp.group(0))
                elif oldstamp:
                    newdescription += " " + oldstamp.group(0)
                newobj = _copy.copy(self)
                newobj.description = newdescription

                with open(filename, "w") as fp:
                    fp.write(newobj.format(f))
            else:
                with open(filename, "w") as fp:
                    fp.write(self.format(f))
        return _display_html(_HTML(msg))
Esempio n. 6
0
def _create_animation(od, time, plot_func, func_kwargs, display,
                      **kwargs):
    """
    Create animation using oceanspy plot functions.

    Parameters
    ----------
    od: OceanDataset
        oceandataset used to plot.
    time: DataArray
        DataArray corresponding to time.
    plot_func: function
        Alias referring to the plot function.
    func_kwargs:
        Keyword arguments for plot_func.
    display: bool
        If True, display the animation.
    **kwargs:
        Keyword arguments for py:class:`matplotlib.animation.FuncAnimation`

    Returns
    -------
    anim: matplotlib.animation.FuncAnimation
        Animation object

    References
    ----------
    https://matplotlib.org/api/_as_gen/matplotlib.animation.FuncAnimation.html
    """

    # Check parameters
    _check_instance({'od': od,
                     'time': time,
                     'func_kwargs': func_kwargs,
                     'display': display},
                    {'od': 'oceanspy.OceanDataset',
                     'time': 'xarray.DataArray',
                     'func_kwargs': ['type(None)', 'dict'],
                     'display': ['bool']})

    # Handle kwargs
    if func_kwargs is None:
        func_kwargs = {}
    func_kwargs = dict(func_kwargs)

    # Animate function
    def animate(i):
        _plt.clf()
        func_kwargs['cutout_kwargs'] = {'timeRange':
                                        time.isel({time.dims[0]: i}).values,
                                        'dropAxes': 'time'}
        with _io.capture_output() as captured:
            plot_func(od, **func_kwargs)
        if 'pbar' in locals():
            pbar.update(1)

    # Create animation object
    anim = _FuncAnimation(**{'fig': _plt.gcf(),
                             'func': animate,
                             'frames': len(time),
                             **kwargs})

    # Display
    if display is True:
        pbar = _tqdm(total=len(time))
        _display(_HTML(anim.to_html5_video()))
        pbar.close()
        del pbar

    return anim
Esempio n. 7
0
def _create_animation(od, time, plot_func, func_kwargs, display, **kwargs):
    """
    Create animation using oceanspy plot functions.
    
    Parameters
    ----------
    od: OceanDataset
        oceandataset to check for missing variables
    time: DataArray
        DataArray corresponding to time
    plot_func: function
        Alias referring to the plot function
    func_kwargs:
        Keyword arguments for plot_func
    display: bool
        If True, display the animation
    **kwargs:
        Keyword arguments for matplotlib.animation.FuncAnimation
        
    Returns
    -------
    Animation object
    
    See also
    --------
    subsample.coutout
    
    References
    ----------
    https://matplotlib.org/api/_as_gen/matplotlib.animation.FuncAnimation.html
    """

    # Check input
    if not isinstance(od, _ospy.OceanDataset):
        raise TypeError('`od` must be OceanDataset')

    if not isinstance(time, _xr.DataArray):
        raise TypeError('`time` must be a DataArray')
    elif len(time.dims) != 1:
        raise TypeError('`time` must have one dimension only')

    # TODO: check plot function

    if not isinstance(func_kwargs, (type(None), dict)):
        raise TypeError('`func_kwargs` must be None or dict')

    if not isinstance(display, bool):
        raise TypeError('`display` must be bool')

    # Handle kwargs
    if func_kwargs is None: func_kwargs = {}

    # Animate function
    def animate(i):
        _plt.clf()
        func_kwargs['cutout_kwargs'] = {
            'timeRange': time.isel({
                time.dims[0]: i
            }).values,
            'dropAxes': 'time'
        }
        with _io.capture_output() as captured:
            plot_func(od, **func_kwargs)
        if 'pbar' in locals(): pbar.update(1)

    # Create animation object
    anim = _FuncAnimation(**{
        'fig': _plt.gcf(),
        'func': animate,
        'frames': len(time),
        **kwargs
    })

    # Display
    if display is True:
        pbar = _tqdm(total=len(time))
        _display(_HTML(anim.to_html5_video()))
        pbar.close()
        del pbar

    return anim