Пример #1
0
def divide_images_interface():
    
    parameters = []
    
    print('\x1b[1m'+"Input directory")
    input_dir = FileChooser('./datasets')
    display(input_dir)
    print('\x1b[1m'+"Output directory")
    output_dir = FileChooser('./datasets')
    display(output_dir)

    label_layout = Layout(width='100px',height='30px')

    width_divider = HBox([Label('Width divider:', layout=label_layout), widgets.IntText(
        value=2, description='', disabled=False)])
    display(width_divider)
    height_divider = HBox([Label('Height divider:', layout=label_layout), widgets.IntText(
        value=2, description='', disabled=False)])
    display(height_divider)
    
    parameters.append(input_dir)
    parameters.append(output_dir)
    parameters.append(width_divider)
    parameters.append(height_divider)
    return parameters
Пример #2
0
    def __init__(self, _type: str = "shape"):

        self.type = _type

        if _type == 'shape':
            accept = '*.shp'
        elif _type == 'json':
            accept = '*.json'

        self.wfu_text_file = FileChooser(filter_pattern=accept, multiple=False)

        self.wdd_fid_attrib = Dropdown(placeholder='Fid Attribute',
                                       description='Fid Attribute:',
                                       disabled=False)

        self.wt_ext_fid_list = FileChooser(
            placeholder='External Fid List (Optional)',
            description='External Fid List:',
            disabled=False)

        def on_upload_change():

            # load the geodataframe and get the columns values
            gdf = gpd.read_file(self.wfu_text_file.selected)

            # get a list of columns in the geodataframe
            cols = list(gdf.columns)

            self.wdd_fid_attrib.options = cols

        self.wfu_text_file.register_callback(on_upload_change)

        super().__init__(
            [self.wfu_text_file, self.wdd_fid_attrib, self.wt_ext_fid_list])
Пример #3
0
class source_from_txt(VBox):
    def __init__(self):
        self.wt_text_file = FileChooser(filter_pattern='*.txt', multiple=False)

        super().__init__([self.wt_text_file])

    def dump(self) -> dict:
        out_dict = {}

        out_dict["type"] = "txt"

        if self.wt_text_file.selected is not None:
            out_dict["fid_list_file"] = self.wt_text_file.selected
        else:
            if self.wt_text_file.default is not None:
                out_dict["fid_list_file"] = self.wt_text_file.default

        return out_dict

    def initialize(self, options: dict):

        if "fid_list_file" in options:
            try:
                full_path = options["fid_list_file"].replace("\\", "/")

                if os.path.isfile(full_path):
                    base_path = full_path[:full_path.rfind("/") + 1]
                    filename = full_path[full_path.rfind("/") + 1:]
                    self.wt_text_file.reset(path=base_path, filename=filename)

            except:
                print("Unable to set path")
Пример #4
0
def extract_channels_interface():
    
    parameters = []
    
    print('\x1b[1m'+"Input directory")
    input_dir = FileChooser('./datasets')
    display(input_dir)
    print('\x1b[1m'+"Output directory")
    output_dir = FileChooser('./datasets')
    display(output_dir)
    channel_1 = widgets.Checkbox(value=True, description='Channel 1',disabled=False)
    display(channel_1)
    channel_2 = widgets.Checkbox(value=False, description='Channel 2',disabled=False)
    display(channel_2)
    channel_3 = widgets.Checkbox(value=False, description='Channel 3',disabled=False)
    display(channel_3)
    channel_4 = widgets.Checkbox(value=False, description='Channel 4',disabled=False)
    display(channel_4)
    channel_5 = widgets.Checkbox(value=False, description='Channel 5',disabled=False)
    display(channel_5)
    channel_6 = widgets.Checkbox(value=False, description='Channel 6',disabled=False)
    display(channel_6)
    channel_7 = widgets.Checkbox(value=False, description='Channel 7',disabled=False)
    display(channel_7)

    parameters.append(input_dir)
    parameters.append(output_dir)
    parameters.append(channel_1)
    parameters.append(channel_2)
    parameters.append(channel_3)
    parameters.append(channel_4)
    parameters.append(channel_5)
    parameters.append(channel_6)
    parameters.append(channel_7)
    return parameters
Пример #5
0
def initUI(DEFAULTS):
    """
    Main layout.

    - Set working directory.
    - Commands tabs.
    - Output.
    """

    layout = inputBox(layout={"width": "850px", "border": "2px solid black"})

    # widgets
    cd = FileChooser(".", title="Select working directory")
    cd.show_only_dirs = True

    out = widgets.Output()

    # layout
    layout.add_child("cd", cd)
    layout.add_child("out", out)
    # callbacks
    cd.register_callback(
        partial(
            cdCmd,
            DEFAULTS=DEFAULTS,
            layout=layout,
        )
    )
    return layout
Пример #6
0
def running_parameters_interface(nb_trainings):
    input_dir = np.zeros([nb_trainings], FileChooser)
    input_classifier = np.zeros([nb_trainings], FileChooser)
    output_dir = np.zeros([nb_trainings], FileChooser)
    image_size = np.zeros([nb_trainings], HBox)
    
    parameters = []
    for i in range(nb_trainings):
        print('\x1b[1m'+"Input directory")
        input_dir[i] = FileChooser('./datasets')
        display(input_dir[i])
        print('\x1b[1m'+"Input classifier")
        input_classifier[i] = FileChooser('./trainedClassifiers')
        display(input_classifier[i])
        print('\x1b[1m'+"Output directory")
        output_dir[i] = FileChooser('./datasets')
        display(output_dir[i])

        label_layout = Layout(width='215px',height='30px')

        image_size[i] = HBox([Label('Image size as seen by the network:', layout=label_layout), widgets.IntText(
            value=1024, description='', disabled=False)])
        display(image_size[i])

    parameters.append(input_dir)
    parameters.append(input_classifier)
    parameters.append(output_dir)
    parameters.append(image_size)
    
    return parameters  
Пример #7
0
    def _widget_upload_EM_button(self):
       """Import EM dataset """

       vbox_doc = self._widget_upload_EM_doc()

       #self.EM_upload = widgets.FileUpload(
       #        accept='.csv',  # Accepted file extension
       #        multiple=False  # True to accept multiple files upload else False
       #   )

       self.EM_upload = FileChooser(use_dir_icons=True)
       self.EM_upload.filter_pattern = '*.csv'
       self.EM_upload.title = '<b>EM_upload</b>'

       vbox = widgets.VBox([vbox_doc,self.EM_upload])

       display(vbox)

       def on_upload_change(change):
            #for name, file_info in self.EM_upload.value.items():
            name = self.EM_upload.selected

            df = pd.read_csv(name)
            df.head() # see how the header are formatted
            xx=df.to_xarray()
            print(xx)
       #self.EM_upload.observe(on_upload_change, names='_counter')
       self.EM_upload.register_callback(on_upload_change)


       return vbox
Пример #8
0
class netcdf_export(object):

    def __init__(self):
        self._widget_upload_EM_button()

    def _widgets_EM_doc():
        title = widgets.HTML('''
            <h3> EM metadata </h3>
            <hr style="height:1px;border-width:0;color:black;background-color:gray">
            <b> Minimum required metadata. </b>
            Please refer to the <a href="https://agrogeophy.github.io/catalog/schema_documentation.html#table-em-metadata">online EM metadata documentation </a>
             ''')
        vbox = widgets.VBox([title])
        return vbox

    def _widget_upload_EM_doc(self):
        """upload EM file and parse metadata
        """
        title = widgets.HTML(
        '''<h5>Emagpy importer<h5/>
        <hr style="height:1px;border-width:0;color:black;background-color:gray">
        ''')
        text = widgets.HTML('''
        Infer all the EM metadata from the EM uploaded. Please refer to the <a href="https://gitlab.com/hkex/emagpy"> Emagpy online doc</a>
        ''')

        vbox = widgets.VBox([title, text])
        return vbox

    def _widget_upload_EM_button(self):
       """Import EM dataset """

       vbox_doc = self._widget_upload_EM_doc()

       #self.EM_upload = widgets.FileUpload(
       #        accept='.csv',  # Accepted file extension
       #        multiple=False  # True to accept multiple files upload else False
       #   )

       self.EM_upload = FileChooser(use_dir_icons=True)
       self.EM_upload.filter_pattern = '*.csv'
       self.EM_upload.title = '<b>EM_upload</b>'

       vbox = widgets.VBox([vbox_doc,self.EM_upload])

       display(vbox)

       def on_upload_change(change):
            #for name, file_info in self.EM_upload.value.items():
            name = self.EM_upload.selected

            df = pd.read_csv(name)
            df.head() # see how the header are formatted
            xx=df.to_xarray()
            print(xx)
       #self.EM_upload.observe(on_upload_change, names='_counter')
       self.EM_upload.register_callback(on_upload_change)


       return vbox
Пример #9
0
    def __init__(self):

        self.wt_text_file = FileChooser(filter_pattern='*.txt', multiple=False)

        self.wc_connection = connection_widget()

        super().__init__([self.wt_text_file, self.wc_connection])
Пример #10
0
def channelUI(C, channelTabs, useOfftarget, DEFAULTS):
    C = get_value(C)
    currentC = len(channelTabs.children)
    for c in range(max(currentC, C)):
        if c < C and c < currentC:
            continue
        elif c < C and c >= currentC:
            if len(DEFAULTS["channels"]) < c + 1:
                DEFAULTS["channels"].append(defaultdict(lambda: None))
            layout = inputBox()
            layout.add_child(
                "name",
                widgets.Text(
                    value=DEFAULTS["channels"][c]["name"],
                    description="Channel name",
                    style={"description_width": "initial"},
                ),
            )
            layout.add_child(
                "glimpse_folder", FileChooser(".", title="Header/glimpse folder")
            )
            if DEFAULTS["channels"][c]["glimpse-folder"] is not None:
                layout["glimpse_folder"].reset(
                    path=Path(DEFAULTS["channels"][c]["glimpse-folder"])
                )
                layout["glimpse_folder"]._apply_selection()
            layout.add_child("driftlist", FileChooser(".", title="Driftlist file"))
            if DEFAULTS["channels"][c]["driftlist"] is not None:
                layout["driftlist"].reset(
                    path=Path(DEFAULTS["channels"][c]["driftlist"]).parent,
                    filename=Path(DEFAULTS["channels"][c]["driftlist"]).name,
                )
                layout["driftlist"]._apply_selection()
            layout.add_child(
                "ontarget_aoiinfo",
                FileChooser(".", title="Target molecule locations file"),
            )
            if DEFAULTS["channels"][c]["ontarget-aoiinfo"] is not None:
                layout["ontarget_aoiinfo"].reset(
                    path=Path(DEFAULTS["channels"][c]["ontarget-aoiinfo"]).parent,
                    filename=Path(DEFAULTS["channels"][c]["ontarget-aoiinfo"]).name,
                )
                layout["ontarget_aoiinfo"]._apply_selection()
            layout.add_child(
                "offtarget_aoiinfo",
                FileChooser(".", title="Off-target control locations file"),
                hide=not useOfftarget.value,
            )
            if DEFAULTS["channels"][c]["offtarget-aoiinfo"] is not None:
                layout["offtarget_aoiinfo"].reset(
                    path=Path(DEFAULTS["channels"][c]["offtarget-aoiinfo"]).parent,
                    filename=Path(DEFAULTS["channels"][c]["offtarget-aoiinfo"]).name,
                )
                layout["offtarget_aoiinfo"]._apply_selection()
            channelTabs.children = channelTabs.children + (layout,)
        channelTabs.set_title(c, f"Channel #{c}")
    channelTabs.children = channelTabs.children[:C]
Пример #11
0
    def __init__(self):
        self.filename = None

        def file_change(chooser):
            chooser.title = '<b>Selected file</b>'
            self.filename = chooser.selected

        self.fc = FileChooser(str(Path.home()))
        self.fc.show_hidden = False
        self.fc.use_dir_icons = True
        self.fc.filter_pattern = "*.nc"
        self.fc.title = '<b>Select NetCDF Dataset</b>'
        self.fc.register_callback(file_change)
Пример #12
0
    def _widget_upload_EM_button(self):
        """Import EM dataset """

        vbox_doc = self._widget_upload_EM_doc()

        #self.EM_upload = widgets.FileUpload(
        #        accept='.csv',  # Accepted file extension
        #        multiple=False  # True to accept multiple files upload else False
        #   )

        self.EM_upload = FileChooser(use_dir_icons=True)
        self.EM_upload.filter_pattern = '*.csv'
        self.EM_upload.title = '<b>EM_upload</b>'
        #        accept='.csv',  # Accepted file extension
        #        multiple=False  # True to accept multiple files upload else False
        #    )

        vbox = widgets.VBox([vbox_doc, self.EM_upload])

        def on_upload_change(change):
            #for name, file_info in self.EM_upload.value.items():
            name = self.EM_upload.selected
            self._add_to_Zip(name,
                             target_dir=self.metadata['method'],
                             level_dir='Emagpy_import')
            self._update_widget_log(
                'EM file imported for automatic metadata extraction')
            self.metadata['em_filename_metadata'] = name

            k = Problem()  # this create the main object
            k.createSurvey(name)  # this import the data
            k.invert(
                forwardModel='CS'
            )  # specify the forward model (here the Cumulative Sensitivty of McNeil1980)
            k.showResults()  # display the section

            k.coils
            k.freqs
            k.hx
            k.cspacing
            self.metadata['coil_spacing'] = ';'.join(map(str, k.cspacing))

            self._update_widget_export()
            #self._parse_json() # parse to metadata for export
            self._update_fields_values(
                ['coil_spacing'])  # parse to widgets to replace initial valus

        #self.EM_upload.observe(on_upload_change, names='_counter')
        self.EM_upload.register_callback(on_upload_change)

        return vbox
Пример #13
0
    def __init__(self, parent = None):
        """
        Summary:
            Object constructor.
        
        Arguments:
            None
            
        Returns:
            Nothing.
        """
        super().__init__(CsvDataReaderWidget._type, parent)
        
        
        # Path name
        wfc_path = FileChooser(
                placeholder='path',
                description='path:',
                disabled=False
            )

        wdd_fid_attrib = Dropdown(
            placeholder='fid attribute',
            description='fid attribute:',
            disabled=False
        )
        
        wdd_date_attrib = Dropdown(
            value="",
            options=[""],
            placeholder='date attribute',
            description='date attribute:',
            disabled=False
        )
        
        def on_upload_change():
            # load the dataframe and get the columns values
            df = pd.read_csv(wfc_path.selected)
        
            # get a list of columns in the geodataframe
            cols = list(df.columns)
        
            wdd_fid_attrib.options = cols
            wdd_date_attrib.options = ["", *cols]

        wfc_path.register_callback(on_upload_change) 
        
        # Add specific options
        self.add_options([wfc_path, wdd_fid_attrib, wdd_date_attrib])
Пример #14
0
 def __init__(self,
              function_arg_name: str,
              default_directory: str = os.getcwd(),
              validator: Callable[[Any], Any] = lambda value: value,
              file_filter: str = '',
              show_only_dirs: bool = False):
     """
     :param function_arg_name: Name of function argument this
         input corresponds to.
     :default_directory: Directory to start browseing in.
     :validator: Validator function.
     :file_filter: String to use to filter displayed files.
         Will only display files which contain the filter string
         string as a substring.
     :param show_only_dirs: If True will only display
         and allow selection of directories.
     """
     from ipyfilechooser import FileChooser
     self._widget = FileChooser(default_directory,
                                select_desc='Select file',
                                select_default=True,
                                change_desc='Select file',
                                file_filter=f'*{file_filter}*',
                                show_only_dirs=show_only_dirs)
     self._widget.use_dir_icons = True
     self._param_name = function_arg_name
     self._validator = validator
Пример #15
0
def TensorBoard_interface():
    
    print('\x1b[1m'+"Model location")
    classifier_directory = FileChooser('./trainedClassifiers')
    display(classifier_directory)
    
    return classifier_directory
Пример #16
0
    def load_aoi(self):
        fc = FileChooser(".")
        fc.title = "<b>Select an input geometry file</b>"

        button = widgets.Button(description="Load!")

        def load_aoi(fc):
            assert fc.selected, "Please select a file."
            file_path = Path(fc.selected).resolve()
            assert file_path.is_file(
            ), "Please select a file, not a directory."
            aoi = up42.read_vector_file(file_path, as_dataframe=True)
            display(aoi)
            self.aoi = aoi
            aoi.plot()
            print(f"Saved {aoi}")

        self.process_template([fc], button, load_aoi, fc=fc)
Пример #17
0
def combine_instance_segmentations_interface():
    
    parameters = []
    
    print('\x1b[1m'+"Input directory for Mask R-CNN segmentations")
    input_dir1 = FileChooser('./datasets')
    display(input_dir1)
    print('\x1b[1m'+"Input directory for U-Net segmentations")
    input_dir2 = FileChooser('./datasets')
    display(input_dir2)
    print('\x1b[1m'+"Output directory")
    output_dir = FileChooser('./datasets')
    display(output_dir)

    parameters.append(input_dir1)
    parameters.append(input_dir2)
    parameters.append(output_dir)
    return parameters
Пример #18
0
def ml_tool():

    #Read Data
    data_dir = os.path.abspath('./data')

    fc = FileChooser(data_dir)
    fc.use_dir_icons = True
    fc.filter_pattern = ['*.shp', '*.geojson', '*.csv']
    long_text = widgets.Text(description="Longitude")
    lat_text = widgets.Text(description='Latitude')
    header_text = widgets.Text(value='True', desciption='Header')
    csv_area = widgets.HBox([long_text, lat_text, header_text])

    button = widgets.Button(description='Read Data')

    def button_click(change):
        if fc.selected[-3:] != 'csv':
            m = folium.Map(zoom_start=15)
            geo = []

            if fc.selected is not None:
                if fc.selected.endswith(".shp"):
                    geo = mygeopackage.Geo(fc.selected,
                                           request=False,
                                           file_type='shp')
                    #geo.show(map=m)
                elif fc.selected.endswith(".geojson"):
                    geo = mygeopackage.Geo(fc.selected, request=False)
                    #geo.show(map=m)
            analysis(m, geo)
            #display(m)
        else:
            if header_text.value == 'True':
                m = mygeopackage.Map(in_csv=fc.selected,
                                     x=long_text.value,
                                     y=lat_text.value,
                                     header=True)
                display(m)

    button.on_click(button_click)
    filechooser_widget = widgets.VBox([fc, csv_area, button])
    display(filechooser_widget)
Пример #19
0
class SingleFilePicker(FilePickerInterface):
    def __init__(self):
        self.filename = None

        def file_change(chooser):
            chooser.title = '<b>Selected file</b>'
            self.filename = chooser.selected

        self.fc = FileChooser(str(Path.home()))
        self.fc.show_hidden = False
        self.fc.use_dir_icons = True
        self.fc.filter_pattern = "*.nc"
        self.fc.title = '<b>Select NetCDF Dataset</b>'
        self.fc.register_callback(file_change)
        #self.fc.reset(path='..', filename='era5_19120612.nc')

    def get_file_paths(self) -> list:
        return [self.filename]

    def get_widget(self) -> FileChooser:
        return self.fc
Пример #20
0
    def __init__(self, a_map: Map, path: str = ""):
        """Constructor.
        
        :param a_map: The map for which to record events.
        :param path: The path of a JSON records file containing a map recording.
        """
        self.recording = []
        if os.path.exists(path):
            with open(path) as f:
                self.recording = [json.loads(line) for line in f.read().splitlines()]
        self.a_map = a_map

        layout = Layout(width="30px")
        self.start = Button(tooltip="Start/Stop", icon="video-camera", layout=layout)
        self.start.on_click(self.toggle_rec)
        disabled = len(self.recording) == 0
        self.play = Button(tooltip="Play", icon="play", disabled=disabled, layout=layout)
        self.play.on_click(self.play_rec)
        self.save = Button(tooltip="Save", icon="floppy-o", disabled=disabled, layout=layout)
        self.save.on_click(self.save_rec)
        self.fc = FileChooser(os.getcwd())
        self.widget = HBox([self.start, self.play, self.save])
Пример #21
0
    def _widget_upload_figures_type1(self):
        """upload EM file and parse metadata
        """
        title = widgets.HTML('''<h5>Upload figures type 1 <h5/>
        <hr style="height:1px;border-width:0;color:black;background-color:gray">
        ''')
        self.fig1 = FileChooser(use_dir_icons=True)
        self.fig1.title = '<b>figure type 1</b>'

        vbox = widgets.VBox([title, self.fig1])

        def on_upload_change(change):
            #for name, file_info in self.EM_upload.value.items():
            name = self.fig1.selected
            print(name)
            self._add_to_Exdir(name, target_dir='fig', level_dir='type1')
            #self._add_file_to_Expipe(name, target_dir='fig', level_dir='type1')
            #self._add_to_Zip(name, target_dir='fig', level_dir='type1')

        self.fig1.register_callback(on_upload_change)

        return vbox
Пример #22
0
    def ts_btn_click(self, b):
        ts_btn.disabled = True
        sd_btn.disabled = True

        if ask_root_dir:
            fc: FileChooser = FileChooser(str(Path.home()))
            fc.show_only_dirs = True
            fc.title = '<b>Select root directory</b>'

            # root_dir_text: widgets.Text = widgets.Text(
            #     value=str(Path.home()),
            #     placeholder="e.g. /home/2020/01/ecmwf_era5_21020900.nc -> root dir: /home",
            #     description='Root directory:',
            #     disabled=False,
            #     style={'description_width': 'initial'},
            #     layout=widgets.Layout(width='50%')
            # )
            lbl_info = widgets.Label(
                value=
                'e.g. /home/2020/01/ecmwf_era5_21020900.nc -> root dir: /home')

            ts_start_btn = widgets.Button(
                description="Confim",
                style={'description_width': 'initial'},
                button_style='success')

            root_dir_box = widgets.HBox([fc, lbl_info, ts_start_btn],
                                        layout=widgets.Layout(
                                            display='flex',
                                            flex_flow='column',
                                            align_items='flex-start'))

            def start(b: widgets.Button):
                root_dir = fc.selected_path
                if root_dir is not None:
                    view = TimeseriesView(root_dir=root_dir)
                    root_dir_box.layout.visible = 'hidden'
                    view.show()
                else:
                    display(
                        HTML("<script>alert('{}');</script>".format(
                            "No root directory selected")))

            ts_start_btn.on_click(start)
            display(root_dir_box)

        else:
            view = TimeseriesView()
            view.show()
Пример #23
0
    def _load_project_button(self):
        # load a project (just need to set the path)
        title = widgets.HTML('''
            <h4> Load project </h4>
          ''')

        self.pipe_prj_upload = FileChooser(use_dir_icons=True)
        self.pipe_prj_upload.filter_pattern = '*.dir'
        self.pipe_prj_upload.title = '<b>Dir of the project</b>'

        #out = widgets.Output()

        #def on_button_clicked(bmap):
        #with out:
        #add_expipe_action()

        #action_button.on_click(on_button_clicked)

        vbox = widgets.VBox([title, self.pipe_prj_upload])

        return vbox
Пример #24
0
    def _init_widget(self):

        self.model_select = Dropdown(options=sasmodels.core.list_models())
        self.model_select.value = 'sphere'
        self.model_select.observe(self._update_model, names='value')

        self.qmin = Text(description='qmin', value='0.001')
        self.qmax = Text(description='qmax', value='0.5')
        self.numq = Text(description='numq', value='150')
        self.qrange = VBox([self.qmin, self.qmax, self.numq])
        for i in (self.qmin, self.qmax, self.numq):
            i.on_submit(self._update_model)

        self.file_chooser = FileChooser()
        self.load_data = Button(description='Load Data')
        self.load_data.on_click(self._load_data)

        self.parameters = VBox([])
        self.parameters_pd = VBox([])
        self.docs = Output()

        self.tabs = Tab([
            self.parameters, self.parameters_pd, self.qrange,
            VBox([self.file_chooser, self.load_data]), self.docs
        ])
        self.tabs.set_title(0, 'Model Params')
        self.tabs.set_title(1, 'Dispersity')
        self.tabs.set_title(2, 'Q-Range')
        self.tabs.set_title(3, 'Load Data')
        self.tabs.set_title(4, 'Documentation')
        self.tabs.layout = {'height': '300px', 'width': '600px'}

        self.output = Output()

        widget = VBox(
            [self.model_select, self.tabs, self.output, debug_output])
        return widget
Пример #25
0
}

dd['bandwidth'] = wdg.SelectionSlider(description='Bandwidth:',
                                      options=Bdwt_val.values(),
                                      continuous_update=False)

dd['bandwidth'].add_class("osa_bandwidth")
dd['clr'] = wdg.Button(
    description='Clear Trace',
    button_style='info',
    tooltip='Click me',
)
dd['clr'].add_class("osa_clear")
dd['save'] = wdg.Button(description='Save Spectra', button_style='info')
dd['save'].add_class("osa_save")
dd['picker'] = FileChooser('./../')
dd['picker'].use_dir_icons = True
dd['picker'].rows = 5
dd['picker'].width = 200
ui = _dic2struct(dd)

# ----------------------------------
# -- Worker for scanning
# ----------------------------------
run_thread = True


def worker(f, instr):
    while run_thread:
        trace = instr.trace
        #         x = np.linspace(600, 1700, 50001)
Пример #26
0
    def __init__(self, signal_components: dict):
        """
        Summary:
            Object constructor.
        
        Arguments:
            signal_components - dictionary with the signal components.
            
        Returns:
            Nothing.
        """
        self.signal_components = signal_components
        self.count = 0

        # List of marker detectors
        self.marker_detectors = []

        self.wt_marker_detectors = Tab()

        self.wb_add = Button(description='Add', disabled=False, icon='Add')

        supported_types = [
            x._type for x in base_marker_detector_widget.__subclasses__()
        ]
        self.wdd_types = Dropdown(options=supported_types, disabled=False)

        self.wb_remove = Button(description='Remove',
                                disabled=False,
                                icon='Remove')

        @self.wb_add.on_click
        def wb_add_on_click(b):

            new_w = None

            md_type = self.wdd_types.value

            if md_type in supported_types:
                ind = supported_types.index(md_type)
                new_w = base_marker_detector_widget.__subclasses__()[ind](
                    self.signal_components)

            if new_w is not None:
                self.marker_detectors.append(new_w)
                self.wt_marker_detectors.children = self.marker_detectors
                self.wt_marker_detectors.set_title(self.count, new_w.type)
                self.count += 1

        @self.wb_remove.on_click
        def wd_remove_on_click(b):

            if len(self.marker_detectors):
                self.marker_detectors.pop()
                self.count -= 1

            self.wt_marker_detectors.children = self.marker_detectors

        self.wb_save = Button(description='Save', disabled=False, icon='save')

        @self.wb_save.on_click
        def wb_save_on_click(b):

            # Create the output element in the JSON file
            _dict = self.dump()

            key = list(_dict.keys())[0]
            value = _dict[key]

            config.set_value(key, value)

            # Add an empty key for the marker-aggregator (to be dealt with
            # in a second phase)
            if config.get_value("marker-aggregator") is None:
                config.set_value("marker-aggregator", [{}])

                # Add a default marker-sink (to be dealt with
                # in a second phase)
                config.set_value("marker-sink", [{
                    "output_file": "./marker_output.csv",
                    "include_header": True
                }])
            else:
                config.set_value("marker-sink", [{
                    "output_file": "./marker_output.csv",
                    "include_header": True
                }, {
                    "output_file": "./agg_marker_output.csv",
                    "include_header": True
                }])

        self.wb_load = Button(description='Load', disabled=False, icon='load')

        wfc_options = FileChooser(placeholder='Option file',
                                  description='Option file:',
                                  disabled=False)

        self.whb_load = HBox([self.wb_load, wfc_options])

        @self.wb_load.on_click
        def wb_load_on_click(b):

            if wfc_options.selected is not None:
                optionFile = open(wfc_options.selected)
                options = json.load(optionFile)

                self.initialize(options)

        super().__init__([
            self.wt_marker_detectors,
            HBox([self.wb_add, self.wdd_types]), self.wb_remove, self.wb_save,
            self.whb_load
        ])
Пример #27
0
    def __init__(self, signal_components: dict):

        # Tab counter
        self.tab_counter = 0

        self.signal_components = signal_components

        # List of processing lines
        self.pro_lines = [processing_line(signal_components, self)]

        self.wt_pro_lines = Tab(self.pro_lines)
        self.set_title(self.tab_counter, f"Pro Line {self.tab_counter}")
        self.tab_counter += 1

        # Add and remove buttons
        self.wb_add = Button(description='Add', disabled=False, icon='Add')

        self.wb_remove = Button(description='Remove',
                                disabled=False,
                                icon='Remove')

        @self.wb_add.on_click
        def wb_add_on_click(b):
            # Append a new processing line tab
            self.pro_lines.append(processing_line({**signal_components, \
                                                   **(self.get_signal_components())},
                                                  self))

            self.wt_pro_lines.children = self.pro_lines
            self.set_title(self.tab_counter, f"Pro Line {self.tab_counter}")
            self.tab_counter += 1

        @self.wb_remove.on_click
        def wd_remove_on_click(b):

            if len(self.pro_lines) > 1:
                self.pro_lines.pop()
                self.tab_counter -= 1
            else:
                # Empty tab
                self.pro_lines = [processing_line(signal_components)]

            self.wt_pro_lines.children = self.pro_lines

        self.wb_save = Button(description='Save', disabled=False, icon='save')

        @self.wb_save.on_click
        def wb_save_on_click(b):

            # Create the output element in the JSON file
            _dict = self.dump()

            key = list(_dict.keys())[0]
            value = _dict[key]

            config.set_value(key, value)

        self.wb_load = Button(description='Load', disabled=False, icon='load')

        wfc_options = FileChooser(placeholder='Option file',
                                  description='Option file:',
                                  disabled=False)

        self.whb_load = HBox([self.wb_load, wfc_options])

        @self.wb_load.on_click
        def wb_load_on_click(b):

            if wfc_options.selected is not None:
                optionFile = open(wfc_options.selected)
                options = json.load(optionFile)

                self.initialize(options)

        super().__init__([self.wt_pro_lines, HBox([self.wb_add, self.wb_remove]),\
                          self.wb_save, self.whb_load])
Пример #28
0
    def __init__(self, verbose=False):

        self.quantifier = Quantifier(verbose)

        self.home = None
        self.run_dir = None

        # Initialize child logger for class instances
        self.logger = logging.getLogger("RMNQ_logger.ui.notebook.Rnb")
        # fh = logging.FileHandler(f"{self.run_name}.log")
        handler = logging.StreamHandler()
        if verbose:
            handler.setLevel(logging.DEBUG)
        else:
            handler.setLevel(logging.INFO)
        formatter = logging.Formatter(
            '%(asctime)s - %(name)s - %(levelname)s - %(message)s',
            "%Y-%m-%d %H:%M:%S")
        handler.setFormatter(formatter)
        if not self.logger.hasHandlers():
            self.logger.addHandler(handler)

        widgetstyle = {'description_width': 'initial'}

        self.display = False
        self.fmt = False

        self.upload_datafile_btn = FileChooser(os.getcwd())
        self.upload_datafile_btn.title = "Select Datafile"
        self.upload_database_btn = FileChooser(os.getcwd())
        self.upload_database_btn.title = "Select Database"
        self.upload_template_btn = FileChooser(os.getcwd())
        self.upload_template_btn.title = "Select Template"

        self.strd_btn = widgets.Text(value='',
                                     description='Strd concentration:',
                                     disabled=True,
                                     style=widgetstyle)

        self.dilution_text = widgets.Text(value='',
                                          description='Dilution factor:',
                                          style=widgetstyle,
                                          disabled=True)

        self.submit_btn = widgets.Button(description='Submit data',
                                         disabled=False,
                                         button_style='',
                                         tooltip='Click to submit selection',
                                         icon='',
                                         style=widgetstyle)

        self.calculate_btn = widgets.Button(
            description='Calculate',
            disabled=True,
            button_style='',
            tooltip='Click to calculate and export',
            icon='',
            style=widgetstyle)

        self.plots_btn = widgets.Button(description='Make plots',
                                        disabled=True,
                                        button_style='',
                                        tooltip='Click to generate plots',
                                        icon='',
                                        style=widgetstyle)

        self.generate_metadata_btn = widgets.Button(
            description='Generate Template',
            disabled=True,
            button_style='',
            tooltip='Click to generate template in parent folder',
            icon='',
            style=widgetstyle)

        self.export_mean_checkbox = widgets.Checkbox(value=False,
                                                     description="Mean export",
                                                     disabled=True,
                                                     style=widgetstyle)

        self.format_chooser = widgets.Dropdown(
            options=['png', 'svg', 'jpeg'],
            value='svg',
            description='Choose plot format:',
            disabled=True,
            style=widgetstyle)

        self.plot_choice_dropdown = widgets.SelectMultiple(
            options=[
                "individual_histogram", "meaned_histogram",
                "individual_lineplot", "summary_lineplot"
            ],
            value=("individual_histogram", "individual_histogram"),
            description="Choose plot(s) to create",
            disabled=True,
            style=widgetstyle)
Пример #29
0
def open_data_widget(m):
    """A widget for opening local vector/raster data.

    Args:
        m (object): geemap.Map
    """
    tool_output = widgets.Output()
    tool_output_ctrl = WidgetControl(widget=tool_output, position="topright")

    if m.tool_output_ctrl is not None and m.tool_output_ctrl in m.controls:
        m.remove_control(m.tool_output_ctrl)

    file_type = widgets.ToggleButtons(
        options=["Shapefile", "GeoJSON", "GeoTIFF"],
        tooltips=[
            "Open a shapefile",
            "Open a GeoJSON file",
            "Open a GeoTIFF",
        ],
    )

    file_chooser = FileChooser(os.getcwd())
    file_chooser.filter_pattern = "*.shp"
    file_chooser.use_dir_icons = True

    style = {"description_width": "initial"}
    layer_name = widgets.Text(
        value="Shapefile",
        description="Enter a layer name:",
        tooltip="Enter a layer name for the selected file",
        style=style,
        layout=widgets.Layout(width="454px"),
    )

    ok_cancel = widgets.ToggleButtons(
        value=None,
        options=["Apply", "Reset", "Close"],
        tooltips=["Apply", "Reset", "Close"],
        button_style="primary",
    )

    bands = widgets.Text(
        value="1",
        description="Bands:",
        tooltip="Enter a list of band indices",
        style=style,
        layout=widgets.Layout(width="110px"),
    )

    colormap = widgets.Dropdown(
        options=[],
        value=None,
        description="colormap:",
        layout=widgets.Layout(width="172px"),
        style=style,
    )

    x_dim = widgets.Text(
        value="x",
        description="x_dim:",
        tooltip="The x dimension",
        style=style,
        layout=widgets.Layout(width="80px"),
    )

    y_dim = widgets.Text(
        value="y",
        description="y_dim:",
        tooltip="The xydimension",
        style=style,
        layout=widgets.Layout(width="80px"),
    )

    raster_options = widgets.HBox()

    main_widget = widgets.VBox(
        [file_type, file_chooser, layer_name, raster_options, ok_cancel]
    )

    tool_output.clear_output()
    with tool_output:
        display(main_widget)

    # def chooser_callback(chooser):
    #     if len(layer_name.value) == 0 and file_chooser.selected is not None:
    #         layer_name.value = os.path.splitext(file_chooser.selected_filename)[0]

    def bands_changed(change):
        if change["new"] and "," in change["owner"].value:
            colormap.value = None
            colormap.disabled = True
        else:
            colormap.disabled = False

    bands.observe(bands_changed, "value")

    def file_type_changed(change):
        ok_cancel.value = None
        file_chooser.default_path = os.getcwd()
        file_chooser.reset()
        layer_name.value = file_type.value
        if change["new"] == "Shapefile":
            file_chooser.filter_pattern = "*.shp"
            raster_options.children = []
        elif change["new"] == "GeoJSON":
            file_chooser.filter_pattern = "*.geojson"
            raster_options.children = []
        elif change["new"] == "GeoTIFF":
            import matplotlib.pyplot as plt

            file_chooser.filter_pattern = "*.tif"
            colormap.options = plt.colormaps()
            colormap.value = "terrain"
            raster_options.children = [bands, colormap, x_dim, y_dim]

    def ok_cancel_clicked(change):
        if change["new"] == "Apply":
            m.default_style = {"cursor": "wait"}
            file_path = file_chooser.selected

            if file_path is not None:
                ext = os.path.splitext(file_path)[1]
                with tool_output:
                    if ext.lower() == ".shp":
                        ee_object = shp_to_ee(file_path)
                        m.addLayer(ee_object, {}, layer_name.value)
                        m.centerObject(ee_object)
                    elif ext.lower() == ".geojson":
                        ee_object = geojson_to_ee(file_path)
                        m.addLayer(ee_object, {}, layer_name.value)
                        m.centerObject(ee_object)
                    elif ext.lower() == ".tif":
                        sel_bands = [int(b.strip()) for b in bands.value.split(",")]
                        m.add_raster(
                            image=file_path,
                            bands=sel_bands,
                            layer_name=layer_name.value,
                            colormap=colormap.value,
                            x_dim=x_dim.value,
                            y_dim=y_dim.value,
                        )
            else:
                print("Please select a file to open.")

            m.toolbar_reset()
            m.default_style = {"cursor": "default"}

        elif change["new"] == "Reset":
            file_chooser.reset()
            tool_output.clear_output()
            with tool_output:
                display(main_widget)
            m.toolbar_reset()
        elif change["new"] == "Close":
            if m.tool_output_ctrl is not None and m.tool_output_ctrl in m.controls:
                m.remove_control(m.tool_output_ctrl)
                m.tool_output_ctrl = None
                m.toolbar_reset()

        ok_cancel.value = None

    file_type.observe(file_type_changed, names="value")
    ok_cancel.observe(ok_cancel_clicked, names="value")
    # file_chooser.register_callback(chooser_callback)

    m.add_control(tool_output_ctrl)
    m.tool_output_ctrl = tool_output_ctrl
def create_filechooser(default_path="~/", html_title="Select File", use_dir_icons=True):
    fc = FileChooser(default_path)
    fc.title = html_title
    fc.use_dir_icons = use_dir_icons
    return fc