示例#1
0
class Theme(param.Parameterized):
    """
    A Theme customizes the look and feel of a Template by providing
    custom CSS and bokeh Theme class.

    When adding a new theme a generic Theme class should be created,
    which is what users will important and set on the Template.theme
    parameter. Additionally a concrete implementation of the Theme
    should be created specific to the particular Template being used.

    For example when adding a DarkTheme there should be a
    corresponding MaterialDarkTheme which declares the Template class
    on its _template class variable. In this way a user can always use
    the generic Theme but the actual CSS and bokeh Theme will depend
    on the exact Template being used.
    """

    base_css = param.Filename()

    css = param.Filename()

    bokeh_theme = param.ClassSelector(class_=(_BkTheme, str))

    _template = None

    __abstract = True

    @classmethod
    def find_theme(cls, template_type):
        if cls._template is template_type:
            return cls
        for theme in param.concrete_descendents(cls).values():
            if theme._template is template_type:
                return theme
class FileImage(GenericImage):
    """
    2D Image generator that reads the image from a file.

    The image at the supplied filename is converted to grayscale if it
    is not already a grayscale image. See Image's Image class for
    details of supported image file formats.
    """

    filename = param.Filename(default='images/ellen_arthur.pgm',precedence=0.9,doc="""
        File path (can be relative to Param's base path) to a bitmap image.
        The image can be in any format accepted by PIL, e.g. PNG, JPG, TIFF, or PGM.
        """)


    def __init__(self, **params):
        """
        Create the last_filename attribute, used to hold the last
        filename. This allows reloading an existing image to be
        avoided.
        """
        super(FileImage,self).__init__(**params)
        self.last_filename = None


    def _get_image(self,p):
        """
        If necessary as indicated by the parameters, get a new image,
        assign it to self._image and return True.  If no new image is
        needed, return False.
        """
        if p.filename!=self.last_filename or self._image is None:
            self.last_filename=p.filename
            self._image = ImageOps.grayscale(Image.open(p.filename))
        return self._image
示例#3
0
文件: audio.py 项目: ivanov/imagen
class AudioFile(TimeSeries):
    """
    Requires an audio file in any format accepted by audiolab (wav, aiff, flac).
    """

    time_series = param.Array(precedence=(-1))
    sample_rate = param.Number(precedence=(-1))

    filename = param.Filename(default='sounds/complex/daisy.wav',
                              doc="""
        File path (can be relative to Param's base path) to an audio file. 
        The audio can be in any format accepted by audiolab, e.g. WAV, AIFF, or FLAC."""
                              )

    precision = param.Parameter(default=float64,
                                doc="""
        The float precision to use for loaded audio files.""")

    def __init__(self, **params):
        super(AudioFile, self).__init__(**params)
        self._load_audio_file()

    def _load_audio_file(self):
        source = audiolab.Sndfile(self.filename, 'r')

        # audiolab scales the range by the bit depth automatically so the dynamic range is now [-1.0, 1.0]
        # we rescale it to the range [0.0, 1.0]
        self.time_series = (
            source.read_frames(source.nframes, dtype=self.precision) + 1) / 2
        self.sample_rate = source.samplerate
示例#4
0
class DefaultTheme(Theme):
    """
    The DefaultTheme uses the standard Panel color palette.
    """

    base_css = param.Filename(default=pathlib.Path(__file__).parent /
                              'default.css')
示例#5
0
class MaterialDefaultTheme(DefaultTheme):

    css = param.Filename(default=pathlib.Path(__file__).parent / 'default.css')

    bokeh_theme = param.ClassSelector(class_=(_BkTheme, str),
                                      default=_BkTheme(json=MATERIAL_THEME))

    _template = MaterialTemplate
示例#6
0
class DarkTheme(Theme):
    """
    The DefaultTheme uses the standard Panel color palette.
    """

    base_css = param.Filename(default=pathlib.Path(__file__).parent /
                              'dark.css')

    bokeh_theme = param.ClassSelector(class_=(_BkTheme, str),
                                      default=_BkTheme(json=BOKEH_DARK))
示例#7
0
class MaterialDarkTheme(DarkTheme):
    """
    The MaterialDarkTheme is a Dark Theme in the style of Material Design
    """

    css = param.Filename(default=pathlib.Path(__file__).parent / 'dark.css')

    bokeh_theme = param.ClassSelector(
        class_=(_BkTheme, str), default=_BkTheme(json=MATERIAL_DARK_THEME))

    _template = MaterialTemplate
示例#8
0
class FastDarkTheme(DarkTheme):

    base_css = param.Filename(default=_ROOT / 'fast_root_dark.css')

    style = param.ClassSelector(default=DARK_STYLE, class_=FastStyle)

    __abstract = True

    @property
    def bokeh_theme(self):
        return _BkTheme(json=self.style.create_bokeh_theme())
示例#9
0
class ParameterSets(param.Parameterized):
    """
    Allows selection from sets of pre-defined parameters saved in YAML.

    Assumes the YAML file returns a list of groups of values.
    """

    examples_filename = param.Filename("attractors.yml")
    current           = param.Callable(lambda: None, precedence=-1)
    remember_this_one = param.Action(lambda x: x._remember())

    load      = param.Action(lambda x: x._load())
    randomize = param.Action(lambda x: x._randomize())
    sort      = param.Action(lambda x: x._sort())
    save      = param.Action(lambda x: x._save(), precedence=0.8)
    example   = param.Selector(objects=[[]], precedence=-1)

    def __init__(self,**params):
        super(ParameterSets,self).__init__(**params)
        self._load()

        self.attractors = OrderedDict(sorted([(k,v(name=k + " parameters")) for k,v in concrete_descendents(Attractor).items()]))
        for k in self.attractors:
            self.attractor(k, *self.args(k)[0])

    def _load(self):
        with open(self.examples_filename,"r") as f:
            vals = yaml.safe_load(f)
            assert(vals and len(vals)>0)
            self.param.example.objects=vals
            self.example = vals[0]

    def _save(self):
        with open(self.examples_filename,"w") as f:
            yaml.dump(self.param.example.objects,f)

    def __call__(self):        return self.example
    def _randomize(self):      npr.shuffle(self.param.example.objects)
    def _sort(self):            self.param.example.objects = list(sorted(self.param.example.objects))
    def _add_item(self, item): self.param.example.objects += [item] ; self.example=item

    def _remember(self):
        vals = self.current().vals()
        self._add_item(vals)

    def args(self, name):
        return [v[1:] for v in self.param.example.objects if v[0]==name]

    def attractor(self, name, *args):
        """Factory function to return an Attractor object with the given name and arg values"""
        attractor = self.attractors[name]
        fn_params = ['colormap'] + attractor.sig()
        attractor.param.set_param(**dict(zip(fn_params, args)))
        return attractor
class FastDarkTheme(DarkTheme):
    """The Dark Theme of the FastListTemplate"""

    css = param.Filename(default=pathlib.Path(__file__).parent / "dark.css")

    _template = FastListTemplate

    style = param.ClassSelector(class_=styles.FastStyle,
                                default=styles.DARK_STYLE)

    bokeh_theme = param.ClassSelector(
        class_=(_BkTheme, str), default=_BkTheme(json=styles.DARK_BOKEH_THEME))
class FastGridDefaultTheme(DefaultTheme):
    """The Default Theme of the FastGridTemplate"""

    css = param.Filename(default=pathlib.Path(__file__).parent / "default.css")

    _template = FastGridTemplate

    style = param.ClassSelector(class_=styles.FastStyle,
                                default=styles.DEFAULT_STYLE)

    bokeh_theme = param.ClassSelector(
        class_=(_BkTheme, str),
        default=_BkTheme(json=styles.DEFAULT_BOKEH_THEME))
 class _BigDumbParams(param.Parameterized):
     action = param.Action(default_action, allow_None=True)
     array = param.Array(np.array([1.0, 2.0]))
     boolean = param.Boolean(True, allow_None=True)
     callable = param.Callable(default_action, allow_None=True)
     class_selector = param.ClassSelector(int, is_instance=False, allow_None=True)
     color = param.Color("#FFFFFF", allow_None=True)
     composite = param.Composite(["action", "array"], allow_None=True)
     try:
         data_frame = param.DataFrame(
             pd.DataFrame({"A": 1.0, "B": np.arange(5)}), allow_None=True
         )
     except TypeError:
         data_frame = param.DataFrame(pd.DataFrame({"A": 1.0, "B": np.arange(5)}))
     date = param.Date(datetime.now(), allow_None=True)
     date_range = param.DateRange((datetime.min, datetime.max), allow_None=True)
     dict_ = param.Dict({"foo": "bar"}, allow_None=True, doc="dict means dictionary")
     dynamic = param.Dynamic(default=default_action, allow_None=True)
     file_selector = param.FileSelector(
         os.path.join(FILE_DIR_DIR, "LICENSE"),
         path=os.path.join(FILE_DIR_DIR, "*"),
         allow_None=True,
     )
     filename = param.Filename(
         os.path.join(FILE_DIR_DIR, "LICENSE"), allow_None=True
     )
     foldername = param.Foldername(os.path.join(FILE_DIR_DIR), allow_None=True)
     hook_list = param.HookList(
         [CallableObject(), CallableObject()], class_=CallableObject, allow_None=True
     )
     integer = param.Integer(10, allow_None=True)
     list_ = param.List([1, 2, 3], allow_None=True, class_=int)
     list_selector = param.ListSelector([2, 2], objects=[1, 2, 3], allow_None=True)
     magnitude = param.Magnitude(0.5, allow_None=True)
     multi_file_selector = param.MultiFileSelector(
         [],
         path=os.path.join(FILE_DIR_DIR, "*"),
         allow_None=True,
         check_on_set=True,
     )
     number = param.Number(-10.0, allow_None=True, doc="here is a number")
     numeric_tuple = param.NumericTuple((5.0, 10.0), allow_None=True)
     object_selector = param.ObjectSelector(
         False, objects={"False": False, "True": 1}, allow_None=True
     )
     path = param.Path(os.path.join(FILE_DIR_DIR, "LICENSE"), allow_None=True)
     range_ = param.Range((-1.0, 2.0), allow_None=True)
     series = param.Series(pd.Series(range(5)), allow_None=True)
     string = param.String("foo", allow_None=True, doc="this is a string")
     tuple_ = param.Tuple((3, 4, "fi"), allow_None=True)
     x_y_coordinates = param.XYCoordinates((1.0, 2.0), allow_None=True)
示例#13
0
文件: theme.py 项目: Jhsmit/PyHDX
class ExtendedGoldenDarkTheme(pn.template.golden.GoldenDarkTheme):

    css = param.Filename(
        default=pathlib.Path(__file__).parent
        / "static"
        / "extendedgoldentemplate"
        / "dark.css"
    )

    _template = ExtendedGoldenTemplate

    bokeh_theme = param.ClassSelector(
        class_=(BkTheme, str), default=BkTheme(json=custom_dark_json_theme)
    )
示例#14
0
    class MyParameterized(param.Parameterized):
        enable = param.Boolean(True,
                               doc="A sample Boolean parameter",
                               allow_None=True)
        what_proportion = param.Magnitude(default=0.9)
        age = param.Number(49,
                           bounds=(0, 100),
                           doc="Any Number between 0 to 100")
        how_many = param.Integer()
        favorite_quote = param.String(default="Hello, world!")

        choose_file_or_folder = param.Path(search_paths='./')
        choose_folder = param.Foldername(search_paths="./")
        choose_file = param.Filename(search_paths="./")
        select_a_file = param.FileSelector(path='./*')
        select_multiple_files = param.MultiFileSelector(path='./*')

        favorite_color = param.ObjectSelector(
            default="green", objects=["red", "yellow", "green"])
        favorite_fruit = param.Selector(default="Apple",
                                        objects=["Orange", "Apple", "Mango"])
        select_multiple = param.ListSelector(default=[3, 5],
                                             objects=[1, 2, 3, 4, 5])

        birthday = param.CalendarDate(dt.date(2017, 1, 1),
                                      bounds=(dt.date(2017, 1,
                                                      1), dt.date(2017, 2, 1)))
        appointment = param.Date(dt.datetime(2017, 1, 1),
                                 bounds=(dt.datetime(2017, 1, 1),
                                         dt.datetime(2017, 2, 1)))
        least_favorite_color = param.Color(default='#FF0000')
        dataset = param.DataFrame(pd.util.testing.makeDataFrame().iloc[:3])

        this_strange_thing = param.Tuple(default=(False, ), allow_None=True)
        some_numbers = param.NumericTuple(default=(1, 2, 3.0, 4.0))
        home_city = param.XYCoordinates(default=(-111.65, 40.23))
        bounds = param.Range(default=(-10, 10))
示例#15
0
class SMLMParameters(param.Parameterized):
    """
    SMLM parameter definitions
    """
    # movie
    source = param.ObjectSelector(
        default='nstorm',
        objects=['nstorm', 'elyra', 'homemade'],
        doc='the software that was used to create the movie')
    # channel
    channel = param.Integer(0, bounds=(0, 3), doc="Which channel to process")
    # is this a 3D acquisition
    is_3d = param.Boolean(default=False,
                          bounds=(0, 1),
                          doc="The type of acquisition - 2D or 3D")
    # if it is, what is the step size
    z_step = param.Number(50.0,
                          bounds=(50.0, 100.0),
                          doc="z step size for 3D calibration")
    # are we doing a z calibration
    is_zcalibration = param.Boolean(default=False,
                                    bounds=(0, 1),
                                    doc="Are we making a z calibration?")
    zcal_type = param.ObjectSelector(
        default='fourth_poly',
        objects=['fourth_poly', 'zdefocus'],
        doc="The curve fit method for 3D calibration")
    start_frame = param.Integer(0,
                                bounds=(0, None),
                                doc="Movie frame on which to start analysis")
    stop_frame = param.Integer(1,
                               bounds=(1, None),
                               doc="Movie frame on which to stop analysis")
    camera_pixel = param.Number(160,
                                doc="Camera pixel size in image plane in nm")
    frame_width = param.Integer(256, doc="Raw image width in pixels")
    frame_height = param.Integer(256, doc="Raw image height in pixels")
    photon_conversion = param.Number(
        0.45, doc="Factor for converting ADC to photons")
    # locate
    locate_method = param.ObjectSelector(
        default='uniform',
        objects=['wavelet', 'uniform', 'dog'],
        doc=("The method using for preprocessing when"
             "estimating molecule positions"))
    # intensity thresholding for object identification
    threshold_method = param.ObjectSelector(
        default='std',
        objects=['std', 'manual', 'something'],
        doc="The thresholding method - 'std' or 'manual'")
    threshold = param.Number(0.0, bounds=(0.0, None), doc="Threshold in ADU")
    # locate
    samples = param.Integer(
        3,
        bounds=(1, 5),
        doc="Number of samples for uniform and maximum filters")
    # wavelet parameters
    wavelet_spline_order = param.Integer(
        3,
        bounds=(1, 5),
        doc="Spline order for wavelet filter (default is 3.0)")
    wavelet_spline_scale = param.Integer(
        2,
        bounds=(1, 3),
        doc="Spline scale for wavelet filter (default is 2.0)")
    # refine
    # localisation method used
    refine_method = param.ObjectSelector(default='gauss',
                                         objects=['gauss', 'phasor'],
                                         doc="The iterative fitting method")
    iter_method = param.ObjectSelector(default='mle',
                                       objects=['mle', 'ls'],
                                       doc="The type of gaussian fitting")
    # PSF parameters
    psf = param.ObjectSelector(default='circular',
                               objects=['circular', 'elliptical'],
                               doc="The (Gaussian) modelled PSF shape")
    # iterative 'fitting' parameters
    max_iter = param.Integer(
        500,
        bounds=(500, 5000),
        doc="Maximum number of iterations to attempt convergance")
    tol = param.Number(
        1e-6,
        doc="tolerance for curve fitting or log likelihood determination")
    # fitting window (used for phasor or any iterative method)
    window = param.Integer(
        5,
        bounds=(5, 11),
        doc="Window for molecule localisation (needs to be an odd number)")
    # drift correction
    blocksize = param.Integer(
        1000,
        bounds=(500, 5000),
        doc="Number of camera frames to be grouped for drift correction")
    # linking
    radius = param.Number(0.5,
                          bounds=(0.5, 1.0),
                          doc="Search radius for linking in pixels")
    max_gap = param.Integer(
        3,
        bounds=(0, 10),
        doc="Maximum number of frames a peak can disappear when linking")
    max_length = param.Integer(0,
                               bounds=(0, 1000),
                               doc="Maximum length of link (0 is unlimited)")
    # reconstruction
    scale = param.Integer(
        5,
        bounds=(2, 20),
        doc=
        "The upscaling factor to determine frame size in reconstructed image")
    z_pix = param.Number(100.0,
                         bounds=(50.0, 200.0),
                         doc="Voxel size in z direction (nm) for 3D rendering")
    # io
    movie_path = param.Filename()
    locs_path = param.String()
    zcal_path = param.Filename()
示例#16
0
文件: image.py 项目: fcr/imagen
class FileImage(GenericImage):
    """
    2D Image generator that reads the image from a file.

    Grayscale versions of the image are always available, converted
    from the color version if necessary.  For color images,
    three-channel color values are available through the channels()
    method. See Image's Image class for details of supported image
    file formats.
    """

    filename = param.Filename(default='images/ellen_arthur.pgm',
                              precedence=0.9,
                              doc="""
        File path (can be relative to Param's base path) to a bitmap
        image.  The image can be in any format accepted by PIL,
        e.g. PNG, JPG, TIFF, or PGM as well or numpy save files (.npy
        or .npz) containing 2D or 3D arrays (where the third dimension
        is used for each channel).""")

    def __init__(self, **params):
        self.last_filename = None  # Cached to avoid unnecessary reloading for each channel
        self._cached_average = None
        super(FileImage, self).__init__(
            **params)  ## must be called after setting the class-attributes
        self._image = None  # necessary to ensure reloading of data (due to cache mechanisms
        # call after super.__init__, which calls _get_image()

    def __call__(self, **params_to_override):
        # Cache image to avoid channel_data being deleted before channel-specific processing completes.
        p = param.ParamOverrides(self, params_to_override)

        if not (p.cache_image and (p._image is not None)):
            self._cached_average = super(FileImage,
                                         self).__call__(**params_to_override)

            self._channel_data = self._process_channels(
                p, **params_to_override)

            for c in self.channel_transforms:
                self._channel_data = c(self._channel_data)

            if p.cache_image is False:
                self._image = None

        return self._cached_average

    def set_matrix_dimensions(self, *args):
        """
        Subclassed to delete the cached image when matrix dimensions
        are changed.
        """
        self._image = None
        super(FileImage, self).set_matrix_dimensions(*args)

    def _get_image(self, p):
        file_, ext = splitext(p.filename)
        npy = (ext.lower() == ".npy")
        reload_image = (p.filename != self.last_filename
                        or self._image is None)

        self.last_filename = p.filename

        if reload_image:
            if npy:
                self._load_npy(p.filename)
            else:
                self._load_pil_image(p.filename)

        return self._image

    def _load_pil_image(self, filename):
        """
        Load image using PIL.
        """
        self._channel_data = []
        self._original_channel_data = []

        im = Image.open(filename)
        self._image = ImageOps.grayscale(im)
        im.load()

        file_data = np.asarray(im, float)
        file_data = file_data / file_data.max()

        # if the image has more than one channel, load them
        if (len(file_data.shape) == 3):
            num_channels = file_data.shape[2]
            for i in range(num_channels):
                self._channel_data.append(file_data[:, :, i])
                self._original_channel_data.append(file_data[:, :, i])

    def _load_npy(self, filename):
        """
        Load image using Numpy.
        """
        self._channel_data = []
        self._original_channel_data = []
        file_channel_data = np.load(filename)
        file_channel_data = file_channel_data / file_channel_data.max()

        for i in range(file_channel_data.shape[2]):
            self._channel_data.append(file_channel_data[:, :, i])
            self._original_channel_data.append(file_channel_data[:, :, i])

        self._image = file_channel_data.sum(2) / file_channel_data.shape[2]
示例#17
0
class ReactDarkTheme(DarkTheme):

    css = param.Filename(default=pathlib.Path(__file__).parent / 'dark.css')

    _template = ReactTemplate
示例#18
0
文件: rapids.py 项目: xizil/cuxfilter
class RapidsTheme(Theme):
    DARK = {
        "attrs": {
            "Figure": {
                "background_fill_color": "#2f2f2f",
                "border_fill_color": "#2f2f2f",
                "outline_line_color": "#E0E0E0",
                "outline_line_alpha": 0.25,
            },
            "Grid": {
                "grid_line_color": "#a0a0a0",
                "grid_line_alpha": 0.25,
                "dimension": 1,
            },
            "Axis": {
                "major_tick_line_alpha": 0.25,
                "major_tick_line_color": "#E2E2E2",
                "minor_tick_line_alpha": 0,
                "minor_tick_line_color": "#A2A2A2",
                "axis_line_alpha": 0,
                "axis_line_color": "#E0E0E0",
                "major_label_text_color": "#E2E2E2",
                "major_label_text_font": "Helvetica",
                "major_label_text_font_size": "1.025em",
                "axis_label_standoff": 10,
                "axis_label_text_color": "#a0a0a0",
                "axis_label_text_font": "Helvetica",
                "axis_label_text_font_size": "1.25em",
                "axis_label_text_font_style": "bold",
            },
            "Legend": {
                "spacing": 8,
                "glyph_width": 15,
                "label_standoff": 8,
                "label_text_color": "#E0E0E0",
                "label_text_font": "Helvetica",
                "label_text_font_size": "1.025em",
                "border_line_alpha": 0,
                "background_fill_alpha": 0.25,
                "background_fill_color": "#20262B",
                "background_color": "#2f2f2f",
                "text_color": "#a0a0a0",
            },
            "ColorBar": {
                "title_text_color": "#e0e0e0",
                "title_text_font": "Helvetica",
                "title_text_font_size": "1.025em",
                "title_text_font_style": "normal",
                "major_label_text_color": "#E0E0E0",
                "major_label_text_font": "Helvetica",
                "major_label_text_font_size": "1.025em",
                "background_fill_color": "#15191C",
                "background_fill_alpha": 0.4,
                "major_tick_line_alpha": 0,
                "bar_line_alpha": 0,
            },
            "Title": {
                "text_color": "#a0a0a0",
                "text_font": "helvetica",
                "text_font_size": "1.15em",
                "text_font_style": "bold",
            },
        }
    }

    bokeh_theme = _BkTheme(json=DARK)
    mapbox_style = "mapbox://styles/mapbox/dark-v9"
    color_palette = list(palettes.Purples[9])
    chart_color = "#8735fb"
    css = param.Filename(default=STATIC_DIR_THEMES / "rapids.css")
    datatile_active_color = "#8735fb"

    # Custom React Template
    _template = ReactTemplate

    # datasize_indicator_class: The color of the progress bar, one of
    # 'primary', 'secondary', 'success', 'info', 'warn', 'danger', 'light',
    # 'dark'
    datasize_indicator_class = "primary"
示例#19
0
class VanillaDarkTheme(DarkTheme):

    css = param.Filename(default=pathlib.Path(__file__).parent / 'dark.css')

    _template = VanillaTemplate
示例#20
0
class PyGauge(param.Parameterized):
    value = param.Integer(85, bounds=(0, 1000))
    max_value = param.Integer(150)
    pygal_config = pygal.Config()

    custom_style = param.Dict(default=dict(
        background="transparent",
        plot_background="transparent",
        foreground="#0000ff",  # 53E89B",
        foreground_strong="#53A0E8",
        foreground_subtle="transparent",
        opacity=".2",
        opacity_hover=".9",
        transition="400ms ease-in",
        colors=("#0000ff", "#ff0000"),
    ))
    custom_style_css_path = param.Filename(css_file_gauge)

    css_info_h2 = """
        margin: auto;
    """
    size_w = param.Integer(100)
    value_font_size = param.Integer()
    w_name = ""

    def __init__(self, **params):
        super(PyGauge, self).__init__(**params)
        self.set_max()
        self.value_font_size = len(str(self.value)) * self.size_w
        self.w_name = self.name

    @pn.depends("value_font_size", "custom_style", watch=True)
    def set_style(self):
        if self.custom_style_css_path:
            self.pygal_config.css.append(self.custom_style_css_path)
            # with open(self.custom_style_css_path, 'r') as f: css = f.read()
            # self.custom_style = css2dict(css)

        self.custom_style["value_font_size"] = self.value_font_size
        self.param["custom_style"].default = self.custom_style

    @pn.depends("max_value", watch=True)
    def set_max(self):
        self.param.value.bounds = (0, self.max_value)
        if self.max_value == 0:
            self.max_value = int(1e5)
        self.value = self.max_value if self.value > self.max_value else self.value

    @pn.depends("value", "custom_style", watch=True)
    def create_gauge(self):
        gauge = pygal.SolidGauge(
            inner_radius=0.70,
            show_legend=False,
            style=Style(**self.custom_style),
        )
        percent_formatter = lambda x: "{:.10g}".format(x)
        gauge.value_formatter = percent_formatter
        vals = {"value": self.value, "max_value": self.max_value}
        gauge.add("", [vals])
        self.file_name = gauge.render_data_uri()
        self.HTML_GAUGE_HEADER = """
        <h2 style="{css_info_h2}">{name}</h2>
        """.format(
            name=self.w_name,
            css_info_h2=self.css_info_h2,
        )

        self.HTML_GAUGE_IMG = """
        <img src="{filepath}" width="{width}px" />
        
        """.format(
            filepath=self.file_name,
            width=self.size_w,
        )

    def view(self):
        self.create_gauge()
        return pn.pane.HTML(
            self.HTML_GAUGE_HEADER + self.HTML_GAUGE_IMG,
            css_classes=[
                re.sub(r"(?<!^)(?=[A-Z])", "-",
                       type(self).__name__).lower()
            ],
        )
示例#21
0
class ExtendedGoldenDefaultTheme(pn.template.golden.GoldenDefaultTheme):

    css = param.Filename(default=pathlib.Path(__file__).parent / 'static' / 'extendedgoldentemplate' / 'default.css')

    _template = ExtendedGoldenTemplate
示例#22
0
class GoldenDarkTheme(DarkTheme):

    css = param.Filename(default=pathlib.Path(__file__).parent / 'dark.css')

    _template = GoldenTemplate
示例#23
0
class BootstrapDarkTheme(DarkTheme):

    css = param.Filename(default=pathlib.Path(__file__).parent / 'dark.css')

    _template = BootstrapTemplate
示例#24
0
class MednumDefaultTheme(DefaultTheme):

    css = param.Filename(default=pathlib.Path(__file__).parent / 'default.css')

    _template = MednumTemplate
示例#25
0
文件: audio.py 项目: ivanov/imagen
class AudioFolder(AudioFile):
    """
    Returns a rolling spectrogram, i.e. the spectral density over time 
    of a rolling window of the input audio signal, for all files in the 
    specified folder.
    """

    filename = param.Filename(precedence=(-1))

    folderpath = param.Foldername(
        default='sounds/sine_waves/normalized',
        doc="""Folder path (can be relative to Param's base path) to a
        folder containing audio files. The audio can be in any format accepted 
        by audiolab, i.e. WAV, AIFF, or FLAC.""")

    gap_between_sounds = param.Number(
        default=0.0,
        bounds=(0.0, None),
        doc="""The gap in seconds to insert between consecutive soundfiles.""")

    def __init__(self, **params):
        super(AudioFolder, self).__init__(**params)
        self._load_audio_folder()

    def _load_audio_folder(self):
        folder_contents = os.listdir(self.folderpath)
        self.sound_files = []

        for file in folder_contents:
            if file[-4:] == ".wav" or file[-3:] == ".wv" or file[
                    -5:] == ".aiff" or file[-4:] == ".aif" or file[
                        -5:] == ".flac":
                self.sound_files.append(self.folderpath + "/" + file)

        self.filename = self.sound_files[0]
        self._load_audio_file()
        self.next_file = 1

    def extract_specific_interval(self, interval_start, interval_end):
        """
        Overload if special behaviour is required when a series ends.
        """

        interval_start = int(interval_start)
        interval_end = int(interval_end)

        if interval_start >= interval_end:
            raise ValueError(
                "Requested interval's start point is past the requested end point."
            )

        elif interval_start > self.time_series.size:
            if self.repeat:
                interval_end = interval_end - interval_start
                interval_start = 0
            else:
                raise ValueError(
                    "Requested interval's start point is past the end of the time series."
                )

        if interval_end < self.time_series.size:
            interval = self.time_series[interval_start:interval_end]

        else:
            requested_interval_size = interval_end - interval_start
            remaining_signal = self.time_series[interval_start:self.
                                                time_series.size]

            if self.next_file == len(self.sound_files) and self.repeat:
                self.next_file = 0

            if self.next_file < len(self.sound_files):
                next_source = audiolab.Sndfile(
                    self.sound_files[self.next_file], 'r')
                self.next_file += 1

                if next_source.samplerate != self.sample_rate:
                    raise ValueError(
                        "All sound files must be of the same sample rate")

                if self.gap_between_sounds > 0:
                    remaining_signal = hstack(
                        (remaining_signal,
                         zeros(int(self.gap_between_sounds * self.sample_rate),
                               dtype=self.precision)))

                self.time_series = hstack(
                    (remaining_signal,
                     next_source.read_frames(next_source.nframes,
                                             dtype=self.precision)))

                interval = self.time_series[0:requested_interval_size]
                self._next_interval_start = requested_interval_size

            else:
                self.warning("Returning last interval of the time series.")
                self._next_interval_start = self.time_series.size + 1

                samples_per_interval = self.interval_length * self.sample_rate
                interval = hstack(
                    (remaining_signal,
                     zeros(samples_per_interval - remaining_signal.size)))

        return interval
示例#26
0
class FastGridDefaultTheme(FastDefaultTheme):
    """The Default Theme of the FastGridTemplate"""

    css = param.Filename(default=pathlib.Path(__file__).parent / "default.css")

    _template = FastGridTemplate
示例#27
0
class MaterialDarkTheme(DarkTheme):

    css = param.Filename(default=pathlib.Path(__file__).parent / 'dark.css')

    _template = MaterialTemplate
示例#28
0
文件: light.py 项目: xizil/cuxfilter
class LightTheme(DefaultTheme):
    LIGHT = {
        "attrs": {
            "Figure": {
                "background_fill_color": "#ffffff",
                "border_fill_color": "#ffffff",
                "outline_line_color": "#000000",
                "outline_line_alpha": 0.25,
            },
            "Grid": {
                "grid_line_color": "#a0a0a0",
                "grid_line_alpha": 0.25,
                "dimension": 1,
            },
            "Axis": {
                "major_tick_line_alpha": 0.25,
                "major_tick_line_color": "#262626",
                "minor_tick_line_alpha": 0,
                "minor_tick_line_color": "#a0a0a0",
                "axis_line_alpha": 0,
                "axis_line_color": "#000000",
                "major_label_text_color": "#262626",
                "major_label_text_font": "Helvetica",
                "major_label_text_font_size": "1.025em",
                "axis_label_standoff": 10,
                "axis_label_text_color": "#a0a0a0",
                "axis_label_text_font": "Helvetica",
                "axis_label_text_font_size": "1.25em",
                "axis_label_text_font_style": "bold",
            },
            "Legend": {
                "spacing": 8,
                "glyph_width": 15,
                "label_standoff": 8,
                "label_text_color": "#000000",
                "label_text_font": "Helvetica",
                "label_text_font_size": "1.025em",
                "border_line_alpha": 0,
                "background_fill_alpha": 0.4,
                "background_fill_color": "#ffffff",
                "background_color": "#ffffff",
                "text_color": "#000000",
            },
            "ColorBar": {
                "title_text_color": "#000000",
                "title_text_font": "Helvetica",
                "title_text_font_size": "1.025em",
                "title_text_font_style": "normal",
                "major_label_text_color": "#000000",
                "major_label_text_font": "Helvetica",
                "major_label_text_font_size": "1.025em",
                "background_fill_color": "#ffffff",
                "background_fill_alpha": 0.4,
                "major_tick_line_alpha": 0,
                "bar_line_alpha": 0,
            },
            "Title": {
                "text_color": "#a0a0a0",
                "text_font": "helvetica",
                "text_font_size": "1.15em",
                "text_font_style": "bold",
            },
        }
    }
    bokeh_theme = _BkTheme(json=LIGHT)
    mapbox_style = "mapbox://styles/mapbox/light-v9"
    color_palette = list(palettes.Blues[9])
    chart_color = "#4292c6"
    css = param.Filename(default=STATIC_DIR_THEMES / "default.css")
    datatile_active_color = DATATILE_ACTIVE_COLOR

    # Custom React Template
    _template = ReactTemplate

    # datasize_indicator_class: The color of the progress bar, one of
    # 'primary', 'secondary', 'success', 'info', 'warn', 'danger', 'light',
    # 'dark'
    datasize_indicator_class = "success"
示例#29
0
class FastListDarkTheme(FastDarkTheme):
    """The Dark Theme of the FastListTemplate"""

    css = param.Filename(default=pathlib.Path(__file__).parent / "dark.css")

    _template = FastListTemplate