Pylogix and Matplotlib

Thanks Peter!
Small detail, but the dotted actual for the step response is slick.
Yes, RMCTools should do the same so when the target and actual positions or velocities are the same, they don't look like just one line.



Is there a py module that reads from the delta? Not that the plots can get much better in Tools.
Yes, there is a download called RMCLink on our website. It is a .net assembly that allows one to access the RMCs using just about anything when running on Windows. There are example programs for python. Ask Jacob ( out tech support ) for help if required. RMCLink is cool.
It is tough to beat RMCTools but it allows access to too much. People have made decent interfaces and data logging using Excel or VB.
 
That code is over my head.


zip(...) method should absolutely be in everyone's toolbox, IMNSHO; it is to list comprehension what heroin is to morphine: once you know about it you won't be able to stop using it ;).

"*" and "**" argument prefix operators in method calls are a bit "Huh?"-ish, but not too hard to understand, and common enough in libraries (e.g. matplotlib) that they should be understood.

Generator functions are the hairiest "trick" of that script, but certainly understandable.

Google and StackExchange should get you there.
 
A little showing off but Taylor will appreciate this because he also does hydraulic servo control.
https://deltamotion.com/peter/Videos/ValveID.mp4
I meant to post this on YouTube over a year ago but something prevented me from doing it. In the video I am finding the model for a non-linear 10 gpm Parker valve. Notice that I am using a swept sine wave and I don't need the PV or actual position to come to a steady state.
The video shows I can model non-linear items very well. However, I did try many different types of models before settling on the 10 gain segment model. Notice I find the value for 15 unknown variables. It takes about 20 minutes to try all the combinations. I am just modeling a simple valve. I have heard that Boeing modeled things will as many a 40 unknown variables. It takes time but finding the model is crucial when doing cutting edge design. Caterpillar does about the same for each component since the manufacturer's documented specifications are usually poor. When making a big project one starts by modeling all the small components that will go into the big design. The simulations get to be very complex and take a long time but in the end one can be pretty sure if the design will work or not. This is MUCH cheaper than trial and error.
Also, I would use C or C++ instead of python because it is faster and the time saved doing simulations offsets the development time.



I can thank forum member rwatson for motivating me to implement jupyter lab and jupyter hub which are web based python environments.
 
A little showing off but Taylor will appreciate this because he also does hydraulic servo control.
https://deltamotion.com/peter/Videos/ValveID.mp4
I meant to post this on YouTube over a year ago but something prevented me from doing it. In the video I am finding the model for a non-linear 10 gpm Parker valve. Notice that I am using a swept sine wave and I don't need the PV or actual position to come to a steady state.
The video shows I can model non-linear items very well. However, I did try many different types of models before settling on the 10 gain segment model. Notice I find the value for 15 unknown variables. It takes about 20 minutes to try all the combinations. I am just modeling a simple valve. I have heard that Boeing modeled things will as many a 40 unknown variables. It takes time but finding the model is crucial when doing cutting edge design. Caterpillar does about the same for each component since the manufacturer's documented specifications are usually poor. When making a big project one starts by modeling all the small components that will go into the big design. The simulations get to be very complex and take a long time but in the end one can be pretty sure if the design will work or not. This is MUCH cheaper than trial and error.
Also, I would use C or C++ instead of python because it is faster and the time saved doing simulations offsets the development time.



I can thank forum member rwatson for motivating me to implement jupyter lab and jupyter hub which are web based python environments.

Thanks for sharing Peter! Admittedly, I don't understand....all of it. But it appears to be well suited for machine learning(?). I'm in my 3rd week of a machine learning course now, so....

Could this have also been done using a polynomial regression algorithm (or other ML algorithm) that is part of the Scikit-Learn python library?
 
Thanks for sharing Peter! Admittedly, I don't understand....all of it.
I have two MUCH simpler examples on my YouTube channel. The simple one has only to find two parameters which is a gain and time constant. This example is good one to learn on because you can think of the gain is moving north-south and the time constant as moving east west. The elevation is the sum of squared errors between the actual positions ( PV ) and the estimated positions (EV). The goal is to reduce the sum of squared errors so you want to walk down hill. What the computer does is take a small step to the north and checks the elevations ( the sum of squared errors ), then go back to the original position and take a small step to the west and check the elevation. From these two steps it is possible to determine which way to go down hill and then one keeps going in that direction until the elevation starts increasing again. Then one takes a small step to the north and another small step to the west to determine a new direction that reduces the elevation ( sum of squared errors ). Eventually you will get to the valley floor where the elevation is a minimum. At this point you have the good approximations of the gain and time constant.
The computer can do this in a fraction of a second. RMCTools does this almost instantly because the code is written in C instead of python.



But it appears to be well suited for machine learning(?). I'm in my 3rd week of a machine learning course now, so....
Auto tuning can be done with just a move back and forth.


Delta does have a machine learning application but it is different from motion control. We make machines that can scan, grade and remove defects from potato strips.
Turn the volume down. This is more of a marketing video than an engineering one
At Delta we had to run many hundreds of potato strips through the scanners to teach the computers what to look for. This branch if AI is called classification. After "learning" what to look for it is very good at finding defects in potato strips. This isn't much different in having a computer tell the difference in letters or animals or people's faces. In the end all of this comes down to minimizing errors between the computer's answers and the real or best answers.

https://deltamotion.com/peter/Videos/Delta Fry Cutting Machine Demo.mp4
At one time we had 5 computers working on minimizing the error detection. Now we have an AMD thread ripper working on it.


@busarider29, if you ever want to get "geeked" you should come to an advanced training.


Just so the forum knows. Both busarider29 and Taylor are customers.


Could this have also been done using a polynomial regression algorithm (or other ML algorithm) that is part of the Scikit-Learn python library?
Laplace transforms and state space work for simple applications but when getting serious, one uses differential equations because they are capable of simulating non-linear and other odd ball functions.


You need to look up system identification. That is what I am doing with the non-linear valve. One must be able to understand the system well enough to use a reasonable differential equation that will approximate the real system. Like I said above, I tried a few different differential equations in an effort to approximate the valve.


If you are using Python for your class you really need to look at the APMonitor YouTube channel. The young professor is good. I also have lots to share on my "Peter Ponders PID" channel but the math is intense. Most people can't follow after 2-3 minutes and bail out.
 
That code is over my head. I know "real-time" is used too lightly, but I'm not even certain the plot is doing what it's supposed to...



y = .ACC from a one second timer


That looks roughly right: the default inter-sample period is 0.628s*; it appears the timer expires very near each whole second of the abscissa, so and the ordinate value drops across each of those boundaries.



* originally coded using cos(x) for testing, so 11 samples would cover ~2π
 
Last edited:
Any ideas

For live plotting this kinda works but it's clunky, is there an easier method?

Code:
array=np.append(arr,NewValue)            
plt.ion()                               
plt.plot(array)
plt.draw()            
plt.pause(0.001)

This is then Looped
 
Look for the word animation
import matplotlib.animation as animation
There are plenty of examples on the internet
Code:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation

# Fixing random state for reproducibility
np.random.seed(19680801)


# Create new Figure with black background
fig = plt.figure(figsize=(8, 8), facecolor='black')

# Add a subplot with no frame
ax = plt.subplot(111, frameon=False)

# Generate random data
data = np.random.uniform(0, 1, (64, 75))
X = np.linspace(-1, 1, data.shape[-1])
G = 1.5 * np.exp(-4 * X ** 2)

# Generate line plots
lines = []
for i in range(len(data)):
    # Small reduction of the X extents to get a cheap perspective effect
    xscale = 1 - i / 200.
    # Same for linewidth (thicker strokes on bottom)
    lw = 1.5 - i / 100.0
    line, = ax.plot(xscale * X, i + G * data[i], color="w", lw=lw)
    lines.append(line)

# Set y limit (or first line is cropped because of thickness)
ax.set_ylim(-1, 70)

# No ticks
ax.set_xticks([])
ax.set_yticks([])

# 2 part titles to get different font weights
ax.text(0.5, 1.0, "MATPLOTLIB ", transform=ax.transAxes,
        ha="right", va="bottom", color="w",
        family="sans-serif", fontweight="light", fontsize=16)
ax.text(0.5, 1.0, "UNCHAINED", transform=ax.transAxes,
        ha="left", va="bottom", color="w",
        family="sans-serif", fontweight="bold", fontsize=16)


def update(*args):
    # Shift all data to the right
    data[:, 1:] = data[:, :-1]

    # Fill-in new values
    data[:, 0] = np.random.uniform(0, 1, len(data))

    # Update data
    for i in range(len(data)):
        lines[i].set_ydata(i + G * data[i])

    # Return modified artists
    return lines

# Construct the animation, using the update function as the animation director.
anim = animation.FuncAnimation(fig, update, interval=10)
plt.show()
 
More
https://www.geeksforgeeks.org/how-to-save-matplotlib-animation/
I couldn't get the save video part to work so I commented it out

Code:
"""
Matplotlib Animation Example

author: Jake Vanderplas
email: [email protected]
website: http://jakevdp.github.com
license: BSD
Please feel free to use and modify this, but keep the above information. Thanks!
"""

import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation

# First set up the figure, the axis, and the plot element we want to animate
fig = plt.figure()
ax = plt.axes(xlim=(0, 2), ylim=(-2, 2))
line, = ax.plot([], [], lw=2)

# initialization function: plot the background of each frame
def init():
    line.set_data([], [])
    return line,

# animation function.  This is called sequentially
def animate(i):
    x = np.linspace(0, 2, 1000)
    y = np.sin(2 * np.pi * (x - 0.01 * i))
    line.set_data(x, y)
    return line,

# call the animator.  blit=True means only re-draw the parts that have changed.
anim = animation.FuncAnimation(fig, animate, init_func=init,
                               frames=200, interval=20, blit=True)

# save the animation as an mp4.  This requires ffmpeg or mencoder to be
# installed.  The extra_args ensure that the x264 codec is used, so that
# the video can be embedded in html5.  You may need to adjust this for
# your system: for more information, see
# http://matplotlib.sourceforge.net/api/animation_api.html
#anim.save('basic_animation.mp4', fps=30, extra_args=['-vcodec', 'libx264'])
#anim.save('basic_animation.mp4', fps=30 )

plt.show()
 
I have two MUCH simpler examples on my YouTube channel.
Good explanations, now I understand it in theory. I'll most certainly check out your YT channel, which I wasn't aware of before.

At Delta we had to run many hundreds of potato strips through the scanners to teach the computers what to look for. This branch if AI is called classification.
Classify as 'good' or 'defect' potato strip. Understood. Coincidentally, I have a "ML via classification" assignment due this week.

At one time we had 5 computers working on minimizing the error detection. Now we have an AMD thread ripper working on it.
Great processors. I've got a 5950x in my desktop at home. Beckhoff is now starting to offer these AMD Ryzen multicore processors in their IPC's too. CX2043

@busarider29, if you ever want to get "geeked" you should come to an advanced training.
Actually, I tried to a couple years ago. I felt it would be good to learn things that I didn't know or that might be useful later, plus I looked at it as an opportunity to visit my old stomping grounds (I lived in the Tri-Cities area for almost 4 years, 2009-2013). But my boss said, "Well, if you can show me a compelling reason why we need to send you to the advanced training, then we most certainly will send you, because right now it looks like you have everything working just fine for our needs". 🙃

If you are using Python for your class you really need to look at the APMonitor YouTube channel. The young professor is good. I also have lots to share on my "Peter Ponders PID" channel but the math is intense. Most people can't follow after 2-3 minutes and bail out.
Yep, using Python in just about every course. Only one course thus far where a different programming language was required for the course - "Statistics Using R".
I will most certainly explore the YT channels. Thanks.
 
Last edited:
Yep, using Python in just about every course. Only one course thus far where a different programming language was required for the course - "Statistics Using R".
I will most certainly explore the YT channels. Thanks.
R is what we used for classification on the french fry project.
R runs under jupyter lab/hub too. The thread riper is running R.
 
Last edited:
I ported that to show graphs but also what can be done with auto tuning.
So many think they must use step jumps and that the PV must reach a steady state. This may be true of trying to "eyeball estimate" the model.


However, when tuning a system with a 50ton coil of steel on it, step jumps are a no-no. The steel would probably fall off the platform and who knows what the shock would do.


Those that have used our product know we don't use step jumps. The excitation looks more like a W or inverted W depending on direction of motion. This excitation avoids shock and allows us to determine if the gains are linear.
 

Similar Topics

Hey everyone, I am looking for a tool to parse PLC data and I believe pylogix may be the best approach. I am very new with python but can see its...
Replies
1
Views
867
Can I not access locally defined UDT data? Scope.. Task>Prog1>Parameters and Local Tags(Test1 = real)(UTD.Test2 = real) #To access the local...
Replies
10
Views
1,500
If anyone is interested, I have an experimental branch on github that adds an “adapter” module to pylogix, which will allow you to interface to a...
Replies
1
Views
1,141
I am trying to use pylogix to write to a string array ID_Data_Table_Name. In the array there are 200 possible entries. For...
Replies
13
Views
4,032
I'm currently working with pylogix and have no trouble reading and writing tags. My problem is, I would like to be able to read (and write) I/O...
Replies
5
Views
3,708
Back
Top Bottom