Beispiel #1
0
def upload():

    text_file = FileUpload()

    def cb(change):
        global file_contents
        decoded = io.StringIO(change['owner'].data[0].decode('utf-8'))
        # filename = change['owner'].filename
        # print('Uploaded `{}` ({:.2f} kB)'.format(
        #    filename, len(decoded.read()) / 2 **10))
        file_contents = decoded.getvalue()

    text_file.observe(cb, names='data')
    display(text_file)
Beispiel #2
0
    def _create_input_widget(self, inputs: HasTraits) -> Widget:
        print("Creating widget")

        # uploaded_file_details = Output()
        file_upload = FileUpload(accept=".csv", multiple=False)

        def set_module_value(change):

            # inputs.files = list(change.new.values())
            inputs.files = change.new
            # file_upload.value.clear()
            file_upload._counter = 0

        file_upload.observe(set_module_value, names="value")
        return file_upload
Beispiel #3
0
    def create_file_upload(self) -> v.Btn:
        file_uploader = FileUpload(description=".ics file", multiple=False)

        def on_upload(change):
            self.main_loading.indeterminate = True
            value = change["new"]
            filename = list(value.keys())[0]
            uploaded_file = Path(self.app_dir) / filename
            try:
                with open(uploaded_file, "wb") as outfile:
                    outfile.write(value[filename]["content"])
                hm = Heatmap(input_data=uploaded_file)
                hm.draw(title=filename)
                self.heatmap_plot.children = [hm.result.canvas]
            finally:
                Path(uploaded_file).exists() and Path(uploaded_file).unlink()
                self.main_loading.indeterminate = False

        file_uploader.observe(on_upload, "value")
        btn_uploader = v.Btn(class_="mx-2", children=[file_uploader])
        return btn_uploader
Beispiel #4
0
class ImageSelector():
    def __init__(self, image_dict, max_width=None):
        self.max_width = max_width
        self.image_dict = image_dict
        self.default_image = list(image_dict.keys())[0]
        self.image = self.image_dict[self.default_image]
        # Image Selector
        self.image_selector = Dropdown(options=list(self.image_dict) + ['+ Add new image'])
        self.image_selector.observe(self.on_selector_change, 'value')
        self.selector_box = HBox(children=[self.image_selector], layout=Layout(justify_content='space-around'))
        # Image Display
        width, height = self.get_size(*self.image.size)
        self.image_display = Image(value=to_binary(self.image),
                                   format='png',
                                   width=width,
                                   height=height)
        self.display_box = HBox(children=[self.image_display], layout=Layout(justify_content='center'))
        self.widget = VBox(children=[self.selector_box, self.display_box],
                           layout=Layout(align_content='inherit'))

    def get_size(self, width, height):
        if self.max_width is not None:
            new_width = min(self.max_width, width)
            height = int((new_width/width) * height)
            return new_width, height
        return width, height

    def change_image(self, image):
        self.image = image
        self.image_display.width, self.image_display.height = self.get_size(*image.size)
        self.image_display.value = to_binary(image)

    def on_selector_change(self, change):
        if self.image_selector.value in self.image_dict:
            self.change_image(self.image_dict[self.image_selector.value])
            self.widget.children = [self.selector_box, self.display_box]
        else:
            self.upload_widget = FileUpload(accept='image/*', multiple=False)
            self.name_widget = Text(description='<b>Image Name</b>', style={'description_width': 'initial'})
            self.ok_widget = ToggleButton(
                            value=False,
                            description='Add',
                            disabled=False,
                            button_style='success',
                            tooltip='Description',
                            icon='check')

            self.add_widget = HBox(children=[self.upload_widget, self.name_widget, self.ok_widget],
                                   layout=Layout(justify_content='space-around'))

            self.widget.children = [self.selector_box, self.add_widget]
            self.upload_widget.observe(self.on_upload, 'value')
            self.ok_widget.observe(self.on_add, 'value')
    #

    def on_upload(self, change):
        image_binary = list(self.upload_widget.value.values())[0]['content']
        image = PImage.open(BytesIO(image_binary))
        self.change_image(image)
        self.widget.children = [self.selector_box, self.add_widget, self.display_box]

    def on_add(self, change):
        if self.upload_widget.value:
            image_binary = list(self.upload_widget.value.values())[0]['content']
            self.image_dict[self.name_widget.value] = PImage.open(BytesIO(image_binary))
            self.image_selector.options = list(self.image_dict) + ['+ Add new image']
            self.image_selector.value = self.name_widget.value
Beispiel #5
0
            self.geojson = None
        self.marker_or_geojson = None


label = Label()
file_upload = FileUpload(accept='.geojson,.json',
                         multiple=False,
                         description='Upload GeoJSON')

m = Map(center=(-10, -60),
        zoom=4,
        interpolation='nearest',
        basemap=basemaps.CartoDB.DarkMatter)
map_menu = Map_menu(m, label, file_upload)
m.on_interaction(map_menu.show)
file_upload.observe(map_menu.show_geojson, 'value')


def to_webmercator(source, affine, bounds):
    with rasterio.Env():
        rows, cols = source.shape
        src_transform = affine
        src_crs = {'init': 'EPSG:4326'}
        dst_crs = {'init': 'EPSG:3857'}
        dst_transform, width, height = rasterio.warp.calculate_default_transform(
            src_crs, dst_crs, cols, rows, *bounds)
        dst_shape = height, width
        destination = np.zeros(dst_shape)
        reproject(source,
                  destination,
                  src_transform=src_transform,
Beispiel #6
0
class Mint(MintBase):
    def __init__(self, *args, **kwargs):

        self.progress_callback = self.set_progress

        super().__init__(progress_callback=self.progress_callback,
                         *args,
                         **kwargs)

        fc = FileChooser()
        fc.show_only_dirs = True
        fc.default_path = tempfile.gettempdir()

        self.ms_storage_path = fc

        self.ms_upload = FileUpload()

        self.peaklist_files_button = FileUpload(description='Peaklists',
                                                accept='csv,xlsx',
                                                multiple=False)

        self.peaklist_files_button.observe(self.load_peaklist, names='value')

        self.load_ms_button = Button(description='Load MS-files')

        self.load_ms_button.on_click(self.search_files)

        self.detect_peaks_button = Button(description="Detect Peaks")
        self.detect_peaks_button.on_click(self.detect_peaks)

        self.message_box = Textarea(
            value='',
            placeholder='Please select some files and click on Run.',
            description='',
            disabled=True,
            layout={
                'width': '90%',
                'height': '500px',
                'font_family': 'monospace'
            })

        self.run_button = Button(description="Run")
        self.run_button.on_click(self.run)
        self.run_button.style.button_color = 'lightgray'

        self.optimize_rt_button = Button(description="Find closest peaks")
        self.optimize_rt_button.on_click(self.action_optimize_rt)

        self.download_button = Button(description="Export")
        self.download_button.on_click(self.export_action)
        self.download_button.style.button_color = 'lightgray'

        self.progress_bar = Progress(min=0,
                                     max=100,
                                     layout=Layout(width='90%'),
                                     description='Progress:',
                                     bar_style='info')

        self.output = widgets.Output()

        tabs = Tab()
        tabs.children = [
            HBox([self.ms_storage_path, self.ms_upload, self.load_ms_button]),
            HBox([
                self.peaklist_files_button, self.detect_peaks_button,
                self.optimize_rt_button
            ]),
        ]

        tabs.set_title(0, 'MS-Files')
        tabs.set_title(1, 'Peaklists')

        self.layout = VBox([
            tabs, self.message_box,
            HBox([self.run_button, self.download_button]), self.progress_bar
        ])

    def load_peaklist(self, value):
        for fn, data in value['new'].items():
            self.load(io.BytesIO(data['content']))
        self.list_files()

    def action_optimize_rt(self, b):
        if (self.n_files > 0) and len(self.peaklist) > 0:
            self.optimize_rt()

    def message(self, text):
        self.message_box.value = f'{text}\n' + self.message_box.value

    def clear_messages(self):
        self.message_box.value = ''

    def search_files(self, b=None):
        self.ms_files = (
            glob(os.path.join(self.ms_storage_path.selected_path, '*mzXML')) +
            glob(os.path.join(self.ms_storage_path.selected_path, '*mzML')) +
            glob(os.path.join(self.ms_storage_path.selected_path, '*mzHDF')) +
            glob(os.path.join(self.ms_storage_path.selected_path, '*mzxml')) +
            glob(os.path.join(self.ms_storage_path.selected_path, '*mzml')) +
            glob(os.path.join(self.ms_storage_path.selected_path, '*mzhdf')))
        self.list_files()

    def show(self):
        display(
            HTML("<style>textarea, input { font-family: monospace; }</style>"))
        return self.layout

    def files(self, files):
        super(Mint, self).ms_files = files
        self.ms_files_button.files = files
        self.list_files()

    def add_ms_files(self, fns):
        if fns is not None:
            self.ms_files = self.ms_files + fns
        self.list_files()

    def add_peaklist_files(self, fns):
        if fns is not None:
            self.peaklist_files = self.peaklist_files + fns
        self.list_files()

    def list_files(self, b=None):
        text = f'{self.n_files} MS-files to process:\n'
        for i, line in enumerate(self.ms_files):
            text += line + '\n'
            if i > 10:
                text += line + '\n...\n'
                break
        text += '\nUsing peak list:\n'
        if len(self.peaklist_files) != 0:
            text += '\n'.join([str(i) for i in self.peaklist_files])
        elif len(self.peaklist) != 0:
            text += self.peaklist.to_string()
        else:
            text += '\nNo peaklist defined.'
        self.message(text)
        if (self.n_files != 0) and (self.n_peaklist_files != 0):
            self.run_button.style.button_color = 'lightgreen'
        else:
            self.run_button.style.button_color = 'lightgray'

    def run(self, b=None, **kwargs):
        self.progress = 0
        super(Mint, self).run(**kwargs)
        self.message('Done processing MS-files.')
        if self.results is not None:
            self.download_button.style.button_color = 'lightgreen'

    def detect_peaks(self, b=None, **kwargs):
        self.message('\n\nRun peak detection.')
        super(Mint, self).detect_peaks(**kwargs)

    def set_progress(self, value):
        self.progress_bar.value = value

    def export_action(self, b=None, filename=None):
        if filename is None:
            filename = 'MINT__results.xlsx'
            filename = os.path.join(HOME, filename)
        self.export(filename)
        self.message(f'\n\nExported results to: {filename}')
Beispiel #7
0
class UbxMap():
    def __init__(self,
                 basemapName="Mapnik",
                 animate=False,
                 zoom=16,
                 width="100%",
                 height="720px"):
        """Parse the UBX File and put it into a DataFrame"""
        self.OnLocationChanged = None
        self.OnDataLoaded = None
        self.OnDataFileChanged = None
        self._animate = animate

        # map
        self._basemaps = {
            "Mapnik": basemaps.OpenStreetMap.Mapnik,
            "Satellite": basemaps.Esri.WorldImagery,
            "WorldStreetMap": basemaps.Esri.WorldStreetMap,
            "BlackAndWhite": basemaps.OpenStreetMap.BlackAndWhite,
            "France": basemaps.OpenStreetMap.France,
            "HOT": basemaps.OpenStreetMap.HOT,
            "OpenTopoMap": basemaps.OpenTopoMap,
            "WorldTopoMap": basemaps.Esri.WorldTopoMap,
        }
        self._basemapName = basemapName
        self._basemap = self._basemaps[self._basemapName]
        self._zoom = zoom
        self._startLocation = (49, 8)
        self._m = Map(basemap=self._basemap,
                      center=self._startLocation,
                      zoom=self._zoom,
                      close_popup_on_click=False)
        self._m.layout.width = width
        self._m.layout.height = height

        self._addControls()
        # parser
        self._parser = UbxParser()

        # GUI elements
        self._fileSelector = widgets.Dropdown(value=self.UbxFiles[0],
                                              placeholder="Log Files",
                                              options=self.UbxFiles,
                                              description="Log File",
                                              ensureoption=False,
                                              disabled=False)
        self._fileSelector.observe(self._on_filename_changed, names='value')

        self._waypointSlider = widgets.IntSlider(
            value=0,
            description="Waypoint",
            min=0,
            max=0,
            layout=widgets.Layout(width='50%'))
        self._waypointSlider.observe(self._on_waypoint_changed, names='value')

        self._mapSelector = widgets.Dropdown(value=self._basemapName,
                                             options=list(
                                                 self._basemaps.keys()),
                                             description="Map",
                                             ensureoption=True,
                                             disabled=False)
        self._mapSelector.observe(self._on_mapstyle_changed, names='value')

        self._upload = FileUpload(accept='.pubx', multiple=True)
        self._upload.observe(self._on_file_upload_changed, names="value")

        self._header = HTML(
            "<b><font size='2' color='orange'>pixelmaps</font></b>")

        self._gui = widgets.VBox([
            widgets.HBox([
                self._header, self._fileSelector, self._waypointSlider,
                self._mapSelector, self._upload
            ]), self._m
        ])

    @property
    def CurrentLocation(self):
        return self._waypointMarker.location

    @property
    def RouteLine(self):
        return self._routeLine

    @property
    def Map(self):
        return self._m

    @property
    def WaypointSliderWidget(self):
        return self._waypointSlider

    @property
    def FileSelectorWidget(self):
        return self._fileSelector

    @property
    def MaxNumberOfWaypoints(self):
        return len(self._df) - 1

    @property
    def UbxFiles(self):
        ubxFiles = []
        dir = os.listdir()
        ubxFiles = []
        for file in dir:
            if file.endswith(".pubx"):
                ubxFiles.append(file)
        if len(ubxFiles) == 0:
            ubxFiles.append("<NoLogFiles>")
        return ubxFiles

    def setCurrentWaypoint(self, value):
        self._currentWaypoint = value
        row = self._df.iloc[self._currentWaypoint]
        speed = row["groundspeed"]
        gz = row["gravityz"]
        ml = row["miclevel"]
        lat = row["latitude"]
        lng = row["longitude"]
        head = row["headingofmotion"]
        self._waypointMessage.value = f"Moving {self._parser.direction(head)} with {speed:.0f} Km/h"
        #self._waypointMarker.rotation_angle = head
        self._waypointMarker.location = (lat, lng)
        self._center()

    def Append(self, filename):
        self._filename = filename
        self._df = self._df.append(
            DataFrame.from_dict(self._parser.read(self._filename)))
        self._updateData()

    def Load(self, filename="<First>"):
        if filename == "<First>":
            self._filename = self.UbxFiles[0]
            if self._filename == "<NoLogFiles>":
                return
        else:
            self._filename = filename
        self._df = DataFrame.from_dict(self._parser.read(self._filename))
        self._updateData()
        self._clearLayers()

    def _updateData(self):
        # Get the start location
        self._startLocation = (self._df.at[0, 'latitude'],
                               self._df.at[0, 'longitude'])

        # Calculate the route average speed
        self._averageSpeed = self._df["groundspeed"].mean()
        self._minSpeed = self._df["groundspeed"].min()
        self._maxSpeed = self._df["groundspeed"].max()
        self._averageHOF = self._df["headingofmotion"].mean()
        # Get the route points to draw the route
        self._routePoints = self._df.loc[:, ["latitude", "longitude"
                                             ]].values.tolist()

        self._waypointSlider.max = self.MaxNumberOfWaypoints

        if self.OnDataLoaded:
            self.OnDataLoaded(self)

    def _addControls(self):
        # Add Controls
        self._m.add_control(
            MeasureControl(position='bottomleft',
                           active_color='orange',
                           primary_length_unit='kilometers'))
        self._m.add_control(FullScreenControl())
        self._m.add_control(ScaleControl(position='bottomleft'))
        searchMarker = Marker(icon=AwesomeIcon(
            name="check", marker_color='green', icon_color='darkred'))
        self._m.add_control(
            SearchControl(
                position="topleft",
                url=
                'https://nominatim.openstreetmap.org/search?format=json&q={s}',
                zoom=self._zoom,
                marker=searchMarker))

    def Display(self):
        self._fileSelector.options = self.UbxFiles
        self._waypointSlider.max = self.MaxNumberOfWaypoints
        return self._gui

    def move(self, location):
        self._waypointMarker.location = location

    def _on_filename_changed(self, change):
        newFile = change["new"]
        self.Load(newFile)
        self.DrawRoute()
        if self.OnDataFileChanged:
            self.OnDataFileChanged(self, change["new"])

    def _on_file_upload_changed(self, change):
        newFile = change["new"]
        with open(newFile, 'wb') as output_file:
            for uploaded_filename in self._upload.value:
                content = self._upload.value[uploaded_filename]['content']
                output_file.write(content)

    def _on_mapstyle_changed(self, change):
        self._basemapName = change["new"]
        self._m.layers = [basemap_to_tiles(self._basemaps[self._basemapName])]
        self.DrawRoute()

    def _on_waypoint_changed(self, change):
        self._currentWaypoint = int(change['new'])
        self.setCurrentWaypoint(self._currentWaypoint)

    def _on_location_changed(self, event):
        # Do some computation given the new marker location, accessible from `event['new']
        print(event["new"])

    def _addWaypoint(self):
        # Waypoint
        self._waypointMarker = Marker(location=self._startLocation,
                                      draggable=False)
        self._waypointMarker.observe(self._on_location_changed, 'location')
        self._m.add_layer(self._waypointMarker)

        # Waypoint Popup Message
        self._waypointMessage = HTML()
        self._waypointMarker.popup = self._waypointMessage

    def DrawRoute(self):
        # Draw the route
        #self._clearLayers()
        self._routeLine = AntPath(
            locations=self._routePoints,
            dash_array=[1, int(self._averageSpeed)],
            delay=int(self._averageSpeed * 500),
            color="red",
            pulse_color="blue")  #color='#7590ba',pulse_color='#3f6fba')
        self._m.add_layer(self._routeLine)
        self._addWaypoint()
        self._center()
        self._addStats()
        if self._animate:
            self._center()

    def _center(self):
        self._m.center = self._waypointMarker.location

    def _centerTo(self, location):
        self._m.center = location

    def _clearLayers(self):
        self._m.clear_layers()
        self._m.layers = [basemap_to_tiles(self._basemap)]

    def calcSpeedZGravityThreshold(self, speed, grvityz):
        threshold = 10.5
        if speed < 6:  #walking
            threshold = 12.5
        elif speed >= 6 and speed < 10:  # running
            threshold = 14.5
        elif speed > 10 and speed < 25:  # bike
            threshold = 16.5
        return threshold

    def _addStats(self):
        oldloc = (0, 0)
        # Iterate through the route points
        for index, row in self._df.iterrows():
            # Get various row info
            speed = row["groundspeed"]
            gz = row["gravityz"]
            ml = row["miclevel"]
            lat = row["latitude"]
            lng = row["longitude"]
            loc = (lat, lng)

            # Add speed markers
            if speed < 2 and self._parser.distance(loc, oldloc) > 0.01:
                #m.add_layer(Marker(location=loc, draggable=False, title="Stopped"))
                self._m.add_layer(
                    Circle(location=loc,
                           radius=5,
                           color="green",
                           fill_color="green"))
                oldloc = loc
                if self._animate:
                    self._centerTo(loc)

            # Add Z Gravity markers (bumps)
            if gz > self.calcSpeedZGravityThreshold(speed, gz):
                self._m.add_layer(
                    Circle(location=loc,
                           radius=int(gz / 2),
                           color="red",
                           fill_color="red"))
                if self._animate:
                    self._centerTo(loc)

            # Add Sound Markers
            if ml >= 1.5:
                self._m.add_layer(
                    Circle(location=loc,
                           radius=int(ml * 5),
                           color="orange",
                           fill_color="orange"))
                if self._animate:
                    self._centerTo(loc)