6.05.2020

App in python for Control Systems modeling

For the final chapter of modeling control systems a computer program must be developed to calculate processes using a computational model and visualize them. The program should have a standard Windows interface (a window with data entry fields, buttons and a graphic area).

Requirements for models:
  • Ability to set the simulation time and time step.
  • Ability to display one or more timelines on the construction area.
  • Convenience of scaling charts. The main driving influence of the system (for z) is a single jump at the initial moment of time.

For Subordinate Regulation Control System:
  • The ability to visualize the processes u (t), x (t), y (t), z (t), as well as defining the effects of internal circuits for the quantities x (t) and y (t).

For Modal Control System:
  • The ability to visualize processes for all state variables, as well as for the output value z (t), if it is not a state variable.

For reason of it simplicity, the language chosen was Python 3 programming environment. Python is a general-purpose programming language, moreover, the entry threshold is low, and the code is largely concise and understandable even to someone who has never used Python.

Creating the app here begins with choosing a GUI framework and other libraries to develop our window and related components. The chosen GUI library is tkinter, the other libraries are: numpy for math functions and matplotlib for plot visualization.

Both control systems will be calculated in this app. All schedules will be built all in the same program at the same time. The visualization will consist in the fact that the user selects the graphic of interest to him in the graphic selection block, and, when you click on the corresponding buttons, the graphics are already built and become visible.

This should be the app behaviour: the user enters the initial parameters into the data entry fields and clicks the "Calculate" button; after that, the program calculates all the points in the coordinate plane for plotting; and finally, the user selects the desired graphic to be displayed, and the app will show it.

I explain the development of the app in this video on youtube:


Also here is the source code for the app; you can download, add or edit if you want to improve the performance and behaviour.

5.30.2020

Modal Control System

This system has only one feedback loop, but this loop doesn't have a regulator as such. Regulation occurs due to the input system coefficient and the state variable coefficients. Therefore, the calculation of these coefficients will give us the result for the system. 

The modal control system should provide a monotonic transient function without overshoot (which corresponds to a binomial pole distribution). 

The control object is covered by feedback on selected state variables with some transmission coefficients. The matrix of these coefficients is a modal regulator. The principal quantity z may be one of the state variables, but this is not necessary.

Using additional corrective devices, it is necessary to provide a single static transmission coefficient between the control action and the main value z.

The development of a modal control system begins with the transformation of the source data. We are given a system of equations:

x = 20v,
2y' + y = x - 2z,
z'' + z' + 3z = 15y

Value of the transition time tpp = 2,4 s.

Now we introduce the following notation:

x1 = y        x2 = z          r = 1         n = 3
y1 = z        x3 = z'         m = 1
u1 = u

We substitute the replaced variables in the system of equations, and also make the change: v = 47u. Now we write the obtained equations in the normal Cauchy form, expressing the variables x. We get:
From here we can write the following matrices:

Now let's look at the diagram shown on the demo sheet and, in accordance with it, we will write a system of two equations in matrix form:

We calculate the matrix A-BK. We call it the matrix E.

Subtract the diagonal matrix P from the resulting matrix, calculate the determinant of the resulting matrix and equate it to zero to obtain the characteristic equation of the system.

Since we use the binomial distribution of poles, the third-order characteristic equation should have the form:
Here A is the geometric mean pole equal to: A = τpp/tpp = 6,3/2,4 = 2.625 s
We equate the values of p of the same degree. From here we find all the coefficients.

The next and last point is to find the coefficient of the system km. To do this, recall the system of equations written according to the scheme.
Static Mode:

We describe these equations in more detail.

From the first equation we obtain the following three equalities:

We write what the coefficient of the system is equal to:
The resulting coefficient of the system will stand at the input of the system and change the input signal. The scheme will looks like this:


5.24.2020

Subordinate Regulation Control System

The system is a multi-circuit system of subordinate regulation, which consists of three circuits, each of which includes an input quantity, a regulator, and a controlled quantity. Each circuit has its own regulator. They depend on each other and they are all unknown, therefore, the main task of this system is the calculation of regulators.

x = 20v
2y' + y = x - 2z
z'' + z' + 3z = 15y

Value of the transition time tpp = 2,4

The system should consist of three control loops (values ​​x, y, z). If necessary, additional action can be introduced to compensate for the internal feedback of the control object. All regulators and additional corrective devices must be physically feasible.

The system should have the first order of astatism. The transition function of the system should have a weak oscillation and overshoot of 4-8% (which corresponds to the distribution of the poles across Butterworth).

From the first equation of the system we get the first-order link, the transfer function W01 (p), at the input of which is the variable v, and at the output is the variable x. The second equation gives us the transfer function W02 (p), the input of which is the error of the controller e5, and the output is the variable y. Also, we get negative feedback from the amplifying variable z 2 times. At the input of the adder, the variable x. From the third equation, a first-order link is obtained - W03 (p). The output of this function is z. We immediately include the variable u in the circuit in accordance with the condition v = 47u. The resulting circuit is shown in Figure 1.1.
Figure 1.1
The next step is the internal compensation feedback from the variable z. It is compensated by the introduction of positive feedback (Figure 1.2)
Figure 1.2
After the internal feedback is compensated, it is necessary to make compensation from the control object, since, by condition, we cannot change the control object itself. For transfer, standard rules for transferring a node through a link and an adder through a link are used. The resulting circuit is shown in Figure 1.3.
Figure 1.3
Now, when calculating, you can ignore feedback values, which greatly simplifies the task. The equivalent circuit is presented in Figure 1.4.
Figure 1.4
Take a section of the circuit from variable u to variable x and add to them the adder and controller R1 (p), as shown in Figure 1.5.
Figure 1.5
The entire plot obtained from x1 to x represents the Desired Function F1 (p). The current section is of second order, therefore, the desired transfer function will be of second order. We take it from the table of transfer functions for Butterworth distribution.
Now we write the formula for the first controller:
We proceed to the next circuit. Now the regulation section looks like in Figure 1.6
Figure 1.6
We follow the same algorithm as above, but the desired transfer function F2 (p):
And finally, repeat the procedure for the last contour, section x3 - z (Figure 1.7).
Figure 1.7




Now you need to calculate T3 using the formula T = tpp/τpp. 
Where tpp = 2,4 s and τpp = 6 (from the table of indicators of universal transition functions for a fourth-order system). Then:
Now we substitute this value in the formulas of all regulators and get their final expressions:



The finished scheme looks like this:


5.17.2020

Machine Learning with Octave or MATLAB

You will find some practical machine learning problems written in MATLAB and also with the possibility to open in Octave(open source software) with different topics: linear regression, logistic regression, PCA, data compression, analysis and so on.

Click the following link https://github.com/Daveric/machine-learning-ex

This examples correspond to the exercises from the Machine Learning course in Coursera platform, so be free to analyse my code, making tips or corrections are welcome, so I'm trying to use a vector implementation for each exercise.

As you know vector implementation for lot of Data could be less computational expensive than some other methods like loops, no matter which programming language you are using. So that's the target, using vectors your machine learning app will have a better performance.

NOTE:
If you want to use MATLAB software, there is a free subscription for testing the online MATLAB services(around 15 days), just through your favourite browser can open it and start to code there. It looks like this:



9.19.2018

Módulo eléctrico de mecanismos de producción(mecanismo de empuje automatizado)

El objetivo del proyecto es seleccionar los componentes principales de las partes de potencia y control del accionamiento eléctrico del mecanismo de producción y el desarrollo de un sistema de control automático.

El empujador se encuentra en la parte final de la línea de producción de las lingotes-molino. En la línea de Producción, se producen lingotes-molino, piezas en bruto de sección transversal cuadrada de 200 x 200 mm y hasta 300 x 300 mm, lo que representa un producto intermedio para su posterior procesamiento. El lingote laminado de la producción es transportado por mesas de rodillos hacia las tijeras para cortar los extremos a medida.

Los lingotes así obtenidos se pesan en escalas, mesas de rodillos transportan hacia el final del tramo y el lingote se empuja de la cinta transportadora hacia un contenedor, que transporta además a un almacén de piezas en bruto, ya sea en tren de barras línea de laminación para la obtención de pre-formas de sección más pequeña. 

El esquema cinemático del empuje se muestra en la figura. El cuerpo de trabajo del empuje es de dos varillas. El movimiento se transfiere a las barras desde uno o dos motores a través del engranaje y los engranajes de accionamiento, que están engranados con las barras de cremallera. El accionamiento eléctrico del empujador funciona en un corto tiempo con una carga variable. El ciclo de trabajo incluye:
  • Aumento de las barras a baja velocidad en ralentí; 
  • El acercamiento de las barras a la pieza de trabajo y el comienzo del empuje con velocidad reducida; 
  • Aceleración hasta velocidad de trabajo; 
  • Empuje con velocidad de trabajo hasta la caída de la pieza de trabajo; 
  • Desaceleración hasta detener las barras; 
  • Aceleración en la dirección opuesta a max. velocidad; 
  • Retorno de barras a ralentí con max. velocidad; 
  • Desaceleración de las barras al tope en la posición inicial; 
  • Pausa (el motor se apaga). 
Los datos del proyecto se muestran en la siguiente tabla:


A continuación procederemos a la selección de los equipos eléctricos y electrónicos para la automatización del proceso. Luego del análisis de potencia del motor a utilizar, se elige el módulo de control de potencia SINAMICS DCM y el generadorТП-80-20-0,2 УХЛ4.

Ahora se elige el controlador automático, debido a la calidad y confiabilidad se decidió utilizar un equipo SIEMENS, dentro del cual incluye: fuente de poder LOGO! Power 24V/0.6A, módulo de procesador LOGO! 12/24 RC, módulo de salidas análogas LOGO! AM2 AQ.

También se tienen que elegir sensores lógicos de ciclo que regularán el trabajo del controlador. Los sensores deben ser de tipo pnp debido al controlador elegido. Por lo tanto elegimos el sensor de inducción ISB BC2A-32P-3-LS4 que, cuando aparece un objeto de acción en el área sensible, conmuta el circuito eléctrico del actuador. Son necesarios 4 sensores para las 4 distintas posiciones de acción.

Se analizan además el sistema automático de control de velocidad del motor, para lo cual se necesita un modelo de control automático que se lo podrá encontrar en la carpeta de los archivos, tal sistema está simulado en el programa MatLab.

Desarrollo del programa del controlador de automatización

La ubicación de los sensores se muestran en la imagen:

La vista general en el programa LOGO! Soft la podemos ver aquí:

Explicaremos la estructura del programa:
Tenemos seis entradas discretas, 4 de las cuales son sensores y 2 de los cuales son interruptores sin fijación (cerrados), una para el inicio de los trabajos, y el otro para una posible interrupción de las barras. En cuanto a las salidas. Salida analógica, que suministra voltaje al motor y una salida discreta, que es responsable de la inversión de dirección.

Vamos a explicar el trabajo del programa.

Al pulsar el botón de inicio, el motor alcanza una velocidad baja y empieza a mover las barras hacia la pieza de trabajo, cuando las barras llegan al sensor I3 el motor alcanza la velocidad de funcionamiento y está directamente en contacto con la pieza de trabajo, por lo que a partir de aquí empieza eficazmente a empujar. 

Además, en la siguiente posición del sensor, el motor desacelera hasta parar las barras y se vuelve en reversa, se mueve en la dirección opuesta a alta velocidad hasta alcanzar el último sensor, en donde se activa una señal de desaceleración, con lo que la máquina se regresa moviéndose con inercia hacia el inicio (sensor de posición 2), donde se indica la reanudación del ciclo y el motor se pausa antes del siguiente ciclo. Cuando se presiona el botón de apagado, la barra se frena, al presionar el botón de encendido reinicia desde la última etapa.

Aquí podrán obtener los archivos del proyecto. Muy pronto tendré listo el archivo de lectura y cálculos de potencia para la elección del motor.

8.31.2018

Robot Clasificador de Colores LEGO Mindstorms NXT 2.0

Llamado también en inglés como: Colour sorting robot with sorting tray. A continuación veremos una breve introducción al mundo LEGO, las especificaciones del set y la programación del robot.

Ladrillo programable LEGO NXT2.0

LEGO Mindstorms NXT es un set programable fabricado por LEGO. La versión del NXT que veremos a continuación salió en 2009, Lego Mindstorms NXT 2.0, la cual incluye un sensor de color y algunas otras mejoras comparado con la versión anterior. 

Actualmente existe un nuevo modelo llamado EV3.



El elemento principal del set es la CPU, el ladrillo programable NXT. El bloque soporta hasta 4 sensores y 3 motores, conectados mediante un cable RJ12. Cuenta con un micro-controlador de 32 bits ARM7TDMI-core Atmel AT91SAM7S256 con 256KB de memoria y 6KB de RAM, además de un micro-controlador de 8 bit Atmel AVR ATmega48.

Construcción

Dentro del manual del set LEGO, existen varios ejemplos por defecto, para lo cual armaremos nuestro robot de acuerdo al manual de Color Sorter, añadiendo a este la canasta de clasificación(Sorter Tray). Como en la imagen a continuación:



Programación

Para la programación del robot se utiliza el software basado en LabVIEW llamado Mindstorms NXT2.0, el cual provee una programación visual, lo que implica que en vez de tener que escribir el código simplemente se puede programar usando diagramas esquemáticos, práctico e ideal para un mejor entendimiento de los niños y adultos. A continuación una vista previa del programa:


Por defecto, existen ejemplos ya programados; los cuales pueden ser utilizados para pruebas y/o como auto-aprendizaje. A partir de los programas por defecto, se ha creado un nuevo desafío: 

  • Dentro de la bandeja de detección de color se introducen 12 pelotas(azul, verde, rojo y 9 amarillas). Después de presionado Enter, empieza el ciclo de clasificación. La pantalla del ladrillo debe mostrar "Start". Todas las pelotas amarillas deben ser lanzadas en 3 celdas de la canasta(de a 3 pelotas en cada celda), las pelotas sobrantes deben ser lanzadas a la 4ta celda. Determinando el color de cada pelota, en la pantalla del ladrillo se debe mostrar su color("Blue","Yellow"). En la pantalla se puede mostrar también la cantidad de pelotas lanzadas. Luego de lanzadas todas las 12 pelotas, la bandeja de clasificación debe volver a su posición inicial y la pantalla del ladrillo debe mostrar "Stop". Puede ocurrir que en el movimiento de la bandeja ninguna pelota caiga hasta la zona del detector de color. En este caso el contador no debe aumentar su valor y la pantalla debe mostrar "Lost Object". Después de terminado el ciclo debe existir la posibilidad de empezar otra vez sin necesidad de reanudar el programa. 

A continuación el programa explicado:
Utilizando los diagramas esquemáticos iniciamos un ciclo infinito con los bloques de flujo(naranja), el primero que repite el ciclo y el siguiente espera mientras no se ha presionado Enter.

Luego tenemos los bloques de acción(verdes) el primero que muestra en la pantalla la palabra "Start", el siguiente que gira la canasta hasta que se accione el sensor 2 y lo posiciona en la celda inicial.


Después añadimos los bloques de operaciones(rojo), creamos dos variables(cont_num para las pelotas amarillas, Number 1 para las demas pelotas) y le asignamos el valor inicial de cero(write=0) a cada una.

Se añade un ciclo que se repetirá hasta que todas las pelotas hayan sido clasificadas y se añade un bloque de flujo con sensor de color(amarillo) para empezar la clasificación, si la pelota analizada es amarilla el programa seguira hacia arriba, si es falso hacia abajo.

Se muestra en la pantalla el color detectado y luego con el bloque de operaciones (>) se comprueba con ciclos lógicos si el valor de la variable cont_num es mayor a 3, si es menor entonces se procede por la parte inferior.


Los bloques de operaciones suman una unidad a la variable cont_num hasta que se hayan arrojado las 3 primeras pelotas amarillas, para luego proseguir así mismo con las siguientes 3, cambiando el angulo de rotación al motor para que cambie de posición a otra celda.

Si el sensor detectó otro color diferente de amarillo se procede analizar que color(azul, rojo o verde) con los bloques de flujo y sensor, para luego mostrar en la pantalla dicho color, por consiguiente vamos añadiendo una unidad cada vez a la segunda variable Number 1. 
En caso de no detectar ningún color se muestra en la pantalla el mensaje "Lost Object" y se revuelve la bandeja.




Al final de todos los flujos, se suman las dos variables(cont_num y Number 1), si la suma da igual a 12 el ciclo termina, sino se repetirá hasta que las 12 pelotas hayan sido distribuidas. Finalmente se muestra en la pantalla la palabra "Stop" terminando así la clasificación.



Si se desea efectuar nuevamente la clasificación se presiona Enter y el programa empezará nuevamente.