Exemple #1
0
class NormalizeDist(ToolBase):
    """
    A simple example Tool.

    This tool re-scales the input distribution so that the sum
    is equal to `norm_val`.


    """
    norm_val = traitlets.Float(1, tooltip='new sum', label='norm')
    input_dist = traitlets.Instance(klass=DistributionSource,
                                    tooltip='input distribution',
                                    label='input')
    output_dist = traitlets.Instance(klass=DistributionSink,
                                     tooltip='output distribution',
                                     label='output')

    def run(self):
        # sanity checks
        if self.input_dist is None:
            raise ValueError("input source must be not-none")
        if self.output_dist is None:
            raise ValueError("output sink must be not-none")

        # grab data from input
        with self.input_dist as src:
            tmp_val = np.array(src.values(), dtype='float')
            edges = src.bin_edges()

        # scale data
        tmp_val *= self.norm_val / np.sum(tmp_val)

        # write results out
        with self.output_dist as snk:
            snk.write_dist(edges, tmp_val)
Exemple #2
0
class FileRepeat(ToolBase):
    """
    This is an example tool that takes in an OpaqueFileSource,
    OpaqueFileSink, and an integer.  The contents of the first file are
    repeated that number of times into the output file.
    """
    src_file = traitlets.Instance(klass=OpaqueFileSource,
                                  tooltip='source file',
                                  label='input')

    snk_file = traitlets.Instance(klass=OpaqueFileSink,
                                  tooltip='source file',
                                  label='output')
    repeat_count = traitlets.Integer(1,
                                     tooltip='number of times to repeat',
                                     label='input')

    def run(self):
        # grab the backing file of the source.  In general, source/sinks
        # need to be activated before they can be used, but you don't need to
        # in this case because you just need to get a string out.
        src_fname = self.src_file.backing_file
        # grab the backing file for the destination file
        snk_fname = self.snk_file.backing_file

        # open the output file for writing
        with open(snk_fname, 'w') as snk:
            # loop over the number of times to repeat
            for j in range(self.repeat_count):
                # open the source read only
                with open(src_fname, 'r') as src:
                    # copy all of the lines to the new file
                    for ln in src.readlines():
                        snk.write(ln)
Exemple #3
0
class ImageHistogram(ToolBase):
    out_file = traitlets.Instance(klass=OpaqueFigure,
                                  tooltip='Figure File',
                                  label='output')
    input_file = traitlets.Instance(klass=ImageSource,
                                    tooltip='Image File',
                                    label='input')

    def run(self):
        # import mpl and set non-gui backend
        import matplotlib
        matplotlib.use('Agg')
        import matplotlib.pyplot as plt

        import numpy as np

        # activate and grab input data
        with self.input_file as src:
            im = src.get_frame(0)

        # set up matplotlib figure + axes
        fig, ax = plt.subplots(1, 1)
        ax.set_xlabel('count')
        ax.set_ylabel('vals')

        # if rgb image, do each channel separately
        if len(im.shape) == 3 and im.shape[2] in (3, 4):
            # assume rgb
            # loop over colors
            for j, c in zip(xrange(3), ('r', 'g', 'b')):
                # compute histogram for channel
                vals, edges = np.histogram(im[..., j].flat, bins=100)
                # add line to graph
                ax.step(edges[:-1], vals, where='post', color=c, label=c)
        # other wise, treat as gray scale
        else:
            # compute histogram of image
            vals, edges = np.histogram(im.flat, bins=100)
            # add line to graph
            ax.step(edges[:-1], vals, where='post')

        # grab path of where to save figure
        with self.out_file as snk:
            fname = snk.backing_file
        # save the figure
        fig.savefig(fname)
        # clean up
        plt.close('all')
Exemple #4
0
class Tangle(TangleBase):
    """
    The base Tangle class: subclass this if you know your way around
    `traitlets`.

    Otherwise, check out `tangle`.
    """
    _view_name = traitlets.Unicode("TangleView", sync=True)
    _view_module = traitlets.Unicode(
        "/nbextensions/ipytangle/js/tangle_view.js", sync=True)

    # compatibilty with core types (interact)
    description = traitlets.Unicode("Tangle", sync=True)
    value = traitlets.Instance(sync=True, klass=TangleBase)

    # for the future?
    _tangle_prefix = traitlets.Unicode("", sync=True)
    _tangle_upstream_traits = traitlets.Tuple(sync=True)
    _tangle_cell_hiding = traitlets.Bool(sync=True)

    def __init__(self, *args, **kwargs):
        _dummy = widgets.DOMWidget()
        kwargs["_tangle_upstream_traits"] = tuple(_dummy.trait_names())
        super(Tangle, self).__init__(*args, **kwargs)
        self.value = self
        self.on_trait_change(self._notify_value)

    def _notify_value(self, name, old, new):
        if name != "value":
            self._notify_trait("value", self, self)
Exemple #5
0
class Result(documents.Document):

    title = traitlets.Unicode()
    smalltitle = traitlets.Unicode()

    value = traitlets.Any()
    date = traitlets.Instance(datetime.datetime)

    def __init__(self, *args, **kwargs):
        super(Result, self).__init__(*args, **kwargs)
        if self.date is None:
            self.date = datetime.datetime.now()

    def _result_html(self):
        if hasattr(self.value, '__html__'):
            return self.value.__html__()
        if hasattr(self.value, '__repr_html__'):
            return self.value.__repr_html__()
        elif isinstance(self.value, sympy.Expr):
            return sympy.latex(self.value)
        else:
            return str(self.value)

    def __repr_html__(self):
        template = env.get_template('base_report.html')
        return template.render(report = self)
Exemple #6
0
class LTThreshold(ToolBase):
    """
    Pixels less than value

    """
    input_file = traitlets.Instance(klass=ImageSource,
                                    tooltip='Image File',
                                    label='input')
    output_file = traitlets.Instance(klass=ImageSink,
                                    tooltip='Image File',
                                    label='output')
    min_val = traitlets.Float(1, tooltip='Minimum Value', label='min_val')

    def run(self):
        with self.input_file as src:
            # grab the input data
            res = _generic_thresh(src.get_frame(0),
                                  min_val=self.min_val)

        self.output_file.set_resolution(self.input_file.resolution,
                                        self.input_file.resolution_units)
        with self.output_file as snk:
            snk.record_frame(res, 0)
Exemple #7
0
class base_binary_op(ToolBase):
    """
    A template class for building binary operation tools
    for pyLight usage.  This is for operations that take two
    images (A and B) and no parameters (ex addition).
    """
    A = traitlets.Instance(klass=ImageSource,
                                    tooltip='Image File A',
                                    label='input')
    B = traitlets.Instance(klass=ImageSource,
                                    tooltip='Image File B',
                                    label='input')
    out = traitlets.Instance(klass=ImageSink,
                                    tooltip='Image File',
                                    label='output')

    @classmethod
    def available(cls):
        """
        Make this class non available (so it does not show up in
        the sub-class lists.
        """
        return False
Exemple #8
0
class PlotDist(ToolBase):
    """
    Loads a distribution and then saves a plot of it
    """
    input_dist = traitlets.Instance(klass=DistributionSource,
                                    tooltip='input distribution',
                                    label='input')
    out_file = traitlets.Instance(klass=OpaqueFigure,
                                  tooltip='Figure File',
                                  label='output')

    def run(self):
        try:
            # import mpl and set non-gui backend
            import matplotlib
            matplotlib.use('Agg')
            import matplotlib.pyplot as plt

            # activate and grab input data
            with self.input_dist as src:
                tmp_val = src.values()
                edges = src.bin_edges()

            # set up the plot
            fig, ax = plt.subplots(1, 1)
            ax.set_xlabel('bins')
            ax.set_ylabel('vals')
            # plot
            ax.step(edges, tmp_val, where='post', color='k')

            #
            with self.out_file as snk:
                fname = snk.backing_file
                fig.savefig(fname)

        except Exception as e:
            print(e)
Exemple #9
0
class VariationDataset(JsonTraits):
    info_text = "Variation dataset"

    name = tls.Unicode("no name", desc="Name")
    description = tls.Unicode("none", desc="Description")
    file_format = tls.Unicode("vcf", desc="File format")
    comments = tls.Unicode("", desc="Comments")
    kbase_genome_id = tls.Unicode("", desc="Genome identifier")
    kbase_genome_name = tls.Unicode("", desc="Genome name")
    shock_node_id = tls.Unicode("", desc="Shock node ID")
    properties = tls.Instance(VariationDataProperties, ())
    command_used = tls.Unicode("unspecified", desc="Command")

    def __repr__(self):
        return json.dumps(self.as_json())
Exemple #10
0
class Report(documents.Document):
    title = traitlets.Unicode()
    results = traitlets.List(documents.Reference(Result))
    date = traitlets.Instance(datetime.datetime)

    def __init__(self, *args, **kwargs):
        super(Report, self).__init__(*args, **kwargs)
        if self.date is None:
            self.date = datetime.datetime.now()

    def __html__(self):
        template = env.get_template('report_base.html')
        return template.render(report = self)

    def make_report(self, report_folder,openbrowser = True):
        save_html_report(self.__html__(), report_folder,
                         openbrowser=openbrowser)
Exemple #11
0
class Homework(traits.HasTraits):

    questions = traits.List
    text = traits.Unicode
    name = traits.Unicode
    due_date = traits.Instance(datetime.datetime)
Exemple #12
0
class NpSave(documents.Document):
    arr = traitlets.Instance(np.ndarray, db=True)
Exemple #13
0
class TestDocument(documents.Document):
    mstr = traitlets.Unicode(default_value = "axx", db= True)
    number = traitlets.Float(db=True)
    emb = traitlets.Instance(EmbDoc, db=True)
    moreembs = traitlets.List(traitlets.Instance(EmbDoc), db=True)
    lst = documents.TList(traitlets.Int)