Matplotlib imshow, dynamically resample based on zoom - python

I'm trying to replicate the behavior of MATLAB imagesc() call in matplotlib - specifically:
- for very large images, decimate the image
- as the user zooms in, show the image with less decimation.
I've written a class that will do it, but my solution seems overly complex. Does anybody know a better way?
Thanks in advance,
Brian

answer by OP, edited out of the question:
Here's my solution:
The basic idea is:
Catch a xlim_changed or ylim_changed event
Calculate a desired stride based on image size and desired num pixels
Draw
https://github.com/flailingsquirrel/cmake_scipy_ctypes_example/blob/master/src/python/FastImshow.py
#!/usr/bin/env python
'''
Fast Plotter for Large Images - Resamples Images to a target resolution on each zoom.
Example::
sz = (10000,20000) # rows, cols
buf = np.arange(sz[0]*sz[1]).reshape(sz)
extent = (100,150,1000,2000)
fig = plt.figure()
ax = fig.add_subplot(111)
im = FastImshow(buf,extent,ax)
im.show()
plt.show()
'''
import numpy as np
import matplotlib.pyplot as plt
class FastImshow:
'''
Fast plotter for large image buffers
Example::
sz = (10000,20000) # rows, cols
buf = np.arange(sz[0]*sz[1]).reshape(sz)
extent = (100,150,1000,2000)
fig = plt.figure()
ax = fig.add_subplot(111)
im = FastImshow(buf,extent,ax)
im.show()
plt.show()
'''
def __init__(self,buf,ax,extent=None,tgt_res=512):
'''
[in] img buffer
[in] extent
[in] axis to plot on
[in] tgt_res(default=512) : target resolution
'''
self.buf = buf
self.sz = self.buf.shape
self.tgt_res = tgt_res
self.ax = ax
# Members required to account for mapping extent to buf coordinates
if extent:
self.extent = extent
else:
self.extent = [ 0, self.sz[1], 0, self.sz[0] ]
self.startx = self.extent[0]
self.starty = self.extent[2]
self.dx = self.sz[1] / (self.extent[1] - self.startx ) # extent dx
self.dy = self.sz[0] / (self.extent[3] - self.starty ) # extent dy
# end __init__
def get_strides( self,xstart=0, xend=-1, ystart=0, yend=-1, tgt_res=512 ):
'''
Get sampling strides for a given bounding region. If none is provided,
use the full buffer size
'''
# size = (rows,columns)
if xend == -1:
xend = self.sz[1]
if yend == -1:
yend = self.sz[0]
if (xend-xstart) <= self.tgt_res:
stridex = 1
else:
stridex = max(int((xend - xstart) / self.tgt_res),1)
if (yend-ystart) <= self.tgt_res:
stridey = 1
else:
stridey = max(int((yend - ystart) / self.tgt_res),1)
return stridex,stridey
# end get_strides
def ax_update(self, ax):
'''
Event handler for re-plotting on zoom
- gets bounds in img extent coordinates
- converts to buffer coordinates
- calculates appropriate strides
- sets new data in the axis
'''
ax.set_autoscale_on(False) # Otherwise, infinite loop
# Get the range for the new area
xstart, ystart, xdelta, ydelta = ax.viewLim.bounds
xend = xstart + xdelta
yend = ystart + ydelta
xbin_start = int(self.dx * ( xstart - self.startx ))
xbin_end = int(self.dx * ( xend - self.startx ))
ybin_start = int(self.dy * ( ystart - self.starty ))
ybin_end = int(self.dy * ( yend - self.starty ))
# Update the image object with our new data and extent
im = ax.images[-1]
stridex,stridey = self.get_strides( xbin_start,xbin_end,ybin_start,ybin_end)
im.set_data( self.buf[ybin_start:ybin_end:stridey,xbin_start:xbin_end:stridex] )
im.set_extent((xstart, xend, ystart, yend))
ax.figure.canvas.draw_idle()
# end ax_update
def show(self):
'''
Initial plotter for buffer
'''
stridex, stridey = self.get_strides()
self.ax.imshow( buf[::stridex,::stridey],extent=self.extent,origin='lower',aspect='auto' )
self.ax.figure.canvas.draw_idle()
self.ax.callbacks.connect('xlim_changed', self.ax_update)
self.ax.callbacks.connect('ylim_changed', self.ax_update)
# end show
# end ImgDisplay
if __name__=="__main__":
sz = (10000,20000) # rows, cols
buf = np.arange(sz[0]*sz[1]).reshape(sz)
extent = (100,150,1000,2000)
fig = plt.figure()
ax = fig.add_subplot(111)
im = FastImshow(buf,ax,extent=extent,tgt_res=1024)
im.show()
plt.show()

Related

Are there any obvious errors why the S measurements won't switch

In my lab, we're trying to automate a keysight VNA to take measurements of the microwave cavity we're using. We're trying to get readings for S21, S22, and S11. However, when we run the program, the switch from S21 to S11 isn't happening. My job is to debug this, but I can't see any obvious errors. This is the snippet of the code that controls the measurement switch, and I was wondering if you all could take a look and give suggestions/make note of errors. There's also. library that we wrote for this particular instrument, so the error could possibly be in there. Thanks!
# Sweep over vna modes
for mode in mode_list:
vnass.s21_mode()
s21_sweep = vnass.sweep(mode) # Do a sweep with these parameters
fcent = mode[0]
fspan = mode[1]
bandwidth = mode[2]
npoints = int(mode[3])
naverages = mode[4]
power = mode[5]
# Processing Starts here
freq_data = gen.get_frequency_space(fcent, fspan, npoints) # Generate list of frequencies
fig.clf()
ax = fig.add_subplot(111)
ax.set_title("ato_pos = %.1f, f = %.3f GHz" % (ato_pos, fcent / 1e9), fontsize=16)
ax.plot(freq_data / 1e9, gen.complex_to_dB(s21_sweep), "g")
ax.set_ylabel(r'$S_{21}$ [dB]')
ax.set_xlabel('Frequency [GHz]')
plt.axis('tight')
plt.draw()
plt.pause(0.1)
if list(mode_list).index(mode) == 0:
s21_data = np.transpose(s21_sweep)
else:
s21_data = np.vstack((s21_data, np.transpose(s21_sweep)[1:]))
vnass.s11_mode()
s11_sweep = vnass.sweep(mode) # Do a sweep with these parameters
if list(mode_list).index(mode) == 0:
s11_data = np.transpose(s11_sweep)
else:
s11_data = np.vstack((s11_data, np.transpose(s11_sweep)[1:]))
vnass.s22_mode()
s22_sweep = vnass.sweep(mode) # Do a sweep with these parameters
if list(mode_list).index(mode) == 0:
s22_data = np.transpose(s22_sweep)
else:
s22_data = np.vstack((s22_data, np.transpose(s22_sweep)[1:]))
#t = datetime.now(timezone('Australia/Perth')).strftime(fmt)
with h5py.File(filepath / p(exp_name + '.hdf5'), 'a') as f:
try:
if f[str(ato_pos)]:
del (f[str(ato_pos)])
except:
None
full_freq = np.linspace(mode_list[0][0] - fspan // 2, fcent + fspan // 2,
s21_data.shape[0]) # freq list in Hz
dset_s21 = f.create_dataset(str(ato_pos)+'_s21', data=s21_data, compression='gzip', compression_opts=6) # VNA dset
dset_s11 = f.create_dataset(str(ato_pos)+ '_s11', data=s11_data, compression='gzip', compression_opts=6)
dset_s22 = f.create_dataset(str(ato_pos)+ '_s22', data=s22_data, compression='gzip', compression_opts=6) # VNA dset
# VNA dset
try:
f['Freq']
except:
fdset = f.create_dataset('Freq', data=full_freq, compression='gzip', compression_opts=6)
fdset.attrs['f_start'] = mode_list[0][0] # this is from the mode map / next freq
fdset.attrs['f_final'] = fcent
fdset.attrs['vna_pow'] = power
fdset.attrs['vna_span'] = fspan
fdset.attrs['vna_pts'] = npoints
fdset.attrs['vna_ave'] = naverages
fdset.attrs['vna_rbw'] = fspan / (npoints - 1)
fdset.attrs['vna_ifb'] = bandwidth
fdset.attrs['nmodes'] = mode_list.shape[0]
#fdset.attrs['ato_voltage'] = setVoltage['x']
#fdset.attrs['ato_freq'] = setFreq['x']
fdset.attrs['ato_step'] = ato_step
fdset.attrs['total_steps'] = total_steps
dset_s21.attrs['ato_pos'] = ato_pos
#dset.attrs['temp'] = temperature
#dset.attrs['time'] = t
if idx % 5 == 0 and idx != 0:
fig1.clf()
ax1 = fig1.add_subplot(111)
mag_data_db, freq, ato_positions = ato_hdf5_parser(filepath / p(exp_name + '.hdf5'))
phi = ato_positions // ato_step
colour = ax1.imshow(mag_data_db, extent=[phi[0], phi[-1], freq[0], freq[-1]],
aspect=(0.8 * (phi[-1] - phi[0]) / (freq[-1] - freq[0])),
cmap=plt.cm.get_cmap('viridis'), origin='lower', norm=Normalize(vmin=db_min, vmax=db_max))
ax1.set_xlabel(r'Phi (Steps)')
ax1.set_ylabel(r'Frequency (GHz)')
cb = fig1.colorbar(colour, ax=ax1, fraction=0.0325, pad=0.04)
cb.set_label('$|S_{21}|$ [dB]')
cm.ScalarMappable()
plt.title(exp_name)
plt.draw()

Python: Animating two lists of lines using matplotlib.animation but only shows one set of lines at a time

Trying to plot persuit curves with spiraling in lines and a shrinking, rotating polygon with corners at each of the current points
problem = can't get both line of sight lines and main lines to simultaneously plot
The figure flicks back and forth between the shrinking polygon(described by SightLine) and the main persuit curves (MainLines)
When individually animated one at a time, the polygon and pursuit curves plot fine but I just can't get them to work together on the same figure.
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
%matplotlib notebook
plt.style.use('dark_background')
NumOfPoints = 6
deltaT = 0.005
duration = 50
steps = int(duration / deltaT)
speed = 0.2
num = 0
CurrentXPoints = []
CurrentYPoints = []
DeltaX = np.zeros(NumOfPoints)
DeltaY = np.zeros(NumOfPoints)
MagnitudeDelta = np.zeros(NumOfPoints)
VelocityX = np.zeros(NumOfPoints)
VelocityY = np.zeros(NumOfPoints)
#Creates Initial Points by equally spacing the points around a polygon inscribed around circle
for i in range(0,NumOfPoints):
x = np.cos(((i/NumOfPoints)*2)*np.pi)
y = np.sin(((i/NumOfPoints)*2)*np.pi)
CurrentXPoints.append(x)
CurrentYPoints.append(y)
AllXPoints = np.array([CurrentXPoints])
AllYPoints = np.array([CurrentYPoints])
#Fills out both AllXPoints and AllYPoints with all points in duration
for i in range(int(steps)):
for j in range(0,NumOfPoints-1): #Calculates deltaX and deltaY at this timestep
DeltaX[j] = CurrentXPoints[j+1] - CurrentXPoints[j]
DeltaY[j] = CurrentYPoints[j+1] - CurrentYPoints[j]
DeltaX[NumOfPoints-1] = CurrentXPoints[0] - CurrentXPoints[NumOfPoints-1]
DeltaY[NumOfPoints-1] = CurrentYPoints[0] - CurrentYPoints[NumOfPoints-1]
for j in range(0,NumOfPoints): # calculats new X and Y Points
MagnitudeDelta[j] = ((DeltaX[j])**2 + (DeltaY[j])**2)**(1/2)
VelocityX[j] = speed * (DeltaX[j]/MagnitudeDelta[j])
VelocityY[j] = speed * (DeltaY[j]/MagnitudeDelta[j])
CurrentXPoints[j] += deltaT * VelocityX[j]
CurrentYPoints[j] += deltaT * VelocityY[j]
CurrentXPointsArr = np.array(CurrentXPoints)
CurrentYPointsArr = np.array(CurrentYPoints)
AllXPoints = np.vstack((AllXPoints,CurrentXPointsArr))
AllYPoints = np.vstack((AllYPoints,CurrentYPointsArr))
fig = plt.figure(figsize=(5,5))
ax = plt.axes()
ax.set_xlim(-2,2)
ax.set_ylim(-2,2)
ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_visible(False)
MainLines = []
SightLines= []
AllLines = MainLines + SightLines
for i in range(NumOfPoints):
line, = ax.plot([AllXPoints[j][i] for j in range(steps)], [AllYPoints[j][i] for j in range(steps)])
MainLines.append(line)
SightLines.append(line)
def UpdateMain(num, AllXPoints, AllYPoints, MainLines):
for line in MainLines:
position = MainLines.index(line)
line.set_data([AllXPoints[i][position] for i in range(num)], [AllYPoints[i][position] for i in range(num)])
def UpdateSight(num, AllXPoints, AllYPoints, SightLines):
for line in SightLines:
position = SightLines.index(line)
if position < (NumOfPoints-1):
line.set_data([AllXPoints[num][position],AllXPoints[num][position+1]],
[AllYPoints[num][position],AllYPoints[num][position+1]])
else:
line.set_data([AllXPoints[num][position],AllXPoints[num][0]],
[AllYPoints[num][position],AllYPoints[num][0]])
ani1 = animation.FuncAnimation(fig, UpdateMain,steps, fargs=[AllXPoints, AllYPoints, MainLines],
interval=1, blit=True)
ani2 = animation.FuncAnimation(fig, UpdateSight,steps, fargs=[AllXPoints, AllYPoints, SightLines],
interval=1, blit=True)
plt.show()
First, you should use only one FuncAnimation that updates all the artists.
The main problem of your code are the lines
for i in range(NumOfPoints):
line, = ax.plot([AllXPoints[j][i] for j in range(steps)], [AllYPoints[j][i] for j in range(steps)])
MainLines.append(line)
SightLines.append(line)
where you are creating one artist (line) and assign it to two different lists. If you create 2 different lines for each list, then the output is as expected.
Full working code:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
%matplotlib notebook
plt.style.use('dark_background')
NumOfPoints = 6
deltaT = 0.005
duration = 50
steps = int(duration / deltaT)
speed = 0.2
num = 0
CurrentXPoints = []
CurrentYPoints = []
DeltaX = np.zeros(NumOfPoints)
DeltaY = np.zeros(NumOfPoints)
MagnitudeDelta = np.zeros(NumOfPoints)
VelocityX = np.zeros(NumOfPoints)
VelocityY = np.zeros(NumOfPoints)
def update(num, AllXPoints, AllYPoints, MainLines, SightLines):
out = []
out.append(UpdateMain(num, AllXPoints, AllYPoints, MainLines))
out.append(UpdateSight(num, AllXPoints, AllYPoints, SightLines))
return out
def UpdateMain(num, AllXPoints, AllYPoints, MainLines):
for line in MainLines:
position = MainLines.index(line)
line.set_data([AllXPoints[i][position] for i in range(num)], [AllYPoints[i][position] for i in range(num)])
return MainLines
def UpdateSight(num, AllXPoints, AllYPoints, SightLines):
for line in SightLines:
position = SightLines.index(line)
if position < (NumOfPoints-1):
line.set_data([AllXPoints[num][position],AllXPoints[num][position+1]],
[AllYPoints[num][position],AllYPoints[num][position+1]])
else:
line.set_data([AllXPoints[num][position],AllXPoints[num][0]],
[AllYPoints[num][position],AllYPoints[num][0]])
return SightLines
#Creates Initial Points by equally spacing the points around a polygon inscribed around circle
for i in range(0,NumOfPoints):
x = np.cos(((i/NumOfPoints)*2)*np.pi)
y = np.sin(((i/NumOfPoints)*2)*np.pi)
CurrentXPoints.append(x)
CurrentYPoints.append(y)
AllXPoints = np.array([CurrentXPoints])
AllYPoints = np.array([CurrentYPoints])
#Fills out both AllXPoints and AllYPoints with all points in duration
for i in range(int(steps)):
for j in range(0,NumOfPoints-1): #Calculates deltaX and deltaY at this timestep
DeltaX[j] = CurrentXPoints[j+1] - CurrentXPoints[j]
DeltaY[j] = CurrentYPoints[j+1] - CurrentYPoints[j]
DeltaX[NumOfPoints-1] = CurrentXPoints[0] - CurrentXPoints[NumOfPoints-1]
DeltaY[NumOfPoints-1] = CurrentYPoints[0] - CurrentYPoints[NumOfPoints-1]
for j in range(0,NumOfPoints): # calculats new X and Y Points
MagnitudeDelta[j] = ((DeltaX[j])**2 + (DeltaY[j])**2)**(1/2)
VelocityX[j] = speed * (DeltaX[j]/MagnitudeDelta[j])
VelocityY[j] = speed * (DeltaY[j]/MagnitudeDelta[j])
CurrentXPoints[j] += deltaT * VelocityX[j]
CurrentYPoints[j] += deltaT * VelocityY[j]
CurrentXPointsArr = np.array(CurrentXPoints)
CurrentYPointsArr = np.array(CurrentYPoints)
AllXPoints = np.vstack((AllXPoints,CurrentXPointsArr))
AllYPoints = np.vstack((AllYPoints,CurrentYPointsArr))
fig = plt.figure(figsize=(5,5))
ax = plt.axes()
ax.set_xlim(-2,2)
ax.set_ylim(-2,2)
ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_visible(False)
MainLines = []
SightLines= []
AllLines = MainLines + SightLines
for i in range(NumOfPoints):
line1, = ax.plot([AllXPoints[j][i] for j in range(steps)], [AllYPoints[j][i] for j in range(steps)])
line2, = ax.plot([AllXPoints[j][i] for j in range(steps)], [AllYPoints[j][i] for j in range(steps)])
MainLines.append(line1)
SightLines.append(line2)
ani = animation.FuncAnimation(fig, update, steps, fargs=[AllXPoints, AllYPoints, MainLines, SightLines], interval=1, blit=True)
plt.show()

Fixing Python code that visualizes audio input

I found some code online that visualizes audio input into a graph. I have been working on it for a while but I keep getting different errors. If anyone could find the time to have a look at it and help me to get it to work it would be much appreciated.
import struct
import wave
import matplotlib.animation as animation
import matplotlib.pyplot as plt
import numpy as np
import pyaudio
SAVE = 0.0
TITLE = ''
WIDTH = 1280
HEIGHT = 720
FPS = 25.0
nFFT = 512
BUF_SIZE = 4 * nFFT
FORMAT = pyaudio.paInt16
CHANNELS = 2
RATE = 44100
def animate(i, line, stream, wf, MAX_y):
# Read n*nFFT frames from stream, n > 0
N = max(stream.get_read_available() / nFFT, 1) * nFFT
data = stream.read(N)
if SAVE:
wf.writeframes(data)
# Unpack data, LRLRLR...
y = np.array(struct.unpack("%dh" % (N * CHANNELS), data)) / MAX_y
y_L = y[::2]
y_R = y[1::2]
Y_L = np.fft.fft(y_L, nFFT)
Y_R = np.fft.fft(y_R, nFFT)
# Sewing FFT of two channels together, DC part uses right channel's
Y = abs(np.hstack((Y_L[-nFFT / 2:-1], Y_R[:nFFT / 2])))
line.set_ydata(Y)
return line,
def init(line):
# This data is a clear frame for animation
line.set_ydata(np.zeros(nFFT - 1))
return line,
def main():
dpi = plt.rcParams['figure.dpi']
plt.rcParams['savefig.dpi'] = dpi
plt.rcParams["figure.figsize"] = (1.0 * WIDTH / dpi, 1.0 * HEIGHT / dpi)
fig = plt.figure()
# Frequency range
x_f = 1.0 * np.arange(-nFFT / 2 + 1, nFFT / 2) / nFFT * RATE
ax = fig.add_subplot(111, title=TITLE, xlim=(x_f[0], x_f[-1]),
ylim=(0, 2 * np.pi * nFFT ** 2 / RATE))
ax.set_yscale('symlog', linthreshy=nFFT ** 0.5)
line, = ax.plot(x_f, np.zeros(nFFT - 1))
# Change x tick labels for left channel
def change_xlabel(evt):
labels = [label.get_text().replace(u'\u2212', '')
for label in ax.get_xticklabels()]
ax.set_xticklabels(labels)
fig.canvas.mpl_disconnect(drawid)
drawid = fig.canvas.mpl_connect('draw_event', change_xlabel)
p = pyaudio.PyAudio()
# Used for normalizing signal. If use paFloat32, then it's already -1..1.
# Because of saving wave, paInt16 will be easier.
MAX_y = 2.0 ** (p.get_sample_size(FORMAT) * 8 - 1)
frames = None
wf = None
if SAVE:
frames = int(FPS * SAVE)
wf = wave.open('temp.wav', 'wb')
wf.setnchannels(CHANNELS)
wf.setsampwidth(p.get_sample_size(FORMAT))
wf.setframerate(RATE)
stream = p.open(format=FORMAT,
channels=CHANNELS,
rate=RATE,
input=True,
frames_per_buffer=BUF_SIZE)
ani = animation.FuncAnimation(
fig, animate, frames,
init_func=lambda: init(line), fargs=(line, stream, wf, MAX_y),
interval=1000.0 / FPS, blit=True
)
if SAVE:
ani.save('temp.mp4', fps=FPS)
else:
plt.show()
stream.stop_stream()
stream.close()
p.terminate()
if SAVE:
wf.close()
if __name__ == '__main__':
main()
The error is:
File "C:\Users\Tonif\Documents\computer science\sound.py", line 26,
in animate data = stream.read(N)
TypeError: integer argument expected, got float

Python -- Matplotlib user input from mouse for plotting

This class plots a curve. However, the inputs are currently set in main(). I'd like to set them as user-driven from mouse interaction. Some of this is possible and in the Matplotlib docs (see referenced sites below) but it's still not really setting it up to be a 'click and plot'. So, ideally the user would click a button to set the P and then whatever point (on the curve, has to be on the curve) they clicked next would be the new P. Same with Q. I'm sure this is a very simple question for anyone who's used Matplotlib but I'm teaching myself it right now, but it would probably take an entry-level dev just a few minutes to do something that I'm getting nowhere with.
Code:
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.axes_grid.axislines import SubplotZero
from math import sqrt
class ECC123(object):
def __init__(self,a,b,px,qx,qy):
self.a = a
self.b = b
self.pxlam = px
self.qxlam = qx
self.invertQy = qy
self.fig = plt.figure(1)
self.ax = SubplotZero(self.fig, 111)
def drawAxis(self):
#fig = plt.figure(1)
#ax = SubplotZero(fig, 111)
self.fig.add_subplot(self.ax)
for direction in ["xzero", "yzero"]:
self.ax.axis[direction].set_axisline_style("->")
self.ax.axis[direction].set_visible(True)
def plotGraph(self):
self.drawAxis()
y, x = np.ogrid[-10:10:100j, -10:10:100j] # range grid [from : to : how_many_points]
xlist = x.ravel(); ylist = y.ravel()
plt.contour(xlist, ylist, self.elliptic_curve(x,y), [0])
pylam = self.ecclambda(self.pxlam,self.a,self.b) # calculate P from pxlam
qylam = self.ecclambda(self.qxlam,self.a,self.b) # calculate Q from qxlam
if self.invertQy == 1: qylam = -qylam # optional, inverts qy to negative on the plot
plt.plot([self.pxlam,self.qxlam], [pylam,qylam], color = "c", linewidth=1)
plt.plot([self.pxlam], [pylam], "mo"); plt.plot([self.qxlam], [qylam], "mo")
plt.text(self.pxlam-0.25,pylam+0.5, '$P$'); plt.text(self.qxlam-0.25,self.qxlam+0.5, '$Q$')
s = (pylam - qylam)/(self.pxlam - self.qxlam) # calculate s slope
xr = s**2 - self.pxlam - self.qxlam # x-value of R
yr = pylam + s*(xr - self.pxlam) # y-value of -R; -y is R (inverted across x-axis)
plt.plot([xr],[yr],"mo")
plt.plot([xr],[-yr],"co")
plt.plot([self.qxlam,xr], [qylam,yr], color = "c", linewidth=1)
plt.plot([xr,xr], [yr,-yr], "x--")
plt.text(xr+0.25,yr, '$-R$'); plt.text(xr+0.25,-yr, '$R$')
plt.grid(True)
plt.show()
I've been going over the docs in Matplotlib, the scipy cookbook, and related questions here on SO and still not seeing exactly how to do this:
http://matplotlib.org/users/event_handling.html
http://matplotlib.org/1.3.1/api/widgets_api.html#matplotlib.widgets.Button.on_clicked
Cursors for data selection in matplotlib
How can I create a frontend for matplotlib?
http://wiki.scipy.org/Cookbook/Matplotlib
So far, I'm getting little red x's all over when I click and they don't even fall within the curve.
I modified your code a little, so that you can set location of P & Q by left & right click, I didn't accomplish all the graph data updates, the rest is left for you:
from mpl_toolkits.axes_grid.axislines import SubplotZero
import numpy as np
import matplotlib.pyplot as plt
from math import sqrt
class ECC(object):
"""
class to implement elliptic curve and find P+Q=R on the plot
"""
def __init__(self,a,b,px,qx,qy):
"""
initialize input variables
"""
self.a = a
self.b = b
self.pxlam = px
self.qxlam = qx
self.invertQy = qy
self.fig = plt.figure(1)
self.ax = SubplotZero(self.fig, 111)
def drawAxis(self):
"""
draw main x,y axis
"""
#fig = plt.figure(1)
#ax = SubplotZero(fig, 111)
self.fig.add_subplot(self.ax)
for direction in ["xzero", "yzero"]:
self.ax.axis[direction].set_axisline_style("->")
self.ax.axis[direction].set_visible(True)
def ecclambda(self,xl,a,b):
"""
returns points elliptic curve for P and Q
y**2 = x**3 + a*x + b
"""
return sqrt(xl**3 + a*xl + b)
def elliptic_curve(self,x,y):
"""
takes in x,y as set of points, returns the elliptic curve
y**2 = x**3 + a*x + b
"""
return pow(y, 2) - pow(x, 3) - x * self.a - self.b
def onclick(self, event):
x = event.xdata
if event.button == 1:
self.pxlam = x
if event.button == 3:
self.qxlam = x
self.update()
def update(self):
pylam = self.ecclambda(self.pxlam,self.a,self.b) # calculate P from pxlam
qylam = self.ecclambda(self.qxlam,self.a,self.b) # calculate Q from qxlam
self.p.set_data([self.pxlam], [pylam])
self.q.set_data([self.qxlam], [qylam])
self.pt.set_x(self.pxlam-0.25)
self.pt.set_y(pylam+0.5)
self.qt.set_x(self.qxlam-0.25)
self.qt.set_y(qylam+0.5)
plt.gcf().canvas.draw()
def plotGraph(self):
"""
main plotting of elliptic curve and points/line for P+Q=R
P+Q=R --->>> -R is plotted (xr,yr), R is plotted (xr, -yr)
conditional with invertQy allows inversion of Q across x-axis; set option in main()
"""
self.drawAxis()
y, x = np.ogrid[-10:10:100j, -10:10:100j] # range grid [from : to : how_many_points]
xlist = x.ravel(); ylist = y.ravel()
plt.contour(xlist, ylist, self.elliptic_curve(x,y), [0])
pylam = self.ecclambda(self.pxlam,self.a,self.b) # calculate P from pxlam
qylam = self.ecclambda(self.qxlam,self.a,self.b) # calculate Q from qxlam
if self.invertQy == 1: qylam = -qylam # optional, inverts qy to negative on the plot
plt.plot([self.pxlam,self.qxlam], [pylam,qylam], color = "c", linewidth=1)
self.p = plt.plot([self.pxlam], [pylam], "mo")[0]
self.q = plt.plot([self.qxlam], [qylam], "mo")[0]
self.pt = plt.text(self.pxlam-0.25,pylam+0.5, '$P$')
self.qt = plt.text(self.qxlam-0.25,self.qxlam+0.5, '$Q$')
s = (pylam - qylam)/(self.pxlam - self.qxlam) # calculate s slope
xr = s**2 - self.pxlam - self.qxlam # x-value of R
yr = pylam + s*(xr - self.pxlam) # y-value of -R; -y is R (inverted across x-axis)
plt.plot([xr],[yr],"mo")
plt.plot([xr],[-yr],"co")
plt.plot([self.qxlam,xr], [qylam,yr], color = "c", linewidth=1)
plt.plot([xr,xr], [yr,-yr], "x--")
plt.text(xr+0.25,yr, '$-R$'); plt.text(xr+0.25,-yr, '$R$')
plt.text(-9,6,' P: (%s ,%s) \n Q: (%s ,%s) \n R: (%s ,%s) \n a: %s \n b: %s '
%(self.pxlam,pylam,self.qxlam,qylam,xr,-yr,self.a,self.b),
fontsize=10, color = 'blue',bbox=dict(facecolor='tan', alpha=0.5))
plt.title(r"Elliptic Curve Implementation $y^{2} = x^{3} + a*x + b$", fontsize = 16, color = 'b')
self.fig.canvas.mpl_connect('button_press_event', self.onclick)
#[xi,yi] = plt.ginput(0)
##print "ginput ",xi,yi
plt.grid(True)
plt.show()
def main():
a = -2; b = 1; px = -1.55; qx = -0.1
invertQy = 0 # set to 1 if q should be inverted to negative along its y axis
ec = ECC(a,b,px,qx,invertQy)
ec.plotGraph()
if __name__ == '__main__':
main()

Creating a tiled map with blender

I'm looking at creating map tiles based on a 3D model made in blender,
The map is 16 x 16 in blender.
I've got 4 different zoom levels and each tile is 100 x 100 pixels. The entire map at the most zoomed out level is 4 x 4 tiles constructing an image of 400 x 400.
The most zoomed in level is 256 x 256 obviously constructing an image of 25600 x 25600
What I need is a script for blender that can create the tiles from the model.
I've never written in python before so I've been trying to adapt a couple of the scripts which are already there.
So far I've come up with a script, but it doesn't work very well. I'm having real difficulties getting the tiles to line up seamlessly. I'm not too concerned about changing the height of the camera as I can always create the same zoomed out tiles at 6400 x 6400 images and split the resulting images into the correct tiles.
Here is what I've got so far...
#!BPY
"""
Name: 'Export Map Tiles'
Blender: '242'
Group: 'Export'
Tip: 'Export to Map'
"""
import Blender
from Blender import Scene,sys
from Blender.Scene import Render
def init():
thumbsize = 200
CameraHeight = 4.4
YStart = -8
YMove = 4
XStart = -8
XMove = 4
ZoomLevel = 1
Path = "/Images/Map/"
Blender.drawmap = [thumbsize,CameraHeight,YStart,YMove,XStart,XMove,ZoomLevel,Path]
def show_prefs():
buttonthumbsize = Blender.Draw.Create(Blender.drawmap[0]);
buttonCameraHeight = Blender.Draw.Create(Blender.drawmap[1])
buttonYStart = Blender.Draw.Create(Blender.drawmap[2])
buttonYMove = Blender.Draw.Create(Blender.drawmap[3])
buttonXStart = Blender.Draw.Create(Blender.drawmap[4])
buttonXMove = Blender.Draw.Create(Blender.drawmap[5])
buttonZoomLevel = Blender.Draw.Create(Blender.drawmap[6])
buttonPath = Blender.Draw.Create(Blender.drawmap[7])
block = []
block.append(("Image Size", buttonthumbsize, 0, 500))
block.append(("Camera Height", buttonCameraHeight, -0, 10))
block.append(("Y Start", buttonYStart, -10, 10))
block.append(("Y Move", buttonYMove, 0, 5))
block.append(("X Start", buttonXStart,-10, 10))
block.append(("X Move", buttonXMove, 0, 5))
block.append(("Zoom Level", buttonZoomLevel, 1, 10))
block.append(("Export Path", buttonPath,0,200,"The Path to save the tiles"))
retval = Blender.Draw.PupBlock("Draw Map: Preferences" , block)
if retval:
Blender.drawmap[0] = buttonthumbsize.val
Blender.drawmap[1] = buttonCameraHeight.val
Blender.drawmap[2] = buttonYStart.val
Blender.drawmap[3] = buttonYMove.val
Blender.drawmap[4] = buttonXStart.val
Blender.drawmap[5] = buttonXMove.val
Blender.drawmap[6] = buttonZoomLevel.val
Blender.drawmap[7] = buttonPath.val
Export()
def Export():
scn = Scene.GetCurrent()
context = scn.getRenderingContext()
def cutStr(str): #cut off path leaving name
c = str.find("\\")
while c != -1:
c = c + 1
str = str[c:]
c = str.find("\\")
str = str[:-6]
return str
#variables from gui:
thumbsize,CameraHeight,YStart,YMove,XStart,XMove,ZoomLevel,Path = Blender.drawmap
XMove = XMove / ZoomLevel
YMove = YMove / ZoomLevel
Camera = Scene.GetCurrent().getCurrentCamera()
Camera.LocZ = CameraHeight / ZoomLevel
YStart = YStart + (YMove / 2)
XStart = XStart + (XMove / 2)
#Point it straight down
Camera.RotX = 0
Camera.RotY = 0
Camera.RotZ = 0
TileCount = 4**ZoomLevel
#Because the first thing we do is move the camera, start it off the map
Camera.LocY = YStart - YMove
for i in range(0,TileCount):
Camera.LocY = Camera.LocY + YMove
Camera.LocX = XStart - XMove
for j in range(0,TileCount):
Camera.LocX = Camera.LocX + XMove
Render.EnableDispWin()
context.extensions = True
context.renderPath = Path
#setting thumbsize
context.imageSizeX(thumbsize)
context.imageSizeY(thumbsize)
#could be put into a gui.
context.imageType = Render.PNG
context.enableOversampling(0)
#render
context.render()
#save image
ZasString = '%s' %(int(ZoomLevel))
XasString = '%s' %(int(j+1))
YasString = '%s' %(int((3-i)+1))
context.saveRenderedImage("Z" + ZasString + "X" + XasString + "Y" + YasString)
#close the windows
Render.CloseRenderWindow()
try:
type(Blender.drawmap)
except:
#print 'initialize extern variables'
init()
show_prefs()
This was relatively simple in the end.
I scaled up the model so that 1 tile on the map was 1 grid in blender.
Set the camera to be orthographic.
Set the scale on the camera to 1 for the highest zoom, 4 for the next one, 16 for the next one and so on.
Updated the start coordinates and move values accordingly.

Categories

Resources