Related
Through this code, I aim to detect an object in real-time that will be put in front of the video camera and classify it. My reasoning is the following I tried to make two for loops the first one for the detection, and once the object is detected I want to apply the classification through the second for loop. I don't know if my reasoning is correct or not, I tested the code but I received this error
ValueError Traceback (most recent call last)
<ipython-input-1-88a18bf89e71> in <module>()
85 for obj_coordinates in objs:
---> 87 x1, x2, y1, y2 = apply_offsets(obj_coordinates, class_offsets)
88 gray_obj = gray_obj[y1:y2, x1:x2]
89 try:
/home/nada/Desktop/testforimage/src/utils/inference.pyc in apply_offsets(obj_coordinates, offsets)
25
26 def apply_offsets(obj_coordinates, offsets):
---> 27 x, y, width, height = obj_coordinates
28 x_off, y_off = offsets
29 return (x - x_off, x + width + x_off, y - y_off, y + height + y_off)
ValueError: too many values to unpack
Could you please correct the following code and tell me if my reasoning is correct or not and thank you in advance.
video_capture = cv2.VideoCapture(0)
if video_capture.isOpened():
frame = video_capture.read()
else:
rval = False
while True:
rval, frame = video_capture.read()
gray_image = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
gray_image = cv2.cvtColor(np.float32(imgUMat), cv2.COLOR_RGB2GRAY)
blur = cv2.GaussianBlur(gray_image, (5,5) , 0)
ctrs = cv2.findContours(blur.copy(),cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
rects = [cv2.boundingRect(ctr) for ctr in ctrs]
for coordinates in rects:
a1, a2, b1, b2 = app_offsets(coordinates, obj_offsets)
gray_image = gray_image[b1:b2, a1:a2]
try:
gray_image = cv2.resize(gray_image, (obj_target_size))
except:
continue
gray_image = preprocess_input(gray_image, True)
gray_image = np.expand_dims(gray_image, 0)
gray_image = np.expand_dims(gray_image, -1)
objs = obj_detection.predict(gray_image)
key = cv2.waitKey(1)
b,g,r = cv2.split(frame) # get b,g,r
rgb_img = cv2.merge([r,g,b]) # switch it to rgb
for obj_coordinates in objs:
x1, x2, y1, y2 = apply_offsets(obj_coordinates, class_offsets)
gray_obj = gray_obj[y1:y2, x1:x2]
try:
gray_obj = cv2.resize(gray_obj, (class_target_size))
except:
continue
gray_obj = preprocess_input(gray_obj, True)
gray_obj = np.expand_dims(gray_obj, 0)
gray_obj = np.expand_dims(gray_obj, -1)
class_prediction = class_classifier.predict(gray_obj)
class_probability = np.max(class_prediction)
class_label_arg = np.argmax(class_prediction)
class_text = emotion_labels[class_label_arg]
class_window.append(class_text)
In line 20 ctrs = cv2.findContours(blur.copy(),cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE), the function returns the contours and its hierarchy.
To draw the bounding box for each contour, you need to pass the first output (contours)
Change the line to the following:
ctrs = cv2.findContours(blur.copy(),cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)[0]
It is your obj_coordinates that does not seem to be a 4-uple. It is an element of objs produced by obj_detection.predict(gray_image). The code context you shared to us is insufficient to tell what is wrong in that function.
I am trying to write my own custom loss function that is based on the false positive and negative rates. I made a dummy code so you can check the first 2 defenitions as well. I added the rest, so you can see how it is implemented. However, still somewhere the gradient turns out to be zero. What is now the step where the gradient turns zero, or how can I check this? Please I would like to know how I can fix this :).
I tried providing you with more information so you can play around as well, but if you miss anything please do let me know!
The gradient stays True during every step. However, still during the training of the model the loss is not updated, therefore the NN does not train.
y = Variable(torch.tensor((0, 0, 0, 1, 1,1), dtype=torch.float), requires_grad = True)
y_pred = Variable(torch.tensor((0.333, 0.2, 0.01, 0.99, 0.49, 0.51), dtype=torch.float), requires_grad = True)
x = Variable(torch.tensor((0, 0, 0, 1, 1,1), dtype=torch.float), requires_grad = True)
x_pred = Variable(torch.tensor((0.55, 0.25, 0.01, 0.99, 0.65, 0.51), dtype=torch.float), requires_grad = True)
def binary_y_pred(y_pred):
y_pred.register_hook(lambda grad: print(grad))
y_pred = y_pred+torch.tensor(0.5, requires_grad=True, dtype=torch.float)
y_pred = y_pred.pow(5) # this is my way working around using torch.where()
y_pred = y_pred.pow(10)
y_pred = y_pred.pow(15)
m = nn.Sigmoid()
y_pred = m(y_pred)
y_pred = y_pred-torch.tensor(0.5, requires_grad=True, dtype=torch.float)
y_pred = y_pred*2
y_pred.register_hook(lambda grad: print(grad))
return y_pred
def confusion_matrix(y_pred, y):
TP = torch.sum(y*y_pred)
TN = torch.sum((1-y)*(1-y_pred))
FP = torch.sum((1-y)*y_pred)
FN = torch.sum(y*(1-y_pred))
k_eps = torch.tensor(1e-12, requires_grad=True, dtype=torch.float)
FN_rate = FN/(TP + FN + k_eps)
FP_rate = FP/(TN + FP + k_eps)
return FN_rate, FP_rate
def dif_rate(FN_rate_y, FN_rate_x):
dif = (FN_rate_y - FN_rate_x).pow(2)
return dif
def custom_loss_function(y_pred, y, x_pred, x):
y_pred = binary_y_pred(y_pred)
FN_rate_y, FP_rate_y = confusion_matrix(y_pred, y)
x_pred= binary_y_pred(x_pred)
FN_rate_x, FP_rate_x = confusion_matrix(x_pred, x)
FN_dif = dif_rate(FN_rate_y, FN_rate_x)
FP_dif = dif_rate(FP_rate_y, FP_rate_x)
cost = FN_dif+FP_dif
return cost
# I added the rest so you can see how it is implemented, but this peace does not fully run well! If you want this part to run as well, I can add more code.
class FeedforwardNeuralNetModel(nn.Module):
def __init__(self, input_dim, hidden_dim, output_dim):
super(FeedforwardNeuralNetModel, self).__init__()
self.fc1 = nn.Linear(input_dim, hidden_dim)
self.relu1 = nn.ReLU()
self.fc2 = nn.Linear(hidden_dim, output_dim)
self.sigmoid = nn.Sigmoid()
def forward(self, x):
out = self.fc1(x)
out = self.relu1(out)
out = self.fc2(out)
out = self.sigmoid(out)
return out
model = FeedforwardNeuralNetModel(input_dim, hidden_dim, output_dim)
optimizer = torch.optim.Adam(model.parameters(), lr=0.0001, betas=[0.9, 0.99], amsgrad=True)
criterion = torch.nn.BCELoss(weight=None, size_average=None, reduce=None, reduction='mean')
for epoch in range(num_epochs):
train_err = 0
for i, (samples, truths) in enumerate(train_loader):
samples = Variable(samples)
truths = Variable(truths)
optimizer.zero_grad() # Reset gradients
outputs = model(samples) # Do the forward pass
loss2 = criterion(outputs, truths) # Calculate loss
samples_y = Variable(samples_y)
samples_x = Variable(samples_x)
y_pred = model(samples_y)
y = Variable(y, requires_grad=True)
x_pred = model(samples_x)
x= Variable(x, requires_grad=True)
cost = custom_loss_function(y_pred, y, x_pred, x)
loss = loss2*0+cost #checking only if cost works.
loss.backward()
optimizer.step()
train_err += loss.item()
train_loss.append(train_err)
I expect the model to update during training. There is no error message.
With your definitions:TP+FN=y and TN+FP=1-y. Then you'll get FN_rate=1-y_pred and FP_rate=y_pred. Your cost is then FN_rate+FP_rate=1, the gradient of which is 0.
You can check this by hand or using a library for symbolic mathematics (e.g., SymPy):
from sympy import symbols
y, y_pred = symbols("y y_pred")
TP = y * y_pred
TN = (1-y)*(1-y_pred)
FP = (1-y)*y_pred
FN = y*(1-y_pred)
# let's ignore the eps for now
FN_rate = FN/(TP + FN)
FP_rate = FP/(TN + FP)
cost = FN_rate + FP_rate
from sympy import simplify
print(simplify(cost))
# output: 1
I use odeint function to solve a coupled differential equations system and plot one of the variables (theta_i) after the system is solved. My variable (theta_i) comes from the equation:
theta_i = np.arctan2(g1,g2)
where g1 ang g2 are variables calculated in the same function. The results have to be between -pi and pi and they are supposed to look like this (plot from matlab simulation):
However, when I try to plot theta_i after odeint has finished I get this(plot from my python code):
which is really weird. When I print the values of theta_i right after its calcumation (still inside the function) they look correct (between -0.2 and 0.5), so it has to be something with the result's storing and my implementation of odeint. All the other variables that come from the odeint solution are correct. I searched similar posts but nobody had the same problem with me. What might be the problem here? I am new to python and I use python 2.7.12. Thank you in advance.
import numpy as np
from scipy.integrate import odeint
import matplotlib.pyplot as plt
added_mass_x = 0.03 # kg
added_mass_y = 0.04
mb = 0.3 # kg
m1 = mb-added_mass_x
m2 = mb-added_mass_y
l1 = 0.07 # m
l2 = 0.05 # m
J = 0.00050797 # kgm^2
Sa = 0.0110 # m^2
Cd = 2.44
Cl = 3.41
Kd = 0.000655 # kgm^2
r = 1000 # kg/m^3
c1 = 0.5*r*Sa*Cd
c2 = 0.5*r*Sa*Cl
c3 = 0.5*mb*(l1**2)
c4 = Kd/J
c5 = (1/(2*J))*(l1**2)*mb*l2
c6 = (1/(3*J))*(l1**3)*mb
theta_0 = 10*(np.pi/180) # rad
theta_A = 20*(np.pi/180) # rad
f = 2 # Hz
t = np.linspace(0,100,8000) # s
def direct(u,t):
vcx = u[0]
vcy = u[1]
wz = u[2]
psi = u[3]
x = u[4]
y = u[5]
vcx_i = u[6]
vcy_i = u[7]
psi_i = u[8]
wz_i = u[9]
theta_i = u[10]
theta_deg_i = u[11]
# Subsystem 1
omega = 2*np.pi*f # rad/s
theta = theta_0 + theta_A*np.sin(omega*t) # rad
theta_deg = (theta*180)/np.pi # deg
thetadotdot = -(omega**2)*theta_A*np.sin(omega*t) # rad/s^2
# Subsystem 2
vcxdot = (m2/m1)*vcy*wz-(c1/m1)*vcx*np.sqrt((vcx**2)+(vcy**2))+(c2/m1)*vcy*np.sqrt((vcx**2)+(vcy**2))*np.arctan2(vcy,vcx)-(c3/m1)*thetadotdot*np.sin(theta)
vcydot = -(m1/m2)*vcx*wz-(c1/m2)*vcy*np.sqrt((vcx**2)+(vcy**2))-(c2/m2)*vcx*np.sqrt((vcx**2)+(vcy**2))*np.arctan2(vcy,vcx)+(c3/m2)*thetadotdot*np.cos(theta)
wzdot = ((m1-m2)/J)*vcx*vcy-c4*wz*wz*np.sign(wz)-c5*thetadotdot*np.cos(theta)-c6*thetadotdot
psidot = wz
# Subsystem 3
xdotdot = vcxdot*np.cos(psi)-vcx*np.sin(psi)*wz+vcydot*np.sin(psi)+vcy*np.cos(psi)*wz # m/s^2
ydotdot = -vcxdot*np.sin(psi)-vcx*np.cos(psi)*wz+vcydot*np.cos(psi)-vcy*np.sin(psi)*wz # m/s^2
xdot = vcx*np.cos(psi)+vcy*np.sin(psi) # m/s
ydot = -vcx*np.sin(psi)+vcy*np.cos(psi) # m/s
# Subsystem 4
vcx_i = xdot*np.cos(psi_i)-ydot*np.sin(psi_i)
vcy_i = ydot*np.cos(psi_i)+xdot*np.sin(psi_i)
psidot_i = wz_i
vcxdot_i = xdotdot*np.cos(psi_i)-xdot*np.sin(psi_i)*psidot_i-ydotdot*np.sin(psi_i)-ydot*np.cos(psi_i)*psidot_i
vcydot_i = ydotdot*np.cos(psi_i)-ydot*np.sin(psi_i)*psidot_i+xdotdot*np.sin(psi_i)+xdot*np.cos(psi_i)*psidot_i
g1 = -(m1/c3)*vcxdot_i+(m2/c3)*vcy_i*wz_i-(c1/c3)*vcx_i*np.sqrt((vcx_i**2)+(vcy_i**2))+(c2/c3)*vcy_i*np.sqrt((vcx_i**2)+(vcy_i**2))*np.arctan2(vcy_i,vcx_i)
g2 = (m2/c3)*vcydot_i+(m1/c3)*vcx_i*wz_i+(c1/c3)*vcy_i*np.sqrt((vcx_i**2)+(vcy_i**2))+(c2/c3)*vcx_i*np.sqrt((vcx_i**2)+(vcy_i**2))*np.arctan2(vcy_i,vcx_i)
A = 12*np.sin(2*np.pi*f*t+np.pi) # eksiswsi tail_frequency apo simulink
if A>=0.1:
wzdot_i = ((m1-m2)/J)*vcx_i*vcy_i-c4*wz_i**2*np.sign(wz_i)-c5*g2-c6*np.sqrt((g1**2)+(g2**2))
elif A<-0.1:
wzdot_i = ((m1-m2)/J)*vcx_i*vcy_i-c4*wz_i**2*np.sign(wz_i)-c5*g2+c6*np.sqrt((g1**2)+(g2**2))
else:
wzdot_i = ((m1-m2)/J)*vcx_i*vcy_i-c4*wz_i**2*np.sign(wz)-c5*g2
if g2>0:
theta_i = np.arctan2(g1,g2)
elif g2<0 and g1>=0:
theta_i = np.arctan2(g1,g2)-np.pi
elif g2<0 and g1<0:
theta_i = np.arctan2(g1,g2)+np.pi
elif g2==0 and g1>0:
theta_i = -np.pi/2
elif g2==0 and g1<0:
theta_i = np.pi/2
elif g1==0 and g2==0:
theta_i = 0
theta_deg_i = (theta_i*180)/np.pi
#print theta_deg_i
return [vcxdot, vcydot, wzdot, psidot, xdot, ydot, vcxdot_i, vcydot_i, psidot_i, wzdot_i, theta_i, theta_deg_i]
# arxikes synthikes
vcx_0 = 0.1257
vcy_0 = 0
wz_0 = 0
psi_0 = 0
x_0 = 0
y_0 = 0
vcx_i_0 = 0.1257
vcy_i_0 = 0
psi_i_0 = 0
wz_i_0 = 0
theta_i_0 = 0.1745
theta_deg_i_0 = 9.866
u0 = [vcx_0, vcy_0, wz_0, psi_0, x_0, y_0, vcx_i_0, vcy_i_0, psi_i_0, wz_i_0, theta_i_0, theta_deg_i_0]
u = odeint(direct, u0, t, tfirst=False)
vcx = u[:,0]
vcy = u[:,1]
wz = u[:,2]
psi = u[:,3]
x = u[:,4]
y = u[:,5]
vcx_i = u[:,6]
vcy_i = u[:,7]
psi_i = u[:,8]
wz_i = u[:,9]
theta_i = u[:,10]
theta_deg_i = u[:,11]
print theta_i
plt.figure(17)
plt.plot(t,theta_i,'r-',linewidth=1,label='theta_i')
plt.xlabel('t [s]')
plt.title('theta_i [rad] (Main body CF)')
plt.legend()
plt.show()
The problem as you stated is that theta_i is not part of the gradient. When you formulate your direct, it should be of the form:
def direct(vector, t):
return vector_dot
The quickest and dirtiest solution (without cleaning the code) is to use the function you already defined:
theta_i = [direct(u_i, t_i)[10] for t_i, u_i in zip(t, u)]
I used a a shorter interval: t = np.linspace(0,10,8000). It yielded this:
EDIT: How to remove your theta from the integrator:
def direct(u, t):
# your original function as it is
def direct2(u,t):
return direct(u,t)[:9]
#now integrate the second function
u = odeint(direct2, u0, t)
I am using wx.python along with VPython to make an orbit simulator, however i'm having trouble trying to get the sliders in the GUI to effect the simulation, I assume it's because I am trying to get the number associated with the slider button to go into a while loop when it is running.
So my question is, how do i get the function SetRate to update in the while loop located at the bottom of the code? (I have checked to see that the slider is retuning values)
Here is my code for reference:
Value = 1.0
dt = 100.0
def InputValue(Value):
dt = Value
def SetRate(evt):
global Value
Value = SpeedOfSimulation.GetValue()
return Value
w = window(menus=True, title="Planetary Orbits",x=0, y=0, width = 1000, height = 1000)
Screen = display(window = w, x = 30, y = 30, width = 700, height = 500)
gdisplay(window = w, x = 80, y = 80 , width = 40, height = 20)
p = w.panel # Refers to the full region of the window in which to place widgets
SpeedOfSimulation = wx.Slider(p, pos=(800,10), size=(200,100), minValue=0, maxValue=1000)
SpeedOfSimulation.Bind(wx.EVT_SCROLL, SetRate)
TestData = [2, 0, 0, 0, 6371e3, 5.98e24, 0, 0, 0, 384400e3, 0, 0, 1737e3, 7.35e22, 0, 1e3, 0]
Nstars = TestData[0] # change this to have more or fewer stars
G = 6.7e-11 # Universal gravitational constant
# Typical values
Msun = 2E30
Rsun = 2E9
vsun = 0.8*sqrt(G*Msun/Rsun)
Stars = []
colors = [color.red, color.green, color.blue,
color.yellow, color.cyan, color.magenta]
PositionList = []
MomentumList = []
MassList = []
RadiusList = []
for i in range(0,Nstars):
s=i*8
x = TestData[s+1]
y = TestData[s+2]
z = TestData[s+3]
Radius = TestData[s+4]
Stars = Stars+[sphere(pos=(x,y,z), radius=Radius, color=colors[i % 6],
make_trail=True, interval=10)]
Mass = TestData[s+5]
SpeedX = TestData[s+6]
SpeedY = TestData[s+7]
SpeedZ = TestData[s+8]
px = Mass*(SpeedX)
py = Mass*(SpeedY)
pz = Mass*(SpeedZ)
PositionList.append((x,y,z))
MomentumList.append((px,py,pz))
MassList.append(Mass)
RadiusList.append(Radius)
pos = array(PositionList)
Momentum = array(MomentumList)
Mass = array(MassList)
Mass.shape = (Nstars,1) # Numeric Python: (1 by Nstars) vs. (Nstars by 1)
Radii = array(RadiusList)
vcm = sum(Momentum)/sum(Mass) # velocity of center of mass
Momentum = Momentum-Mass*vcm # make total initial momentum equal zero
Nsteps = 0
time = clock()
Nhits = 0
while True:
InputValue(Value) #Reprensents the change in time
rate(100000) #No more than 100 loops per second on fast computers
# Compute all forces on all stars
r = pos-pos[:,newaxis] # all pairs of star-to-star vectors (Where r is the Relative Position Vector
for n in range(Nstars):
r[n,n] = 1e6 # otherwise the self-forces are infinite
rmag = sqrt(sum(square(r),-1)) # star-to-star scalar distances
hit = less_equal(rmag,Radii+Radii[:,newaxis])-identity(Nstars)
hitlist = sort(nonzero(hit.flat)[0]).tolist() # 1,2 encoded as 1*Nstars+2
F = G*Mass*Mass[:,newaxis]*r/rmag[:,:,newaxis]**3 # all force pairs
for n in range(Nstars):
F[n,n] = 0 # no self-forces
Momentum = Momentum+sum(F,1)*dt
# Having updated all momenta, now update all positions
pos = pos+(Momentum/Mass)*dt
# Update positions of display objects; add trail
for i in range(Nstars):
Stars[i].pos = pos[i]
I know nothing about vpython but in a normal wxPython app, you will use wx.Timer instead of while loop.
here is an example of wx.Timer modified from https://www.blog.pythonlibrary.org/2009/08/25/wxpython-using-wx-timers/
You will want to separate the while loop part from your SetRate class method and put it in update.
import wx
class MyForm(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, wx.ID_ANY, "Timer Tutorial 1",
size=(500,500))
# Add a panel so it looks the correct on all platforms
panel = wx.Panel(self, wx.ID_ANY)
self.timer = wx.Timer(self)
self.Bind(wx.EVT_TIMER, self.update, self.timer)
SpeedOfSimulation = wx.Slider(p, pos=(800,10), size=(200,100), minValue=0, maxValue=1000)
SpeedOfSimulation.Bind(wx.EVT_SCROLL, SetRate)
self.SpeedOfSimulation = SpeedOfSimulation
def update(self, event):
# Compute all forces on all stars
SpeedOfSimulation = self.SpeedOfSimulation.GetValue()
https://www.dropbox.com/sh/zeaa8ouwq3oo8c3/AAAgRNJwRL_TGwFWkBD6KFV0a?dl=0
My data: data.csv
I tried to draw a contour plot using Python.
import numpy as np
import matplotlib.pyplot as plt
import scipy.interpolate
import time
import datetime
f = open("data.csv","r")
title = f.readline()
lines = f.readlines()
print len(lines)
xlist = []
ylist = []
zlist = []
for line in lines:
titlecells = title.split(',')
linecells = line.split(',')
print len(titlecells)
for i in range(1,len(titlecells)):
items = titlecells[i].split('/')
items = map(int, items)
dt = datetime.datetime(items[0], items[1], items[2])
sdt = datetime.datetime(1900,1,1)
delta = int(str(dt - sdt).split(' ')[0]) / 10
xlist.append(delta)
ylist.append(linecells[0].replace('0~','').replace('m',''))
try:
zlist.append(float(linecells[i]))
except ValueError:
zlist.append(0)
print len(xlist)
print len(ylist)
print len(zlist)
ylist = map(int, ylist)
x = np.array(xlist)
y = np.array(ylist)
z = np.array(zlist)
print z
# Generate data: for N=1e6, the triangulation hogs 1 GB of memory
'''N = 1000000
x, y = 10 * np.random.random((2, N))
rho = np.sin(3*x) + np.cos(7*y)**3
print x.shape,y.shape'''
# Set up a regular grid of interpolation points
xi, yi = np.linspace(x.min(), x.max(), 300), np.linspace(y.min(), y.max(), 300)
xi, yi = np.meshgrid(xi, yi)
print xi,yi
# Interpolate; there's also method='cubic' for 2-D data such as here
zi = scipy.interpolate.griddata((x, y), z, (xi, yi), method='linear')
plt.imshow(zi, vmin=z.min(), vmax=z.max(), origin='lower',
extent=[x.min(), x.max(), y.min(), y.max()])
plt.colorbar()
plt.show()
Output obtained with Matlab:
Input data: TKJS_20150903.xlsx
Matlab Code
clear all; close all;
% read data
list_d2 = dir('C:\\MATLAB_CODE\\Monitoring_well\\TS_Analysis\\MW\\data\\*.xlsx');
for k = 1:length(list_d2)
station = list_d2(k).name(1:13);
filename = sprintf('C:\\MATLAB_CODE\\Monitoring_well\\TS_Analysis\\MW\\data\\%s.xlsx', station);
[MW_data, data_tex, alldata] = xlsread(filename,5);
MW_data = MW_data(2:end,:);
date = datenum(cellfun(#num2str,alldata(3:end,1),'UniformOutput', false),'yyyy/mm/dd');
depth = cell2mat(alldata(2,2:end))';
% MW_data=MW_data';
% compute gap between every rings
for i = 1:length(MW_data(:,1))
for j = 1:length(MW_data(1,:))-1
disp(i,j) = MW_data(i,j)-MW_data(i,j+1);
end
end
vel=disp';
% dlmwrite('displacement.txt', disp, '\t');
for i = 2:length(depth)-1
thick(i) = depth(i+1)-depth(i);
end
thick=thick(1:end);
thick1=repmat(thick,length(disp(:,1)),1);
% dlmwrite('thickness.txt', thick, '\t');
% % check data
% figure(1);
% plot(MW_data,depth*(-1));
% set well depth
yg1 = 0; yg2 = 300;
% make grid
[xgrid,ygrid] = meshgrid(date(1):30:date(end),yg1:1:yg2);
xint=repmat(date',length(thick),1);
yint=repmat(depth(2:end),1,length(date));
xint1 = reshape(xint, numel(xint), 1);
yint1 = reshape(yint, numel(yint), 1);
zint1 = reshape(vel, numel(vel), 1);
% [Xwdp,Ywdp,Zwdp] = griddata(xint1,yint1,zint1,xgrid,ygrid);
[Xwdp,Ywdp,Zwdp] = surfergriddata(xint1, yint1, zint1, xgrid, ygrid, 'kriging');
% save('cresult.mat');
h1 = figure;
set(h1,'paperorientation', 'portrait', 'color', [1 1 1], 'papertype','A4');
set(gcf,'Units','Centimeter','Position', [5 5 18 20]);
set(gcf,'PaperPositionMode','auto');
set(gca, 'FontSize', 12, 'FontWeight','bold');
set(gca, 'FontName', 'Arial')
% box on;
% pcolor(xgrid, ygrid, Zwdp);
surf(xgrid,ygrid,Zwdp);
shading interp;
view(0,90);
colorbar;
z1=round(min(min(vel)));
z2=round(max(max(vel)));
caxis([z1 z2]);
% caxis([-0.5 0.5]);
% caxis([-1.2 1.2]);
% caxis([-1 2]);
% caxis([-1 8]);
% x1=floor(min(min(date)));
% x2=round(max(max(date)));
axis([ min(min(date)), max(max(date)), 0, 300]);
set(gca,'fontsize',5,'xticklabelmode','manual','yticklabelmode','manual');
pa = get(gca,'xlim');
pb = get(gca,'ylim');
pa1 = (pa(1):pa(2));
pa2 = (pb(1):pb(2));
indx = find(mod(pa1-pa1(1),60)==0);
indy = find(mod(pa2,50)==0);
set(gca,'xtick',pa1(indx),'xticklabel',[]);
xrtime=get(gca,'xtick');
xstime=datestr(xrtime,'yyyy/mm');
for n=1:length(xrtime)
text(xrtime(n),308,xstime(n,:),'HorizontalAlignment','center','fontsize',8,'fontweight','bold')
end
set(gca,'ytick',pa2(indy),'yticklabel',pa2(indy),'fontsize',8,'fontweight','bold');
set(gca,'YDir','reverse','tickdir','out'); hold on
% gridnumy = zint1(:,1);
%
% for j = 1:length(gridnumy)
% line(xgrid(1,:)',repmat(gridnumy(j),size(xgrid,2),1),'color','black','linestyle','-');
% end
well=list_d2(k).name(1:4)
title({well 'Monitoring Well'}, 'FontSize', 12, 'FontWeight','bold');
xlabel('Date', 'FontSize', 12, 'FontWeight','bold');
ylabel('Depth (m)', 'Fontsize', 12, 'FontWeight','bold');
% clabel('Compression (cm)', 'Fontsize', 12, 'FontWeight','bold');
list_p4=sprintf('C:\\MATLAB_CODE\\Monitoring_well\\TS_Analysis\\MW\\%s', well);
print('-dpng','-r300', list_p4);
clear MW_data data_tex xint xint1 yint yint1 zint1 thick thick1 vel disp
end
I want to get similar Output using Python.
But, I don't know how to improve my code.