class CurveFit(param.Parameterized):

    dataset = param.FileSelector(path='./*.csv*', label="Choose a file")

    fit_curve = param.Boolean(False, label="Fit Curve")

    @param.depends('dataset', 'fit_curve', watch=True)
    def view(self):

        data = pd.read_csv(self.dataset)

        fig, ax = plt.subplots()

        if self.fit_curve:
            slope, intercept, _, _, _ = stats.linregress(data['x'], data['y'])

            ax = sns.regplot(x="x",
                             y="y",
                             data=data,
                             color='blue',
                             line_kws={
                                 'label':
                                 "y={0:.1f}x+{1:.1f}".format(slope, intercept)
                             })

            ax.legend()
        else:
            data.plot.scatter(x="x", y="y", c="blue", ax=ax)

        plt.close(fig)
        return fig
示例#2
0
class Dashboard(param.Parameterized):
    file_selector = param.FileSelector()
    progress = pn.widgets.Progress(active=False)

    @param.depends("file_selector", watch=True)
    def activate_upload_status(self):
        self.progress.active = True
示例#3
0
class GriddedRoughness(RoughnessSpecification):
    """Roughness specified as a land-use grid file."""
    __abstract = True
    
    land_use_grid = param.FileSelector(default=None, doc="""
       Path to land use grid to use for roughness.""")

    def get_args(self):
        raise NotImplementedError
示例#4
0
class CreateGSSHAModel(CreateModel):
    """Create a new GSSHA model."""

    mask_shapefile = param.FileSelector(
        default='./vicksburg_watershed/watershed_boundary.shp',
        path='./*/*.shp',
        doc="""
       Path to watershed boundary shapefile. Required for new model. Typically a *.shp file.""",
        precedence=0.1)

    grid_cell_size = param.Number(default=None, precedence=0.2)

    # TODO: specify acceptable file extensions?
    elevation_grid_path = param.FileSelector(doc="""
       Path to elevation raster used for GSSHA grid. Required for new model. Typically a *.ele file.""",
                                             precedence=0.3)

    # TODO: paramnb ClassSelector should cache instances that get
    # created or else editing parameters on non-default options is
    # confusing.
    roughness = param.ClassSelector(RoughnessSpecification,
                                    default=UniformRoughness(),
                                    doc="""
        Method for specifying roughness""",
                                    precedence=-1)

    out_hydrograph_write_frequency = param.Number(default=10,
                                                  bounds=(1, 60),
                                                  doc="""
       Frequency of writing to hydrograph (minutes). Sets HYD_FREQ card. Required for new model.""",
                                                  precedence=0.8)

    def _map_kw(self, p):
        kw = super(CreateGSSHAModel, self)._map_kw(p)
        kw['mask_shapefile'] = p.mask_shapefile
        kw['grid_cell_size'] = p.grid_cell_size
        kw['elevation_grid_path'] = os.path.abspath(p.elevation_grid_path)
        kw['out_hydrograph_write_frequency'] = p.out_hydrograph_write_frequency
        kw.update(p.roughness.get_args())
        return kw

    def __call__(self, **params):
        p = param.ParamOverrides(self, params)
        return GSSHAModel(**self._map_kw(p))
示例#5
0
class GriddedRoughnessTable(GriddedRoughness):
    """Roughness specified as a land-use grid file and roughness table."""

    land_use_to_roughness_table = param.FileSelector(default=None, doc="""
       Path to land use to roughness table.""") 
    
    def get_args(self):
        return {
            'roughness': None,
            'land_use_grid': self.land_use_grid,
            'land_use_to_roughness_table': self.land_use_to_roughness_table,
            'land_use_grid_id': None
        }
 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)
示例#7
0
class Activity(param.Parameterized):
    """A model of an Activity

    Currently the Activity is based on data from a .fitfile
    """

    file = param.FileSelector(
        doc="A bytes object. Current only .fit files are supported")
    data = param.DataFrame(doc="The records of the file")

    @param.depends(
        "file",
        watch=True,
    )
    @progress.report(message="Parsing Activity File")
    def parse_file(self, ):
        """Converts the file to the training_data"""
        if self.file:
            self.data = fit_file_services.parse_fit_file(self.file)

    @param.depends("data")
    @progress.report(message="Creating Activity Plots")
    def activity_plots(self, ):
        """A layout of plots of the activity data. For example timestamp vs power.

        Returns:
            HoloViews: A layout of plots
        """
        return activity_plot.activity_plots(self.data)

    @param.depends("data")
    @progress.report(message="Creating Map")
    def map_plot(self, ):
        """The route on a map

        Returns:
                HoloViews: A plot of the route on a map.
        """
        return activity_plot.map_plot(self.data)

    def view(self, ) -> pn.viewable.Viewable:
        """A view of the Activity

        Returns:
            pn.viewable.Viewable: A view of the Activity
        """
        return activity_view.ActivityView(
            self.param,
            self.map_plot,
            self.activity_plots,
        )
class Inputs(param.Parameterized):

    input_file = param.FileSelector(path=r".\sample_data\\*.csv",
                                    doc="A .csv file selector for input data")
    x_field = param.Selector(doc="A field selector for longitude")
    y_field = param.Selector(doc="A field selector for latitude")
    id_field = param.Selector(doc="A field selector for the identifier")
    data = None

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

        if self.param.input_file.default:
            self.input_file = self.param.input_file.default

        self._update_inputs()

    @param.depends("input_file", watch=True)
    def _update_inputs(self):
        if self.input_file in FILE_STORE:
            df = FILE_STORE[self.input_file].copy(deep=True)
        else:
            df = pd.read_csv(self.input_file)
            FILE_STORE[self.input_file] = df.copy(deep=True)

        numeric_cols = list(df.select_dtypes(include=["float64"]).columns)
        columns = [x for i, x in enumerate(df.columns) if x != "Unnamed: 0"]
        self.param.x_field.objects = numeric_cols
        if "lng" in numeric_cols:
            self.x_field = "lng"
        elif numeric_cols:
            self.x_field = numeric_cols[0]

        self.param.y_field.objects = numeric_cols
        if "lat" in numeric_cols:
            self.y_field = "lat"
        elif numeric_cols:
            self.y_field = numeric_cols[0]

        self.param.id_field.objects = columns
        if "comName" in columns:
            self.id_field = "comName"
        elif columns:
            self.id_field = columns[0]

        self.data = df
示例#9
0
    class Example(BaseClass):
        """An example Parameterized class"""

        timestamps = []

        boolean = param.Boolean(True, doc="A sample Boolean parameter")
        color = param.Color(default="#FFFFFF")
        date = param.Date(dt.date(2017, 1, 1), bounds=wired.DATE_BOUNDS)
        dataframe = param.DataFrame(pd.util.testing.makeDataFrame().iloc[:3])
        select_string = param.ObjectSelector(default="yellow", objects=["red", "yellow", "green"])
        select_fn = param.ObjectSelector(default=list, objects=[list, set, dict])
        int_list = param.ListSelector(default=[3, 5], objects=[1, 3, 5, 7, 9], precedence=0.5)
        single_file = param.FileSelector(path="../../*/*.py*", precedence=0.5)
        multiple_files = param.MultiFileSelector(path="../../*/*.py?", precedence=0.5)
        record_timestamp = param.Action(
            lambda x: x.timestamps.append(dt.datetime.utcnow()),
            doc="""Record timestamp.""",
            precedence=0.7,
        )
示例#10
0
class Inputs(param.Parameterized):

    input_file = param.FileSelector(
        path=".\sample_data\*.csv", doc="A .csv file selector for input data"
    )
    x_field = param.Selector(doc="A field selector for longitude")
    y_field = param.Selector(doc="A field selector for latitude")
    id_field = param.Selector(doc="A field selector for the identifier")
    data = None

    @param.depends("input_file", watch=True)
    def update_inputs(self):

        df = pd.read_csv(self.input_file)
        numeric_cols = list(df.select_dtypes(include=["float64"]).columns)
        columns = [x for i, x in enumerate(df.columns) if x != "Unnamed: 0"]
        self.param.x_field.objects = numeric_cols
        self.x_field = numeric_cols[0]
        self.param.y_field.objects = numeric_cols
        self.x_field = numeric_cols[0]
        self.param.id_field.objects = columns
        self.id_field = columns[0]
        self.data = df
示例#11
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))
示例#12
0
class ImageClassifierApp(param.Parameterized):
    """The Image Classifier App

    We define the parameters, views and depencies of the app
    """

    model = param.ObjectSelector()
    image_file = param.FileSelector()
    top_predictions = param.ClassSelector(class_=list)
    progress_value = param.Integer()
    progress_message = param.String()

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

        config_keras_applications()

        self.param.model.default = KERAS_APPLICATIONS[
            DEFAULT_KERAS_APPLICATION_INDEX]
        self.param.model.objects = KERAS_APPLICATIONS
        self.model = KERAS_APPLICATIONS[DEFAULT_KERAS_APPLICATION_INDEX]

    @param.depends("model")
    def resources_view(self, ):
        """A view of a section with links to resources"""
        if self.model:
            return pn.pane.Markdown(get_resources_markdown(self.model))
        return pn.pane.HTML()

    # @param.depends("image_file", watch=True)
    # def set_image(self):
    #     self.image = Image.open(io.BytesIO(self.image_file))

    @param.depends("image_file")
    def image_view(self, ):
        """A view of the image_file"""
        if self.image_file:
            bytes_io = io.BytesIO(self.image_file)
            return pn.pane.HTML(
                ('<img application="data:image/jpg;base64,{0}" '
                 'style="height:400px;min-width:600px;"/>').format(
                     b64encode(bytes_io.getvalue()).decode("utf-8")))
        return pnx.InfoAlert(
            "Upload an image in .jpg format",
            height=400,
            min_width=600,
        )

    def report_progress(
        self,
        message: str = "",
        value: int = 0,
    ):
        """Update the progress message and value

        Args:
            message (str, optional): A message to convery to the user. Defaults to "".
            value (int, optional): A progress value between 0 and 100. Defaults to 0.
        """
        self.progress_message = message
        self.progress_value = value

    @param.depends(
        "image_file",
        "model",
        watch=True,
    )
    def set_top_predictions(self, ):
        """Updates the top_predictions"""
        self.top_predictions = None

        if self.image_file and self.model:
            self.report_progress(
                "Prediction Started",
                1,
            )
            bytes_io = io.BytesIO(self.image_file)
            pil_image = Image.open(bytes_io)
            # pylint: disable=no-member
            self.top_predictions = self.model.get_top_predictions(
                image=pil_image,
                report_progress_func=self.report_progress,
            )
            # pylint: enable=no-member

    @param.depends("top_predictions")
    def main_prediction_view(self, ):
        """A pretty string of the main prediction to output to the user"""
        if self.model and self.top_predictions:
            # pylint: disable=no-member
            main_prediction_string = self.model.to_main_prediction_string(
                self.top_predictions)
            # pylint: enable=no-member
            return pn.pane.Markdown(main_prediction_string)

        return pn.pane.Str("Not Available")

    @param.depends("top_predictions")
    def predictions_chart_view(self, ):
        """A view of a chart showing the top predictions and their probabilities"""
        if self.model and self.top_predictions:
            # pylint: disable=no-member
            chart = self.model.to_predictions_chart(self.top_predictions)
            # pylint: enable=no-member
            chart = chart.properties(
                height=200,
                width=400,
            )
            return pn.pane.Vega(chart)

        return pn.pane.Str("Not Available")

    @param.depends(
        "progress_value",
        "top_predictions",
    )
    def predictions_view(self, ):
        """A view showing the predictions or the progress of the predictions"""
        if self.progress_value:
            return pn.Column(
                pnx.SubHeader("Prediction"),
                pn.widgets.Progress(
                    value=self.progress_value,
                    width=200,
                ),
                pn.pane.Str(self.progress_message),
                sizing_mode="stretch_width",
            )
        if self.top_predictions:
            return pn.Column(
                pnx.SubHeader("Prediction"),
                self.main_prediction_view,
                pnx.SubHeader("Alternative Predictions"),
                self.predictions_chart_view,
                sizing_mode="stretch_width",
            )
        return pn.pane.HTML()
示例#13
0
    class ActivityMock(param.Parameterized):
        """Mock of Activity Class"""

        file = param.FileSelector()
示例#14
0
class MyParamFileSelector(param.Parameterized):
    single_file = param.FileSelector(path='*', precedence=0.5)
示例#15
0
class ChartStudio(param.Parameterized):

    # create param objects for all possible widgets in the app

    # import tab
    data_file = param.FileSelector(path='*.csv')
    use_layout_file = param.Boolean(default=False)
    layout_file = param.FileSelector(path='*.cslayout')

    # chart editor tab

    # type tab widgets
    chart_type = param.ObjectSelector(default="Scatter",
                                      objects=["Scatter", "Bar"])
    bar_mode = param.ObjectSelector(
        default="group", objects=["group", "stack", "relative", "overlay"])
    scatter_mode = param.ObjectSelector(
        default="lines+markers", objects=["lines+markers", "lines", "markers"])

    # trace tab widgets

    trace_to_edit = param.ObjectSelector(default=None, objects=None)

    # style tab widgets

    # general tab widgets
    chart_background_colour = param.Color(default='#ffffff')
    chart_background_opacity = param.Number(0.5, bounds=(0.0, 1.0))
    chart_text_font = param.ObjectSelector(
        default="Arial",
        objects=[
            "Arial", "Balto", "Courier New", "Droid Sans", "Droid Serif",
            "Droid Sans Mono", "Gravitas One", "Old Standard TT", "Open Sans",
            "Overpass", "PT Sans Narrow", "Raleway", "Times New Roman"
        ])
    chart_text_size = param.Integer(default=12)
    chart_text_colour = param.Color(default='#000000')
    chart_title = param.String(default='')

    plot_width = param.Integer(default=650)
    plot_height = param.Integer(default=450)
    top_margin = param.Integer(default=20)
    bottom_margin = param.Integer(default=80)
    left_margin = param.Integer(default=80)
    right_margin = param.Integer(default=80)

    # axes tab widgets

    axes_colour = param.Color(default='#000000')
    axes_thickness = param.Integer(default=1)
    x_title = param.String(default='x_title')
    y_title = param.String(default='y_title')
    y_autorange = param.Boolean(default=True)
    y_min = param.Number(default=0)
    y_max = param.Number(default=0)
    x_autorange = param.Boolean(default=True)
    x_min = param.Number(default=0)
    x_max = param.Number(default=0)
    y_grid_lines = param.Boolean(default=False)
    y_zeroline = param.Boolean(default=False)
    auto_x_tick_angle = param.Boolean(default=True)
    x_tick_angle = param.Number(default=0)

    # legend tab widgets

    auto_position_legend = param.Boolean(default=True)
    legend_x = param.Number(default=1)
    legend_y = param.Number(default=1)

    # annotate tab widgets

    # text annotations widgets
    show_footnote = param.Boolean(default=False)
    footnote_text = param.String(default='<i>Footnote:</i>')
    y_footnote = param.Number(default=-0.1)

    show_annotation_1 = param.Boolean(default=False)
    text_1 = param.String(default='Annotation 1')
    x_1 = param.Number(default=0)
    y_1 = param.Number(default=0)

    show_annotation_2 = param.Boolean(default=False)
    text_2 = param.String(default='Annotation 2')
    x_2 = param.Number(default=0)
    y_2 = param.Number(default=0)

    show_annotation_3 = param.Boolean(default=False)
    text_3 = param.String(default='Annotation 3')
    x_3 = param.Number(default=0)
    y_3 = param.Number(default=0)

    # shape annotation widgets

    show_shape_1 = param.Boolean(default=False)
    shape_1_type = param.ObjectSelector(default="rect",
                                        objects=["rect", "circle", "line"])
    shape_1_colour = param.Color(default='#0000ff')
    shape_1_opacity = param.Number(0.5, bounds=(0.0, 1.0))
    shape_1_line_style = param.ObjectSelector(
        default="solid",
        objects=["solid", "dot", "dash", "longdash", "dashdot", "longdashdot"])
    shape_1_line_width = param.Integer(default=0)
    x_min_1 = param.Number(default=0)
    x_max_1 = param.Number(default=0)
    y_min_1 = param.Number(default=0)
    y_max_1 = param.Number(default=0)

    show_shape_2 = param.Boolean(default=False)
    shape_2_type = param.ObjectSelector(default="rect",
                                        objects=["rect", "circle", "line"])
    shape_2_colour = param.Color(default='#00ff00')
    shape_2_opacity = param.Number(0.5, bounds=(0.0, 1.0))
    shape_2_line_style = param.ObjectSelector(
        default="solid",
        objects=["solid", "dot", "dash", "longdash", "dashdot", "longdashdot"])
    shape_2_line_width = param.Integer(default=0)
    x_min_2 = param.Number(default=0)
    x_max_2 = param.Number(default=0)
    y_min_2 = param.Number(default=0)
    y_max_2 = param.Number(default=0)

    show_shape_3 = param.Boolean(default=False)
    shape_3_type = param.ObjectSelector(default="rect",
                                        objects=["rect", "circle", "line"])
    shape_3_colour = param.Color(default='#ff0000')
    shape_3_opacity = param.Number(0.5, bounds=(0.0, 1.0))
    shape_3_line_style = param.ObjectSelector(
        default="solid",
        objects=["solid", "dot", "dash", "longdash", "dashdot", "longdashdot"])
    shape_3_line_width = param.Integer(default=0)
    x_min_3 = param.Number(default=0)
    x_max_3 = param.Number(default=0)
    y_min_3 = param.Number(default=0)
    y_max_3 = param.Number(default=0)

    # export chart tab
    export_to_file = param.String(default=r"Figure_1",
                                  doc="Declare name for exported plot file")
    png = param.Boolean(default=False)
    svg = param.Boolean(default=False)
    pdf = param.Boolean(default=False)
    html = param.Boolean(default=False)
    json = param.Boolean(default=False)
    cslayout = param.Boolean(default=False)
    export = param.Action(lambda x: x.param.trigger('export'))

    data = None
    figure = None
    update_plot = True

    #dataframe  = param.DataFrame(pd.util.testing.makeDataFrame().iloc[:3])

    @param.depends('data_file', watch=True)
    def process_file(self):
        self.data = pd.read_csv(self.data_file)
        self.data_cols = list(self.data.columns)
        self.xdata = self.data_cols[0]
        self.x_title = self.xdata
        self.trace_names = self.data_cols[1:]

    # method for reading in data if using the customised filebrowser panel widget
    #@param.depends('data_file', watch=True)
    #def process_file(self):
    #    data = StringIO(str(self.data_file,'utf-8'))
    #    self.data = pd.read_csv(data)
    #    self.data_cols = list(self.data.columns)
    #    self.xdata = self.data_cols[0]
    #    self.x_title = self.xdata
    #    self.trace_names = self.data_cols[1:]

    def show_data(self):
        return self.data

    @param.depends('layout_file', 'use_layout_file', watch=True)
    def import_cslayout(self):
        if self.use_layout_file == True:
            self.update_plot = False
            read_layout = pd.read_csv(self.layout_file)
            for attribute in read_layout.Attribute.unique():
                if attribute == read_layout.Attribute.unique()[-1]:
                    self.update_plot = True
                dtype = read_layout[read_layout.Attribute ==
                                    attribute].Type.values[0].replace(
                                        "<class '", '').replace("'>", '')
                value = read_layout[read_layout.Attribute ==
                                    attribute].Value.values[0]

                if dtype == 'int':
                    setattr(self, attribute, int(value))
                elif dtype == 'float':
                    setattr(self, attribute, float(value))
                elif dtype == 'bool':
                    if value == 'True':
                        setattr(self, attribute, True)
                    elif value == 'False':
                        setattr(self, attribute, False)
                elif dtype == 'str':
                    if str(value) == 'nan':
                        setattr(self, attribute, '')
                    else:
                        setattr(self, attribute, value)

    # function to export .cslayout file which contains param object names and values at time of export
    def export_cslayout(self):
        params = list(self.param.objects().keys())
        params_df = []
        # ignore name and export_plot params i.e. start at 1 and end at peniltimate param
        for i in range(len(params)):
            if params[i] not in [
                    'name', 'data_file', 'use_layout_file', 'layout_file',
                    'export_to_file', 'png', 'svg', 'pdf', 'html', 'json',
                    'cslayout', 'export', 'trace_to_edit'
            ]:
                params_df.append([
                    params[i],
                    getattr(self,
                            list(self.param.objects().keys())[i]),
                    type(getattr(self,
                                 list(self.param.objects().keys())[i]))
                ])
        # create dataframe and write out csv containing test layout parameters
        params_df = pd.DataFrame(params_df,
                                 columns=['Attribute', 'Value', 'Type'])
        params_df.to_csv(f'{self.export_to_file}.cslayout', index=False)

    @param.depends(
        'data_file', 'layout_file', 'use_layout_file', 'chart_type',
        'bar_mode', 'scatter_mode', 'chart_background_colour',
        'chart_background_opacity', 'chart_text_font', 'chart_text_size',
        'chart_text_colour', 'chart_title', 'plot_width', 'plot_height',
        'top_margin', 'bottom_margin', 'left_margin', 'right_margin',
        'axes_colour', 'axes_thickness', 'x_title', 'y_title', 'y_autorange',
        'y_min', 'y_max', 'x_autorange', 'x_min', 'x_max', 'y_grid_lines',
        'y_zeroline', 'auto_x_tick_angle', 'x_tick_angle',
        'auto_position_legend', 'legend_x', 'legend_y', 'show_footnote',
        'footnote_text', 'y_footnote', 'show_annotation_1', 'text_1', 'x_1',
        'y_1', 'show_annotation_2', 'text_2', 'x_2', 'y_2',
        'show_annotation_3', 'text_3', 'x_3', 'y_3', 'show_shape_1',
        'shape_1_type', 'shape_1_colour', 'shape_1_opacity',
        'shape_1_line_style', 'shape_1_line_width', 'x_min_1', 'x_max_1',
        'y_min_1', 'y_max_1', 'show_shape_2', 'shape_2_type', 'shape_2_colour',
        'shape_2_opacity', 'shape_2_line_style', 'shape_2_line_width',
        'x_min_2', 'x_max_2', 'y_min_2', 'y_max_2', 'show_shape_3',
        'shape_3_type', 'shape_3_colour', 'shape_3_opacity',
        'shape_3_line_style', 'shape_3_line_width', 'x_min_3', 'x_max_3',
        'y_min_3', 'y_max_3')  # all plot widgets I think
    def plot(self):
        if self.update_plot == True:

            colours = cycle(['#3b064d', '#8105d8', '#ed0cef', '#fe59d7'])

            # create traces
            data = []
            for i in range(0, len(self.trace_names)):

                colour = next(colours)

                if self.chart_type == 'Scatter':
                    data.append(
                        go.Scatter(x=self.data[self.xdata],
                                   y=self.data[self.trace_names[i]],
                                   name=self.trace_names[i],
                                   mode=self.scatter_mode,
                                   marker=dict(size=12,
                                               color=colour,
                                               opacity=0.5),
                                   line=dict(color=colour, width=2)))

                elif self.chart_type == 'Bar':
                    data.append(
                        go.Bar(x=self.data[self.xdata],
                               y=self.data[self.trace_names[i]],
                               name=self.trace_names[i],
                               marker=dict(color=colour,
                                           opacity=1.0,
                                           line=dict(width=0))))

            self.param.trace_to_edit.objects = self.trace_names
            self.trace_to_edit = self.trace_names[0]

            # set values for items with both tickboxes and value boxes
            if self.y_autorange == True:
                ymin = None
                ymax = None
            else:
                ymin = self.y_min
                ymax = self.y_max
            if self.x_autorange == True:
                xmin = None
                xmax = None
            else:
                xmin = self.x_min
                xmax = self.x_max
            if self.auto_x_tick_angle == True:
                xtickangle = None
            else:
                xtickangle = self.x_tick_angle
            if self.auto_position_legend == True:
                legx = None
                legy = None
            else:
                legx = self.legend_x
                legy = self.legend_y

            # set background rgba
            hex = app.chart_background_colour.lstrip('#')
            rgb = tuple(int(hex[i:i + 2], 16) for i in (0, 2, 4))
            alpha = self.chart_background_opacity
            bg_rgba = f'rgba({rgb[0]},{rgb[1]},{rgb[2]},{alpha})'

            # create annotations and shapes
            annotations = []

            if self.show_footnote == True:
                annotations.append(
                    dict(text=self.footnote_text,
                         font=dict(family=self.chart_text_font,
                                   size=self.chart_text_size - 2,
                                   color=self.chart_text_colour),
                         xanchor='right',
                         yref='paper',
                         xref='paper',
                         x=1.0,
                         y=self.y_footnote,
                         align='right',
                         showarrow=False))

            if self.show_annotation_1 == True:
                annotations.append(
                    dict(text=self.text_1,
                         font=dict(family=self.chart_text_font,
                                   size=self.chart_text_size,
                                   color=self.chart_text_colour),
                         x=self.x_1,
                         y=self.y_1,
                         showarrow=False))

            if self.show_annotation_2 == True:
                annotations.append(
                    dict(text=self.text_2,
                         font=dict(family=self.chart_text_font,
                                   size=self.chart_text_size,
                                   color=self.chart_text_colour),
                         x=self.x_2,
                         y=self.y_2,
                         showarrow=False))

            if self.show_annotation_3 == True:
                annotations.append(
                    dict(text=self.text_3,
                         font=dict(family=self.chart_text_font,
                                   size=self.chart_text_size,
                                   color=self.chart_text_colour),
                         x=self.x_3,
                         y=self.y_3,
                         showarrow=False))

            shapes = []

            if self.show_shape_1 == True:
                shapes.append(
                    dict(type=self.shape_1_type,
                         layer='below',
                         x0=self.x_min_1,
                         x1=self.x_max_1,
                         y0=self.y_min_1,
                         y1=self.y_max_1,
                         opacity=self.shape_1_opacity,
                         fillcolor=self.shape_1_colour,
                         line=dict(color=self.shape_1_colour,
                                   width=self.shape_1_line_width,
                                   dash=self.shape_1_line_style)))

            if self.show_shape_2 == True:
                shapes.append(
                    dict(type=self.shape_2_type,
                         layer='below',
                         x0=self.x_min_2,
                         x1=self.x_max_2,
                         y0=self.y_min_2,
                         y1=self.y_max_2,
                         line=dict(color=self.shape_2_colour,
                                   width=self.shape_2_line_width,
                                   dash=self.shape_2_line_style)))

            if self.show_shape_3 == True:
                shapes.append(
                    dict(type=self.shape_3_type,
                         layer='below',
                         x0=self.x_min_3,
                         x1=self.x_max_3,
                         y0=self.y_min_3,
                         y1=self.y_max_3,
                         opacity=self.shape_3_opacity,
                         fillcolor=self.shape_3_colour,
                         line=dict(color=self.shape_3_colour,
                                   width=self.shape_3_line_width,
                                   dash=self.shape_3_line_style)))
            # create layout

            layout = go.Layout(
                title=dict(text='<b>' + self.chart_title + '</b>',
                           font=dict(family=self.chart_text_font,
                                     size=self.chart_text_size + 4,
                                     color=self.chart_text_colour),
                           x=0.5),
                showlegend=True,
                hovermode='x',
                legend=dict(font=dict(family=self.chart_text_font,
                                      size=self.chart_text_size,
                                      color=self.chart_text_colour),
                            x=legx,
                            y=legy,
                            bgcolor='rgba(0,0,0,0)'),
                margin=dict(t=self.top_margin,
                            l=self.left_margin,
                            b=self.bottom_margin,
                            r=self.right_margin),
                width=self.plot_width,
                height=self.plot_height,
                font=dict(family=self.chart_text_font,
                          size=self.chart_text_size,
                          color=self.chart_text_colour),
                paper_bgcolor=bg_rgba,
                plot_bgcolor='rgba(0,0,0,0)',
                xaxis=dict(
                    visible=True,
                    color=self.axes_colour,
                    title=dict(text='<b>' + self.x_title + '</b>',
                               font=dict(family=self.chart_text_font,
                                         size=self.chart_text_size,
                                         color=self.chart_text_colour)),
                    range=[xmin, xmax],
                    ticks='outside',
                    ticklen=5,
                    tickwidth=self.axes_thickness,
                    tickcolor=self.axes_colour,
                    tickfont=dict(family=self.chart_text_font,
                                  size=self.chart_text_size,
                                  color=self.chart_text_colour),
                    tickangle=xtickangle,
                    showline=True,
                    linecolor=self.axes_colour,
                    linewidth=self.axes_thickness,
                    showgrid=False,
                    zeroline=False,
                ),
                yaxis=dict(visible=True,
                           color=self.axes_colour,
                           title=dict(text='<b>' + self.y_title + '</b>',
                                      font=dict(family=self.chart_text_font,
                                                size=self.chart_text_size,
                                                color=self.chart_text_colour)),
                           range=[ymin, ymax],
                           rangemode='tozero',
                           ticks='outside',
                           ticklen=5,
                           tickwidth=self.axes_thickness,
                           tickcolor=self.axes_colour,
                           tickfont=dict(family=self.chart_text_font,
                                         size=self.chart_text_size,
                                         color=self.chart_text_colour),
                           showline=True,
                           linecolor=self.axes_colour,
                           linewidth=self.axes_thickness,
                           showgrid=self.y_grid_lines,
                           gridcolor='grey',
                           zeroline=self.y_zeroline,
                           zerolinecolor='grey',
                           zerolinewidth=1),
                barmode=self.bar_mode,
                annotations=annotations,
                shapes=shapes)

            # create figure
            self.figure = go.Figure(data=data, layout=layout)

            return self.figure

    @param.depends('export', watch=True)
    def export_plots(self):
        if self.figure != None:
            if self.png == True:
                self.figure.write_image(self.export_to_file + ".png", scale=4)
            if self.svg == True:
                self.figure.write_image(self.export_to_file + ".svg")
            if self.pdf == True:
                self.figure.write_image(self.export_to_file + ".pdf")
            if self.json == True:
                self.figure.write_json(self.export_to_file + ".json")
            if self.html == True:
                self.figure.write_html(self.export_to_file + ".html")
            if self.cslayout == True:
                self.export_cslayout()
示例#16
0
class LumenDashboard(param.Parameterized):

    specfile = param.FileSelector()
    reloader = pn.widgets.Button(name='=', width=10)
    config = param.Parameter(precedence=-1)
    specDoc = param.Parameter(precedence=-1)
    dashBoard = param.Parameter(precedence=-1)
    sentinelHackCounter = 0
    loading = False
    indicator = centerContent(pn.indicators.LoadingSpinner(value=True))

    @classmethod
    def getinstancesBySessionId(cls, sessionId):
        instances = [
            inst for inst in instancesList if inst._session == sessionId
        ]
        if len(instances) >= 1:
            return instances
        return None

    @classmethod
    def clearInstancesForSession(cls, sessionId):
        instances = [
            inst for inst in instancesList if inst._session == sessionId
        ]
        for i in instances:
            instancesList.remove(i)

    @classmethod
    def clearInstances(cls):
        instancesList.clear()

    def __init__(self, **kwargs):

        super(LumenDashboard, self).__init__(**kwargs)
        boardId = kwargs['board']
        self.board = BoardEntity.objects.get(id=boardId)
        self._session = kwargs.get('sessionId') + str(boardId)
        self.josso_session_cookies = {
            'JOSSO_SESSIONID': kwargs.get('JOSSO_SESSIONID')
        }
        self.specDoc = self.createSpecFromData()

        instancesList.append(self)

    def initializerCallback(self):
        print(f"call initializerCallback; dashboard {self.dashBoard}")

        if not self.dashBoard and not self.loading:
            self.sentinelHackCounter += 1
            print(f"sentinel UP : {self.sentinelHackCounter}")
            # premier lancement avec affichage d'un spinner car le server renvoi  le document d'un seul tenant,
            # du coup le panel ne s'affiche pas tant que le Dashboard n'est pas totalement chargé!
            self.loading = True
            pn.state.add_periodic_callback(self.update, 700, count=1)

    def update(self):
        print(
            f"call update; dashboard {self.dashBoard}; sentinel {self.sentinelHackCounter}"
        )

        tic = time.clock()
        if not self.dashBoard:
            try:
                self.dashBoard = Dashboard(specification=self.specDoc.name)
                toc = time.clock()
                print(
                    f"Time to create the dashboard {self.dashBoard.name} :  {toc - tic}"
                )
            except (Exception) as e:
                self.dashBoard = pn.pane.HTML(
                    object=
                    f"<p>Erreur dans la préparation du dashboard : {e}</p>")
                print(e)
        else:
            self.dashBoard._yaml_file = self.specDoc.name
            self.dashBoard._load_specification(from_file=True)
            try:
                self.dashBoard._reload()
            except (Exception) as e:
                self.dashBoard = pn.pane.HTML(
                    object=
                    f"<p>Erreur dans la préparation du dashboard : {e}</p>")

        self.loading = False

    def createSpecFromData(self):

        if self.board.config:
            tic = time.clock()
            specification = self.board.config
            with open(
                    r'specYamlFile/temp/dashboard_{}.yml'.format(
                        self._session), 'w') as file:
                yaml.dump(specification, file)
            toc = time.clock()
            print(f"Time to create yaml {file.name} :  {toc - tic}")
            return file
        else:
            specification = self.createFakeYaml()
            with open(
                    r'specYamlFile/dashboard_fake_{}.yml'.format(
                        self._session), 'w') as file:
                yaml.dump(specification.__dict__, file)
            return file

    def createFakeYaml(self):
        path = BASE_DIR + '/vizApps/services/intake/'
        config = {
            'title': "Nouveau DashBoard",
            'layout': "grid",
            'ncols': 2,
            'template': 'material',
            'theme': 'dark'
        }
        targets = [
            {
                'title': 'Nouvelle Source',
                "source": {
                    'type': 'intake',
                    'filename': os.path.join(path, 'catalog.yml')
                },
                'views': [],
                'filters': []
            },
        ]
        specObj = SpecYamlCreator(config=config, targets=targets)
        return specObj

    @param.depends('specfile', watch=True)
    def uploadSpecFile(self):
        if self.specfile:
            with open(
                    r'specYamlFile/upload/dashboard_{}.yml'.format(
                        self._session), 'w') as file:
                spec = yaml.load(self.specfile)
                for i in [
                        v for source, v in spec.get('sources').items()
                        if v.get('type') == 'json'
                ]:
                    i['kwargs']['cookies'] = self.josso_session_cookies
                    break  # no need to iterate further
                yaml.dump(spec, file)
            self.specDoc = file
            self.dashBoard = None

    def updateConfig(self):
        print(f"call updateConfig; dashboard {self.dashBoard}")

        if self.specDoc.name is not None:
            with open(self.specDoc.name, 'r') as f:
                _yaml = yaml.load(f.read())
                _yaml['config'] = self.configMapping()

            with open(
                    r'specYamlFile/temp/new_dashboard_{}.yml'.format(
                        self._session), 'w') as f:
                yaml.dump(_yaml, f)
                self.specDoc = f

    def configMapping(self):
        config = {
            'title': self.config.title,
            'layout': self.config.layout.name,
            'ncols': self.config.ncols,
            'template': self.config.template.name,
            'theme': self.config.theme.name
        }
        return config

    @param.depends('config')
    def panel(self):
        layout = pn.Card(sizing_mode='stretch_width',
                         title="Parametres",
                         collapsed=True)
        layout.append(
            pn.Param(
                self.param,
                widgets={
                    # 'logo': pn.widgets.FileInput(accept='.jpg,.png,.ico,.gif',name="Logo"),
                    'specfile':
                    pn.widgets.FileInput(accept='.yaml,.yml',
                                         name="Specification File")
                },
                show_name=False,
                expand_button=False,
                expand=False,
                sizing_mode="stretch_width"), )
        if self.config:
            layout.append(
                pn.Param(
                    self.config.param,
                    show_name=False,
                    expand_button=False,
                    expand=False,
                    sizing_mode="stretch_width",
                ))
        return layout

    @param.depends('dashBoard')
    def main(self):
        print(
            f"call main; dashboard {self.dashBoard}, sentinel {self.sentinelHackCounter}"
        )
        if isinstance(self.dashBoard, Dashboard):
            self.config = self.dashBoard.config
            layout = pn.Column(self.dashBoard._main,
                               sizing_mode='stretch_both',
                               margin=10,
                               width_policy='max',
                               height_policy='max')
            return layout
        elif self.dashBoard:
            return self.dashBoard
        else:
            return self.indicator

    @param.depends('dashBoard')
    def header(self):
        if isinstance(self.dashBoard, Dashboard):
            header = self.dashBoard._header
            return header

    @param.depends('dashBoard')
    def sidebar(self):
        if isinstance(self.dashBoard, Dashboard):
            sidebar = self.dashBoard._sidebar
            return sidebar

    @param.depends('dashBoard')
    def modal(self):
        if isinstance(self.dashBoard, Dashboard):
            modal = self.dashBoard._modal
            return modal

    @param.depends('dashBoard')
    def busyIndicator(self):
        spinner = pn.indicators.LoadingSpinner(width=40, height=40)
        pn.state.sync_busy(spinner)
        bi = pn.Row(spinner)
        return bi