how to trigger callback event on a plotly scattermapbox plot - callback

I am trying to run the code below, and the map is generated correctly (showing the locations of interest), but when clicking on a location, the callback function is not triggered. I have tried setting the layout to 'clickmode': 'event', and then the selected point is highlighted, but the callback function is not triggered. It must be something small, but I can't figure out what I am missing, any help or suggestion is highly appreciated.
# Import libraries
import pandas as pd
import numpy as np
import plotly.express as px
import plotly.graph_objects as go
import json
import ipywidgets as widgets
from ipywidgets import Output, VBox
data2 = go.Scattermapbox(lat=list(heat_df.ycoord),
lon=list(heat_df.xcoord),
mode='markers+text',
marker=dict(size=20, color='green'),
)
layout = dict(margin=dict(l=0, t=0, r=0, b=0, pad=0),
mapbox=dict(#accesstoken=mapbox_access_token,
center=dict(lat=51.6, lon=-0.2),
style='light',
zoom=8))
f2 = go.FigureWidget(data=data2, layout=layout);
f2.update_layout(mapbox_style="stamen-terrain"
, mapbox_center = {"lat": map_meanY, "lon": map_meanX}
, mapbox_zoom= 11
#, clickmode='event'
);
scatter = f2.data[0]
scatter.marker.size = [20] * 100
f2.layout.hovermode = 'closest'
out = Output()
#out.capture(clear_output=True)
def click_callback(trace, points, selector):
inds = points.point_inds
print(inds)
f2.data[0].on_click(click_callback,append=False)
#help(f2.data[0].on_click)
f2
Setting mode='markers+text', to mode='markers' throws in the ValueError:
File ~\anaconda3\envs\geemap_test\lib\site-packages\plotly\basedatatypes.py:2637, in BaseFigure._perform_plotly_relayout(self, relayout_data)
2633 for key_path_str, v in relayout_data.items():
2635 if not BaseFigure._is_key_path_compatible(key_path_str, self.layout):
-> 2637 raise ValueError(
2638 """
2639 Invalid property path '{key_path_str}' for layout
2640 """.format(
2641 key_path_str=key_path_str
2642 )
2643 )
2645 # Apply set operation on the layout dict
2646 val_changed = BaseFigure._set_in(self._layout, key_path_str, v)
ValueError:
Invalid property path 'mapbox._derived' for layout

Related

Issue with scipy.io.wavfile.read and scipy.fftpack.fft

from os.path import dirname, join as pjoin
import scipy.io as sio
from scipy.io import wavfile
from scipy.fftpack import fft
data_dir = pjoin(dirname(sio.__file__), 'tests', 'data')
wav_fname = pjoin(data_dir, 'test-44100Hz-2ch-32bit-float-be.wav')
print(wav_fname)
def create_FFT(fn,size=1000):
sample_rate, X = wavfile.read(fn)
fft_features = abs(fft(X)[:size])
return(sample_rate, X, fft_features)
for wav_fn in wav_fname :
samplerate, data, fft_features = create_FFT(wav_fn)
print(f"number of channels = {data.shape[1]}")
print("fft features are: {}".format(fft_features))
In the above code, if I don't include fft specific code in the create_FFT function, I could read the file and print the number of channels. However, as soon as I include fft specific code, I get an error "FileNotFoundError: [Errno 2] No such file or directory: 'C'"
Any help will be appreciated.
Found the answer. It was with the for loop at the bottom.

ValueError: Cannot feed value of shape (1, 2048, 2048, 1) for Tensor 'image_tensor:0', which has shape '(?, ?, ?, 3)'

Using TensorFlow I am trying to detect one object(png and grayscale image). I have trained and exported a model.ckpt successfully. Now I am trying to restore the saved model.ckpt for prediction. Here is the script:
import numpy as np
import os
import six.moves.urllib as urllib
import sys
import tarfile
import tensorflow as tf
import zipfile
from collections import defaultdict
from io import StringIO
from matplotlib import pyplot as plt
from PIL import Image
if tf.__version__ != '1.4.0':
raise ImportError('Please upgrade your tensorflow installation to v1.4.0!')
# This is needed to display the images.
#matplotlib inline
# This is needed since the notebook is stored in the object_detection folder.
sys.path.append("..")
from utils import label_map_util
from utils import visualization_utils as vis_util
MODEL_NAME = 'melon_graph'
# Path to frozen detection graph. This is the actual model that is used for the object detection.
PATH_TO_CKPT = MODEL_NAME + '/frozen_inference_graph.pb'
# List of the strings that is used to add correct label for each box.
PATH_TO_LABELS = os.path.join('training', 'object_detection.pbtxt')
NUM_CLASSES = 1
detection_graph = tf.Graph()
with detection_graph.as_default():
od_graph_def = tf.GraphDef()
with tf.gfile.GFile(PATH_TO_CKPT, 'rb') as fid:
serialized_graph = fid.read()
od_graph_def.ParseFromString(serialized_graph)
tf.import_graph_def(od_graph_def, name='')
label_map = label_map_util.load_labelmap(PATH_TO_LABELS)
categories = label_map_util.convert_label_map_to_categories(label_map, max_num_classes=NUM_CLASSES, use_display_name=True)
category_index = label_map_util.create_category_index(categories)
def load_image_into_numpy_array(image):
(im_width, im_height) = image.size
return np.array(image.getdata()).reshape((im_height, im_width, 1)).astype(np.float64)
# For the sake of simplicity we will use only 2 images:
# If you want to test the code with your images, just add path to the images to the TEST_IMAGE_PATHS.
PATH_TO_TEST_IMAGES_DIR = 'test_images'
TEST_IMAGE_PATHS = [ os.path.join(PATH_TO_TEST_IMAGES_DIR, 'te_data{}.png'.format(i)) for i in range(1, 336) ]
# Size, in inches, of the output images.
IMAGE_SIZE = (12, 8)
with detection_graph.as_default():
with tf.Session(graph=detection_graph) as sess:
# Definite input and output Tensors for detection_graph
image_tensor = detection_graph.get_tensor_by_name('image_tensor:0')
# Each box represents a part of the image where a particular object was detected.
detection_boxes = detection_graph.get_tensor_by_name('detection_boxes:0')
# Each score represent how level of confidence for each of the objects.
# Score is shown on the result image, together with the class label.
detection_scores = detection_graph.get_tensor_by_name('detection_scores:0')
detection_classes = detection_graph.get_tensor_by_name('detection_classes:0')
num_detections = detection_graph.get_tensor_by_name('num_detections:0')
for image_path in TEST_IMAGE_PATHS:
image = Image.open(image_path)
# the array based representation of the image will be used later in order to prepare the
# result image with boxes and labels on it.
image_np = load_image_into_numpy_array(image)
# Expand dimensions since the model expects images to have shape: [1, None, None, 3]
image_np_expanded = np.expand_dims(image_np, axis=0)
# Actual detection.
(boxes, scores, classes, num) = sess.run([detection_boxes, detection_scores, detection_classes, num_detections], feed_dict={image_tensor: image_np_expanded})
# Visualization of the results of a detection.
vis_util.visualize_boxes_and_labels_on_image_array(image_np,np.squeeze(boxes),np.squeeze(classes).astype(np.float64), np.squeeze(scores), category_index, use_normalized_coordinates=True, line_thickness=5)
plt.figure(figsize=IMAGE_SIZE)
plt.imshow(image_np)
and this is the error
Traceback (most recent call last): File "cochlear_detection.py",
line 81, in
(boxes, scores, classes, num) = sess.run([detection_boxes, detection_scores, detection_classes, num_detections],
feed_dict={image_tensor: image_np_expanded}) File
"/anaconda/lib/python3.6/site-packages/tensorflow/python/client/session.py",
line 889, in run
run_metadata_ptr) File "/anaconda/lib/python3.6/site-packages/tensorflow/python/client/session.py",
line 1096, in _run
% (np_val.shape, subfeed_t.name, str(subfeed_t.get_shape()))) ValueError: Cannot feed value of shape (1, 2048, 2048, 1) for Tensor
'image_tensor:0', which has shape '(?, ?, ?, 3)'

Error when using Seaborn in jupyter notebook(pyspark)

I am trying to visualize data using Seaborn. I have created a dataframe using SQLContext in pyspark. However, when I call lmplot it results in an error. I am not sure what I am missing. Given below is my code(I am using jupyter notebook):
import pandas as pd
from matplotlib import pyplot as plt
import seaborn as sns
from pyspark.sql import SQLContext
sqlContext = SQLContext(sc)
df = sqlContext.read.load('file:///home/cloudera/Downloads/WA_Sales_Products_2012-14.csv',
format='com.databricks.spark.csv',
header='true',inferSchema='true')
sns.lmplot(x='Quantity', y='Year', data=df)
Error trace:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-86-2a2b43993475> in <module>()
----> 2 sns.lmplot(x='Quantity', y='Year', data=df)
/home/cloudera/anaconda3/lib/python3.5/site-packages/seaborn/regression.py in lmplot(x, y, data, hue, col, row, palette, col_wrap, size, aspect, markers, sharex, sharey, hue_order, col_order, row_order, legend, legend_out, x_estimator, x_bins, x_ci, scatter, fit_reg, ci, n_boot, units, order, logistic, lowess, robust, logx, x_partial, y_partial, truncate, x_jitter, y_jitter, scatter_kws, line_kws)
557 hue_order=hue_order, size=size, aspect=aspect,
558 col_wrap=col_wrap, sharex=sharex, sharey=sharey,
--> 559 legend_out=legend_out)
560
561 # Add the markers here as FacetGrid has figured out how many levels of the
/home/cloudera/anaconda3/lib/python3.5/site-packages/seaborn/axisgrid.py in __init__(self, data, row, col, hue, col_wrap, sharex, sharey, size, aspect, palette, row_order, col_order, hue_order, hue_kws, dropna, legend_out, despine, margin_titles, xlim, ylim, subplot_kws, gridspec_kws)
255 # Make a boolean mask that is True anywhere there is an NA
256 # value in one of the faceting variables, but only if dropna is True
--> 257 none_na = np.zeros(len(data), np.bool)
258 if dropna:
259 row_na = none_na if row is None else data[row].isnull()
TypeError: object of type 'DataFrame' has no len()
Any help or pointer is appreciated. Thank you in advance:-)
sqlContext.read.load(...) returns a Spark-DataFrame. I am not sure, whether seaborn can automatically cast a Spark-DataFrame into a Pandas-Dataframe.
Try:
sns.lmplot(x='Quantity', y='Year', data=df.toPandas())
df.toPandas() returns the the pandas-DF from the Spark-DF.

Bokeh slider change length of x

In a given DataSeries I want to use a Bokeh slider to change the number of observations I show (the tail). Can this be done, if it can why won't my script work?
import pandas as pd
from bokeh.plotting import show, output_file
from bokeh.models import CustomJS, Slider, Column
from bokeh.io import output_notebook
ds = pd.Series( [i for i in range(20)], pd.date_range('2016-01-02', periods=20, freq='D'))
tail = 5
ds.tail(tail)
#Bokeh slider to change value of "tail"
s1 = Slider(start=1, end=20, value=3, step=1)
s1.callback = CustomJS(args=dict(s1=s1, tail=tail), code="""
ds.tail("tail", s1.get('value'));
""")
show(Column(s1))
ds.tail(tail)

How to use ScatterInspector and ScatterInspectorOverlay?

I would like to use the chaco tools ScatterInspector and/or ScatterInspectorOverlay with enaml. I've set up a very simple controller and view (source below) but cannot determine how to proceed. I have tried unsuccessfully to follow the minimal and old examples I've found.
If I uncomment the overlay part for ScatterInspectorOverlay, the code fails to run with
File ".../chaco/scatter_inspector_overlay.py", line 51, in overlay if not plot or not plot.index or not getattr(plot, "value", True):
If I comment out the overlay part, I of course don't get the overlay behavior I want and also, on moving the mouse, get
File ".../chaco/tools/scatter_inspector.py", line 48, in normal_mouse_move index = plot.map_index((event.x, event.y), threshold=self.threshold)
view.enaml source:
from enaml.widgets.api import (
Window, Container, EnableCanvas,
)
enamldef ScatterView(Window):
attr controller
title = "Scatter Inspector Test"
initial_size = (640,480)
Container:
EnableCanvas:
component = controller.scatter_plot
controller.py source:
import enaml
from enaml.stdlib.sessions import show_simple_view
from traits.api import HasTraits, Instance
from chaco.api import Plot, ArrayPlotData, ScatterInspectorOverlay
from chaco.tools.api import ScatterInspector
from numpy import linspace, sin
class ScatterController(HasTraits):
scatter_plot = Instance(Plot)
def _scatter_plot_default(self):
# data
x = linspace(-14, 14, 100)
y = sin(x) * x**3
plotdata = ArrayPlotData(x = x, y = y)
# plot
scatter_plot = Plot(plotdata)
renderer = scatter_plot.plot(("x", "y"), type="scatter", color="red")
# inspector
scatter_plot.tools.append(ScatterInspector(scatter_plot))
# overlay
# scatter_plot.overlays.append( ScatterInspectorOverlay(
# scatter_plot,
# hover_color = 'red',
# hover_marker_size = 6,
# selection_marker_size = 6,
# selection_color = 'yellow',
# selection_outline_color='purple',
# selection_line_width = 3
# ))
#return
return scatter_plot
if __name__ == "__main__":
with enaml.imports():
from view import ScatterView
main_controller = ScatterController()
window = ScatterView(controller=ScatterController())
show_simple_view(window)
The problem with my above code was that I was adding ScatterInspector to scatter_plot rather than to renderer and that I was missing the [0] index to get renderer.
The key thing I was really wanting to do, though, was to be notified when the mouse was hovering over a data point and/or a data point was selected. I added when_hover_or_selection_changes which shows how to do that.
Working controller.py:
...
# plot
scatter_plot = Plot(plotdata)
renderer = scatter_plot.plot(("x", "y"), type="scatter", color="lightblue")[0]
# inspector
renderer.tools.append(ScatterInspector(renderer))
# overlay
renderer.overlays.append(ScatterInspectorOverlay(renderer,
hover_color="red",
hover_marker_size=6,
selection_marker_size=6,
selection_color="yellow",
selection_outline_color="purple",
selection_line_width=3))
...
# get notified when hover or selection changes
#on_trait_change('renderer.index.metadata')
def when_hover_or_selection_changes(self):
print 'renderer.index.metadata = ', self.renderer.index.metadata