Basemap and Matplotlib - Improving Speed - python

I'm creating a tool for geospatial visualization of economic data using Matplotlib and Basemap.
However, right now, the only way I thought of that gives me enough flexibility is to create a new basemap every time I want to change the data.
Here are the relevant parts of the code I'm using:
class WorldMapCanvas(FigureCanvas):
def __init__(self,data,country_data):
self.text_objects = {}
self.figure = Figure()
self.canvas = FigureCanvas(self.figure)
self.axes = self.figure.add_subplot(111)
self.data = data
self.country_data = country_data
#this draws the graph
super(WorldMapCanvas, self).__init__(Figure())
self.map = Basemap(projection='robin',lon_0=0,resolution='c', ax=self.axes)
self.country_info = self.map.readshapefile(
'shapefiles/world_country_admin_boundary_shapefile_with_fips_codes', 'world', drawbounds=True,linewidth=.3)
self.map.drawmapboundary(fill_color = '#85A6D9')
self.map.fillcontinents(color='white',lake_color='#85A6D9')
self.map.drawcoastlines(color='#6D5F47', linewidth=.3)
self.map.drawcountries(color='#6D5F47', linewidth=.3)
self.countrynames = []
for shapedict in self.map.world_info:
self.countrynames.append(shapedict['CNTRY_NAME'])
min_key = min(data, key=data.get)
max_key = max(data, key=data.get)
minv = data[min_key]
maxv = data[max_key]
for key in self.data.keys():
self.ColorCountry(key,self.GetCountryColor(data[key],minv,maxv))
self.canvas.draw()
How can I create these plots faster?
I couldn't think of a solution to avoid creating a map every time I run my code. I tried creating the canvas/figure outside of the class but it didn't make that much of a difference. The slowest call is the one that creates the Basemap and loads the shape data. Everything else runs quite fast.
Also, I tried saving the Basemap for future use but since I need new axes I couldn't get it to work. Maybe you can point me in the right direction on how to do this.
I'd like you to know that I'm using the canvas as a PySide QWidget and that I'm plotting different kinds of maps depending on the data, this is just one of them (another would be a map of Europe, for instance, or the US).

You can pickle and unpickle Basemap instances (there is an example of doing this in the basemap source) which might save you a fair chunk of time on the plot creation.
Additionally, it is probably worth seeing how long the shapefile reading is taking (you may want to pickle that too).
Finally, I would seriously consider investigating the option of updating country colours for data, rather than making a new figure each time.
HTH,

Related

Bokeh: Whats the differences between certain methods of editing data in a ColumnDataSource

I have a question regarding the ColumnDataSource in a Bokeh 2.3.0 Server application.
Below is an example that tries to illustrate my question. Eventough it is a littlebit longer, I've spend a lot of effort making it as minimal but complete as possible.
So, there are at least two major ways of editing the data in ColumnDataSource that I know will work.
First one is by using the 'index_way' (I don't know how to call this method correctly) by using source.data['my_column_name'][<numpy_like_array_indexing>] = 'my_new_value' where <numpy_like_array_indexing> can result in something like [0:10] or [[True,False,True]], ect. to subset the data like a numpy array. This way, one can use the source.selected.indices to index the data for example.
The second method is using the .patch() function of ColumnDataSource. Which the reference calls describes as Efficiently update data source columns at specific locations.
The third method I came accross in my code is when editing/changing a complete column in ColumnDataSource like source.data['my_data_column_1'] = source.data['my_data_column_2']. This way, I can set a data column to an already existing one.
My question is: Are they designed to behave differently? I found that changes using the 'index' method are not propagated or updated to the HoverTool, wheares for the other two methods, this seem to work.
This behavior can be seen in the following code example. When changing the first few samples in the plot, by selecting them with the selection tool and editing source.data['Label'] via label_selected_via_index() the HoverTool does not show the correct and updated value of 'Label'. However, the change in the data was acutally performed, which can be seen by check_label() which accesses and prints the first few samples of source.data['Label'].
Changing the Label Value with one of the other methods does indeed show the correct and updated value when hovering over the data.
import pandas as pd
from bokeh.plotting import figure, curdoc
from bokeh.models import ColumnDataSource, LinearColorMapper, Dropdown, Button, HoverTool
from bokeh.layouts import layout
import random
import time
plot_data = 'Value1'
LEN = 1000
df = pd.DataFrame({"ID":[i for i in range(LEN)],
"Value1":[random.random() for i in range(LEN)],
"Value2":[random.random() for i in range(LEN)],
"Color": [int(random.random()*10) for i in range(LEN)] })
df['plot_data'] = df[plot_data]
df['Label'] = "No Label Set"
df['Label_new_col'] = "Label was added"
source = ColumnDataSource(df)
cmap = LinearColorMapper(palette="Turbo256", low = 0, high = 3)
def make_tooltips():
return [('ID', '#ID'),
('Label', '#Label'),
(plot_data, f'#{plot_data}')]
tooltips = make_tooltips()
hover_tool = HoverTool(tooltips=tooltips)
plot1 = figure(plot_width=800, plot_height=250, tooltips=tooltips, tools='box_select')
plot1.add_tools(hover_tool)
circle = plot1.circle(x='ID', y='plot_data', source=source,
fill_color={"field":'Color', "transform":cmap},
line_color={"field":'Color', "transform":cmap})
def update_plot_data(event):
global plot_data
plot_data = event.item
source.data['plot_data'] = source.data[plot_data]
hover_tool.tooltips = make_tooltips()
dropdown = Dropdown(label='Change Value', menu=["Value1","Value2"])
dropdown.on_click(update_plot_data)
def label_selected_via_index(event):
t0 = time.time()
selected = source.selected.indices
source.data['Label'][0:10] = 'Label was added'
hover_tool.tooltips = make_tooltips()
source.selected.indices = []
print(f"Time needed for label_selected_via_index: {time.time()-t0:.5f}")
button_set_label1 = Button(label='Set Label via Index')
button_set_label1.on_click(label_selected_via_index)
def label_selected_via_patch(event):
t0 = time.time()
selected = source.selected.indices
patches = [(ind, 'Label was added') for ind in selected]
source.patch({'Label': patches})
hover_tool.tooltips = make_tooltips()
source.selected.indices = []
print(f"Time needed for label_selected_via_patch: {time.time()-t0:.5f}")
button_set_label2 = Button(label='Set Label via Patch')
button_set_label2.on_click(label_selected_via_patch)
def label_selected_via_new_col(event):
t0 = time.time()
selected = source.selected.indices
source.data['Label'] = source.data['Label_new_col']
hover_tool.tooltips = make_tooltips()
source.selected.indices = []
print(f"Time needed for label_selected_via_new_col: {time.time()-t0:.5f}")
button_set_label3 = Button(label='Set Label via New Column ')
button_set_label3.on_click(label_selected_via_new_col)
def check_label(event):
print(f"first 10 labels: {[l for l in source.data['Label'][0:10]]}")
button_label_check = Button(label='Check Label')
button_label_check.on_click(check_label)
layout_ = layout([[plot1],
[dropdown],
[button_set_label1 ,button_set_label2, button_set_label3],
[button_label_check]])
curdoc().add_root(layout_)
In my application, I have a lot of data and observed, that using .patch() does take significantly longer than the indexing version or the replacement of a complete column. In my application, the indexing method needs less than a millisecond, while the patch method needs more than one seconds, which makes everything a little bit more laggy when interactively changing values. Basically, my application is somehow similar to the above example regarding the process of selecting samples in one plot and assigning a label via multiple buttons. Those labels are also shown in muliple plots via the tooltip, so this update is necessary for me.
Is there a way to A) Make the indexing version also updating the Hovertool? I prefer this method, because it is visually much faster or B) Make the .patch() version somehow faster?
I hope I could make my problem somehow understandable and be thankful for any suggestions.
In the context of a Bokeh server app, it's worth keeping in mind, "what all actually needs to happen for a change to show up in the browser?" And the answer to that is roughly:
a change is detected (or signaled) in Python
a change event is serialized and sent over the network to a browser
the change event is deserialized by BokehJS
the change is applied and view in the browser is updates
Pretty much Bokeh always handles the last three steps (modulo any actual bugs or TBD features). So the question really boils down to "what are the ways to signal a change" to Bokeh?
Let's start from a position of describing what is available and intended (rather than starting from differences or what is not intended).
Direct Assignment to Properties
The number one, primary way to update a Bokeh object in order see a change in the browser is to assign an entire new value to a Bokeh property. If you do that, e.g. .prop_name = new_value, literally including a "dot" and "equal sign", then Bokeh can auto-magically detect the change and send it to the browser. Here are a few examples:
plot.title.text = "New title" # updates the title
glyph.line_color = "red" # change a glyph's line color
slider.value = 10 # sets a slider's value
The examples above all show basic scalar (string, number) values, but this works just as well for more complicated values. Another extremely common example of this general mechanism is updating the entire .data dict of a ColumnDataSource
source.data = {'x': [...], 'y': [...]} # new data for a glyph or table
That updates all the data in a CDS, so that e.g. a line glyph might re-draw itself.
Depending what you are doing, the size of your data, etc., updating the entire .data dict may be expensive (due to serialization, de-serialization, network transit, etc). So there are some other ways that may be more efficient in specific cases.
"In-place" Special Cases
The distinguishing characteristic above is that everything is a "whole" assignment, i.e. there are not mutating or in-place modifications. In a few cases, Bokeh can auto-magically handle in-place updates to mutable values. Without getting too into the weeds, by far the most important example of this is setting a single new column in a ColumnDataSource by using standard Python dict indexing assignment on .data:
source.data['x'] = [...] # Bokeh will automatically handle this
This is your Third method above. It works fine, but only for updating columns in a CDS .data dict. This method only sends the one new column of data over the wire. As long as you only need to update one or a few columns in a large CDS, it is probably faster than assigning a new whole .data value.
What does NOT work is basically any other kind of mutating, in-place assignment:
source.data['x'][100:200] = [...] # Bokeh does not automatically handle this
This is your First ("index") method above, and it is a non-starter. This kind of usage will not trigger any changes in the browsers.
The TLDR is that wrapping every CDS sequence in some custom class that overrides the standard getitem/setitem machinery just makes common usage too inefficient, and the trade-off cannot be justified. Bokeh will not auto-magically notice or do anything with with mutating assignments like this. (If you are purely in BokehJS JavaScript-side, then you can make in-place assignments like this and then manually call a change.emit() to manually trigger updates, but that is only for the pure JS side of things).
Dedicated APIs for Optimized Cases
Recognizing that sometimes even restricting CDS updates to a single column is still not efficient enough, the patch and stream methods were added to ColumnDataSource.
These methods are for cases like:
I want to append few new values to the end of all my columns, instead of sending all the data again. (e.g for streaming new stock ticker or other sensor data efficiently)
I want to update a few specific values in the middle of my large time series or image, but only send the updated values and not re-send everything else.
This is your Second method and is typically much faster for small updates relative to total data size. As for patch specifically, you can see e.g. the patch_app.py example in the examples folder:
This example updates a three separate scatter, multi-line, and image plots all simultaneously at a 20Hz update rate. The checked-in version has fairly modest data sizes, but I tested it again locally by bumping all the data to 10–100x larger, and it still kept up. If you are seeing something different from patch (i.e. multi-second update times), then a complete Minimal Reproducing Example is needed to actually investigate.

Matplotlib reverse animation

When using animation.FuncAnimation, is it possible to optimally reverse an animation after it plays in forward? i.e. equivalent of
FuncAnimation(.., frames=np.hstack([range(10), range(9)[::-1]]))
This redraws frames in reverse order, eating up drawing computation and memory when 50% of data is exactly the same. FuncAnimation does have a caching mechanism, but does it or any other animation. have a reverse=True? Note all my data is pre-computed and retrieved via simple index for each frame.
Are you looking for a solution within the (interactive?) matplotlib backend or are you writing this animation to file?
The latter is quite a lot simpler, as you could simply use a tool like ffmpeg to revert&append the final gif/movie file. See this answer, for example.
If you need a solution within matplotlib then I guess you'd need to store all your required calculations in separate objects (e.g. create a dictionary like frames = { 0: {"x":0, "y":1, … } } and then tell the FuncAnimation to update with a simple "lookup" function like:
def update(frame):
xdata = frames[frame]["x"]
ydata = frames[frame]["y"]
ln.set_data(xdata, ydata)
return ln,
A third option would be to store your axes as pickle'd object, i.e.:
pickle.dump(ax, file('frame_0.pickle', 'w'))
and then try to re-load those pickle'd frames within FuncAnimation's update call like:
ax = pickle.load(file('frame_0.pickle'))

set_array() in tripcolor bug?

I am new to Python and matplotlib, and I recently referenced to THIS to update my tripcolor plot. With following data preparation
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.tri as tri
import math
r = np.zeros((100,100))
t = np.zeros((100,100))
for i in range(0,100):
for j in range(0,100):
r[i,j]=i
t[i,j]=2*math.pi*j/100
x=r*np.cos(t)
y=r*np.sin(t)
z=r*r
xf=x.flatten()
yf=y.flatten()
zf=z.flatten()
triang = tri.Triangulation(xf,yf)
If I use tripcolor as it is intended,
# Works well
p = plt.tripcolor(triang, zf)
correct figure appears. But, if I try to update after creating tripcolor,
# Not working well
p = plt.tripcolor(triang, xf)
p.set_array(zf)
then, wrong figure appears. Both xf and zf have identical dimensions.
What am I doing wrong? What is the cause of the problem, and how can I avoid it?
Many thanks in advance.
=========================================================
Update
Thank you all. I actually solved myself.
The key was that I need to assign color for each area, which is controlled by shading argument, and default value for tripcolor is 'flat', which is, color for each vertex. So, when I plot the first figure, I need to make sure shading is 'gouraud', which assigns color for each area.
So,
p = plt.tripcolor(triang, xf, shading='gouraud')
p.set_array(zf)
works as I intended.
The reason
p = plt.tripcolor(triang, xf)
p.set_array(zf)
is not working as (may be) expected, is the following. In your case plt.tripcolor() returns a PolyCollection. The PolyCollection's set_array() will essentially set the colors of that Collection. However, the underlying triangles will not be changed, such that you end up with the triangles from xf but the colors from zf.
Since the generation of the tripcolor PolyCollection is quite involved (as it calls Triangulation itself) and there probably is no helper function to set the data externally (at least I am not aware of any), the solution might be not to update the tripcolor at all and instead generate a new one.
Is there any reason for you to update? Couldn't you just directly create p = plt.tripcolor(triang, zf)?
In case there is a real reason to it, like in an animation or so, an option would be to delete the first tripcolor plot before setting up the next.
# create one plot
p = plt.tripcolor(triang, xf)
#delete this plot (you need both lines actually!!)
p.remove()
del p
#create second plot
p = plt.tripcolor(triang, zf)
This is not really efficient, though, and in case someone has a better idea, I'd like to hear about that one as well.

bokeh overlay multiple plot objects in a GridPlot

Say I have a class that holds some data and implements a function that returns a bokeh plot
import bokeh.plotting as bk
class Data():
def plot(self,**kwargs):
# do something to retrieve data
return bk.line(**kwargs)
Now I can instantiate multiple of these Data objects like exps and sets and create individual plots. If bk.hold() is set they'll, end up in one figure (which is basically what I want).
bk.output_notebook()
bk.figure()
bk.hold()
exps.scatter(arg1)
sets.plot(arg2)
bk.show()
Now I want aggregate these plots into a GridPlot() I can do it for the non overlayed single plots
bk.figure()
bk.hold(False)
g=bk.GridPlot(children=[[sets.plot(arg3),sets.plot(arg4)]])
bk.show(g)
but I don't know how I can overlay the scatter plots I had earlier as exps.scatter.
Is there any way to get a reference to the currently active figure like:
rows=[]
exps.scatter(arg1)
sets.plot(arg2)
af = bk.get_reference_to_figure()
rows.append(af) # append the active figure to rows list
bg.figure() # reset figure
gp = bk.GridPlot(children=[rows])
bk.show(gp)
As of Bokeh 0.7 the plotting.py interface has been changed to be more explicit and hopefully this will make things like this simpler and more clear. The basic change is that figure now returns an object, so you can just directly act on those objects without having to wonder what the "currently active" plot is:
p1 = figure(...)
p1.line(...)
p1.circle(...)
p2 = figure(...)
p2.rect(...)
gp = gridplot([p1, p2])
show(gp)
Almost all the previous code should work for now, but hold, curplot etc. are deprecated (and issue deprecation warnings if you run python with deprecation warnings enabled) and will be removed in a future release.
Ok apparently bk.curplot() does the trick
exps.scatter(arg1)
sets.plot(arg2)
p1 = bk.curplot()
bg.figure() # reset figure
exps.scatter(arg3)
sets.plot(arg4)
p2 = bk.curplot()
gp = bk.GridPlot(children=[[p1,p2])
bk.show(gp)

pyQt Matplotlib widget live data updates

Writing in Python 2.7 using pyQt 4.8.5:
How may I update a Matplotlib widget in real time within pyQt?
Currently I'm sampling data (random.gauss for now), appending this and plotting - you can see that I'm clearing the figure each time and re-plotting for each call:
def getData(self):
self.data = random.gauss(10,0.1)
self.ValueTotal.append(self.data)
self.updateData()
def updateData(self):
self.ui.graph.axes.clear()
self.ui.graph.axes.hold(True)
self.ui.graph.axes.plot(self.ValueTotal,'r-')
self.ui.graph.axes.grid()
self.ui.graph.draw()
My GUI works though I think this is the wrong way to achieve this as its highly inefficient, I believe I should use the 'animate call'(?) whilst plotting, though I don't know how.
One idea would be to update only the graphics object after the first plot was done.
axes.plot should return a Line2D object whose x and y-data you can modify:
http://matplotlib.org/api/artist_api.html#matplotlib.lines.Line2D.set_xdata
So, once you have the line plotted, don't delete and plot a new one, but modify the existing:
def updateData(self):
if not hasattr(self, 'line'):
# this should only be executed on the first call to updateData
self.ui.graph.axes.clear()
self.ui.graph.axes.hold(True)
self.line = self.ui.graph.axes.plot(self.ValueTotal,'r-')
self.ui.graph.axes.grid()
else:
# now we only modify the plotted line
self.line.set_xdata(np.arange(len(self.ValueTotal))
self.line.set_ydata(self.ValueTotal)
self.ui.graph.draw()

Categories