Welcome Guest! To enable all features please Login. New Registrations are disabled.

Notification

Icon
Error

Login


3 Pages123>
Options
Go to last post Go to first unread
Offline pTM  
#1 Posted : 25 May 2022 17:25:15(UTC)
pTM


Rank: Member

Groups: Registered
Joined: 20/05/2022(UTC)
Posts: 22
United States
Location: Sunnyvale

Hello everybody,
I am migrating to SMath from Mathcad 15 and I would appreciate a jump start in converting a solver into SMath as I am not yet familiar with all the details of SMath.
The problem is an exercise in thermodynamics with the calculation of a solid composition from a gas mixture.
Mathcad uses a solve block. I understood I need to convert it into a matrix.
Mathcad file (pdf format), the SMath sheet, and a summary are attached.
Thanks for the help

Untitled.png

pTM AlAsSb 3.0 auto v1 2020-04-26.sm (26kb) downloaded 16 time(s). pTM AlAsSb 1.5 auto v1 2020-04-26.pdf (125kb) downloaded 13 time(s). Summary.pdf (899kb) downloaded 9 time(s).

Wanna join the discussion?! Login to your SMath Studio Forum forum account. New Registrations are disabled.

Offline Razonar  
#2 Posted : 25 May 2022 18:39:54(UTC)
Razonar


Rank: Advanced Member

Groups: Registered
Joined: 28/08/2014(UTC)
Posts: 1,356
Uruguay

Was thanked: 815 time(s) in 516 post(s)
Hi. This could be an option, using the non linear solver from alglib plugin.

pTM AlAsSb 3.0 auto v1 2020-04-26.sm (28kb) downloaded 36 time(s).

Best regards.
Alvaro.
Offline Razonar  
#3 Posted : 26 May 2022 05:58:01(UTC)
Razonar


Rank: Advanced Member

Groups: Registered
Joined: 28/08/2014(UTC)
Posts: 1,356
Uruguay

Was thanked: 815 time(s) in 516 post(s)
Hi. This is a way to make the plots.

pTM AlAsSb 3.0 auto v1 2020-04-26_plot.sm (51kb) downloaded 27 time(s).
pTM AlAsSb 3.0 auto v1 2020-04-26_plot.pdf (166kb) downloaded 28 time(s).

Best regards.
Alvaro.

Edited by user 26 May 2022 06:04:14(UTC)  | Reason: Not specified

Offline pTM  
#4 Posted : 26 May 2022 07:56:00(UTC)
pTM


Rank: Member

Groups: Registered
Joined: 20/05/2022(UTC)
Posts: 22
United States
Location: Sunnyvale

Thank you very much!.
Let me go over the details.
Pierre
Offline pTM  
#5 Posted : 30 May 2022 07:58:35(UTC)
pTM


Rank: Member

Groups: Registered
Joined: 20/05/2022(UTC)
Posts: 22
United States
Location: Sunnyvale

Muchas gracias Razonar. Pero no entiendo come funciona. Puedes explicarme el methodo con un ejemplo mas sencillo ? O por favor enviame a una pagina con una explicacion.
Parece que "target" estructura el asunto y "Jx","J(x)" definen el metodo de resolucion. Pero cual es ? Y por fin "f" es el algoritmo que resolve la ecuacion.
Gracias,

Pedro
Offline Razonar  
#6 Posted : 30 May 2022 14:38:01(UTC)
Razonar


Rank: Advanced Member

Groups: Registered
Joined: 28/08/2014(UTC)
Posts: 1,356
Uruguay

Was thanked: 815 time(s) in 516 post(s)
Originally Posted by: pTM Go to Quoted Post
Muchas gracias Razonar. Pero no entiendo come funciona. Puedes explicarme el methodo con un ejemplo mas sencillo ? O por favor enviame a una pagina con una explicacion.
Parece que "target" estructura el asunto y "Jx","J(x)" definen el metodo de resolucion. Pero cual es ? Y por fin "f" es el algoritmo que resolve la ecuacion.
Gracias,

Pedro


Hola Pedro. Sí, hay varios detalles "técnicos", por decirles de alguna forma.

A ver si estos comentarios explican un poco la solución.

La llamé "target" porque es el nombre que suele darse a la función que se quiere optimizar. Si te fijas en la forma en que está resuelto en Mathcad, el bloque given / find resulta en una función, no en los valores de las raíces. Esto porque tienes un sistema con 3 incógnitas y 2 ecuaciones: f ( PzSb ) = Find( Pas, Psb ). La función target no sería esa "f", aún.

Por otro lado, la función al_nlesolve se vuelve muy lenta si no se le da el Jacobiano de la función target, y la forma usual en SMath de construirlo es primero calcularlo y guardarlo en una etiqueta cualquiera (Jx en este caso) para luego decir que en realidad es una función de la variable x ( es decir: escribir J(x) = x ).

Con estos elementos ya puedes construir la función "f" que aparece en mathcad.

Se podría poner directamente

. f( PzSb ) = al_nleqsolve(guess,target)

y funcionaría en teoría, pero en la práctica es muy lenta, por lo cual hay que pasarle el jacobiano para que funcione más rápido, y quedaría

. f( PzSb ) = al_nleqsolve(guess,0,ε,target,J)

Pero como lo que interesa es llamarla recursivamente para calcular cientos de valores de Pas, Psb, a medida que te alejes del guess inicial le va a costar más trabajo encontrar las raíces, así que mejor pasas 'guess' también como argumento de f, así emplea las raíces previamente encontradas, que se supenen mejores aproximaciones de la raíz real que el valor inicial de guess.

Finalmente, para valores de PzSb que no encuentra solución, porque probablemente no la haya, en mathcad usas 'NaN', pero pasan dos cosas: SMath no tiene NaN, y además al_nleqsolve no retorna un error, sino que retorna un valor, pero que no se parece a una raíz. Así que en vez de 'NaN', la función f(PzSb,guess) lo que hace es verificar que normi(target(sol))<sqrt(ε), es decir, el máximo de los valores de sol, que son Pas, Psb, sea menor que sqrt(ε), es decir, que se parezca a una solución del sistema de ecuaciones.

Espero haber podido explicar el procedimiento.

Saludos cordiales.
____________________________________

English translation:

Hi Pedro. Yes, there are several "technical" details, for say something.

Let's see if these comments explain a little the solution.

I called it "target" because it is the name that is usually given to the function that you want to optimize. If you look at the way it's solved in Mathcad, the given / find block results in a function, not the root values. This is because you have a system with 3 unknowns and 2 equations: f ( PzSb ) = Find( Pas, Psb ). The target function would not be that "f", yet.

On the other hand, the function al_nlesolve becomes very slow if it is not given the Jacobian of the target function, and the usual way in SMath to build it is to first calculate it and store it in any label (Jx in this case) and then say that it is actually a function of the variable x ( ie: write J(x) = x ).

With these elements you can now build the function "f" that appears in mathcad.

Could be put directly

. f( PzSb ) = al_nleqsolve(guess,target)

and it would work in theory, but in practice it is very slow, so you have to pass the Jacobian to make it work faster, and it would be

. f( PzSb ) = al_nleqsolve(guess,0,ε,target,J)

But since what matters is calling it recursively to calculate hundreds of values ​​of Pas, Psb, as you move away from the initial guess it will take more work to find the roots, so you better pass 'guess' also as an argument to f, like this uses the previously found roots, which are supposed to be better approximations of the actual roots than the initial value of guess.

Finally, for values ​​of PzSb that do not find a solution, because there probably is not, in mathcad you use 'NaN', but two things happen: SMath does not have NaN, and also al_nleqsolve does not return an error, but rather returns a value, but that it doesn't look like a root. So instead of 'NaN', the function f(PzSb,guess) checks that normi(target(sol))<sqrt(ε), that is, the maximum of the values ​​of sol, which are Pas , Psb, is less than sqrt(ε), that is, it looks like a solution of the system of equations.

I hope I was able to explain the procedure.

Best regards.
Alvaro
Offline pTM  
#7 Posted : 30 May 2022 16:14:22(UTC)
pTM


Rank: Member

Groups: Registered
Joined: 20/05/2022(UTC)
Posts: 22
United States
Location: Sunnyvale

Gracias. Dejame estudiar tu respuesta.
Pedro
Offline pTM  
#8 Posted : 08 January 2023 04:41:04(UTC)
pTM


Rank: Member

Groups: Registered
Joined: 20/05/2022(UTC)
Posts: 22
United States
Location: Sunnyvale

Feliz Ano Nuevo, Happy New Year,

Ahora, intento hacer un cambio de materiales, y lo consegui hasta la funccion que da los valores uno por uno.
Un parametros es borrado.
Obviamente, necesito hacer tambien cambios en el programa y los indejos de IP.


Pero no se leer las lineas siguentes
if(((ko≡0)&(k>2))&IP(k),ko:k-2,continue)
Y no entiendo como hacer los cambios indejos en IP(k).

Puedes explicarmelo por favor?

Necesito el entendimiento para los graficos

Gracias

Pedro

En ingles:

Now, the parameters of the problem have changed as the material is different.
I have achieved to make the change up to the definition of the function that give the single values.
There is one parameter less.
Obviously, I have to make the necessary changes in the program and to the indexes.

But I don't know how to read
if(((ko≡0)&(k>2))&IP(k),ko:k-2,continue)
And what's the exact purpose of IP(k)

Can you please explain them?

I need to understand the concepts in order to make the changes for plotting the data.

Thanks,

Pierre
Offline Razonar  
#9 Posted : 08 January 2023 08:00:29(UTC)
Razonar


Rank: Advanced Member

Groups: Registered
Joined: 28/08/2014(UTC)
Posts: 1,356
Uruguay

Was thanked: 815 time(s) in 516 post(s)
Hola Pedro. Feliz año, igualmente. El problema a resolver es hallar el punto de inflexión de la curva dada por (x,y) = (M7,M6). Esto puede hacerse derivando M6 respecto a M7 y hallando los ceros de esa derivada, lo cual no parece algo fácil de hacer, ni siquiera numéricamente. Otra aproximación es discretizar sobre un índice, en este caso k, y detectar a partir de la definición de concavidad el momento en que ésta cambia, lo cual es la definición de punto de inflexión y es lo que se evalúa con IP(k). Para detectarlo y almacenarlo en ko, es la línea

if(((ko≡0)&(k>2))&IP(k),ko:k-2,continue)

Primero preguntas si ko es cero, por lo cual es el primer punto de inflexión, si k > 2 para asegurarte que puedas evaluar IP(k), pues IP(1) y IP(2) dan error, y finalmente si IP(k) = 1 (se puede omitir el igual a uno). Si las 3 preguntas son ciertas guardas k - 2 en ko, y si no continúas el lazo.

Esta otra versión hace más o menos lo mismo, excepto que detecta los dos puntos de inflexión.

pTM AlAsSb 3.0 auto v1 2020-04-26_plot 2 inflex.sm (52kb) downloaded 13 time(s).

Espero eso explique el algoritmo.
Saludos cordiales.
Alvaro.



Hello Pedro. Happy New Year, too. The problem to solve is to find the inflection point of the curve given by (x,y) = (M7,M6). This can be done by differentiating M6 with respect to M7 and finding the zeros of that derivative, which doesn't seem like an easy thing to do, even numerically. Another approach is to discretize on an index, in this case k, and detect from the definition of concavity the moment in which it changes, which is the definition of inflection point and is what is evaluated with IP(k). To detect it and store it in ko, it is the line

if(((ko≡0)&(k>2))&IP(k),ko:k-2,continue)

You first ask if ko is zero, so it is the first inflection point, if k > 2 to make sure that you can evaluate IP(k), since IP(1) and IP(2) fail, and finally if IP(k) = 1 (equal to one can be omitted). If all those 3 questions are true, you keep k - 2 in ko, and if you don't continue the loop.

This other version does more or less the same thing, except that it detects the two inflection points.

pTM AlAsSb 3.0 auto v1 2020-04-26_plot 2 inflex.sm (52kb) downloaded 13 time(s).

Hope that explains the algorithm.
Best regards.
Alvaro.

Edited by user 08 January 2023 08:25:45(UTC)  | Reason: Not specified

Offline pTM  
#10 Posted : 10 January 2023 05:18:04(UTC)
pTM


Rank: Member

Groups: Registered
Joined: 20/05/2022(UTC)
Posts: 22
United States
Location: Sunnyvale

Hola Alvaro,
* Intente resolver la hoja del compuesto binario pero hay un error que no entiendo.
"result is above max allowed positive number" en el bucle
Pero la funcion f por si sola da una respuesta sensata.
Es en el bucle que f no parece funccionar

Averigue como solucionar el error con eval y Optimization / Numeric, pero no resolvio el error.
(Y ahora encontraras eval por todos los lugares).

* Anade lo siguente
- Una matriz 2D replaza a los vectores M1...M8. Lo necesito para guardar my datos en la computadora.
- Los desconozidos han de ser positivos para tener un sentido fisico. De vez en cuando aparecen como negativos y tengo que rechazarlos.
(De vez en cuando, (pzi-pi) es un negativo y tengo tambien que rechazarlo).
Es possible incorporar esa restriccion al progama ?
- La matriz es exportada al final
- El nombre del fichero es contruido con los parametros del experimento

* La hoja del ternario AlAsSb con el indice IP para detectar los dos puntos de inflexion no funciono con mi computadora.

Gracias,

Pedro


* I came across this error when tayloring the worksheet to the binary:
"result is above max allowed positive number" for the Loop

But the function f appears fine for the first pass out of the loop.
The error seems to be with the loop.

The recomanded method for the resolution of the issue is using eval and switch to a numeric optimization.
But it didn't help. I left in the worksheet many eval requests.

* Few changes have been made to the program
- The many vectors have been replaced by a single 2D matrix for convenience.
- Unkown pA and pB must be positive numbers to keep a physical meaning.
Every so often, negative numbers show up as solutions and I have to discard the result.
Sometimes pzi - pi is negative and the solution is rejected.
Can the constraints be incorporated to the program ?
- The matrix is saved after the calculation
- The filename is built from the experiment parameters.

Thanks again for the help,

VSD06 G14 12 Binary.sm (47kb) downloaded 5 time(s).
AlAsSb.png
Offline pTM  
#11 Posted : 10 January 2023 18:33:13(UTC)
pTM


Rank: Member

Groups: Registered
Joined: 20/05/2022(UTC)
Posts: 22
United States
Location: Sunnyvale

Hello all,

Here is a revised worksheet.

* Parameters are in matrix format (pz, Mp) for a more condensed program (later "if" test of negative values is in loop)
* First pass is using as a guess the solution calculated for the definition of the function.
* Next pass in the loop is using the previous solution as a guess

* The issue is with the use of the function in the loop. The error goes away once removed.

Thanks for helping

Pierre

VSD06 G14 12 Binary.sm (56kb) downloaded 8 time(s).

Edited by user 10 January 2023 18:36:03(UTC)  | Reason: Not specified

Offline Jean Giraud  
#12 Posted : 10 January 2023 21:21:17(UTC)
Jean Giraud

Rank: Guest

Groups: Registered
Joined: 04/07/2015(UTC)
Posts: 6,866
Canada

Was thanked: 981 time(s) in 809 post(s)
You may want testing try on error from f(x) menu
Offline pTM  
#13 Posted : 10 January 2023 22:08:21(UTC)
pTM


Rank: Member

Groups: Registered
Joined: 20/05/2022(UTC)
Posts: 22
United States
Location: Sunnyvale

Hello All,
Try / on error does something. The error vanished.
But I am still getting nothing.

How to I get to display the result matrix out of the program ?
The file doesn't appear to save. Maybe it's an empty matrix ?
How is the plot defined from a 2D matrix?

Thanks for the help,

Pierre VSD06 G14 12 BNR rev.sm (47kb) downloaded 4 time(s).
Offline Razonar  
#14 Posted : 10 January 2023 22:15:45(UTC)
Razonar


Rank: Advanced Member

Groups: Registered
Joined: 28/08/2014(UTC)
Posts: 1,356
Uruguay

Was thanked: 815 time(s) in 516 post(s)
Originally Posted by: pTM Go to Quoted Post
...
Here is a revised worksheet. ...


Hi. In your original version you have M6 = Pal( Pas,Psb,PzSb ) and M7 = PzSb/{PzAs+PzSb}, but now you don't have that function anymore for the partial pressures, and M7 = x(...). So, basically, you're solving a very different problem now and can't use the same steps in the loop. Unlike the previous problem, which was a fairly well-known case study in process engineering, I am not able to identify what type of problem this new approach addresses.

About the error in the image from your previous posts, it seems that you are using an old SMath version, which does not have the option for use 'if' with only two arguments.

Best regards.
Alvaro.
Offline pTM  
#15 Posted : 10 January 2023 22:57:25(UTC)
pTM


Rank: Member

Groups: Registered
Joined: 20/05/2022(UTC)
Posts: 22
United States
Location: Sunnyvale

Thanks for the feedback.

The function gives a solution outside the loop. It can't work in a program ?


Gracias,

Pierre
Offline Razonar  
#16 Posted : 10 January 2023 23:12:20(UTC)
Razonar


Rank: Advanced Member

Groups: Registered
Joined: 28/08/2014(UTC)
Posts: 1,356
Uruguay

Was thanked: 815 time(s) in 516 post(s)
Originally Posted by: pTM Go to Quoted Post
...
The function gives a solution outside the loop. ...


Nope.

Clipboard01.gif

Best regards.
Alvaro.

Offline pTM  
#17 Posted : 10 January 2023 23:42:13(UTC)
pTM


Rank: Member

Groups: Registered
Joined: 20/05/2022(UTC)
Posts: 22
United States
Location: Sunnyvale

Thank you for your time.

I collected 10 points one by one for an earlier set of parameters.
See plot.

Blue line is noise. Data are useless.
Red line looks good.
It is in line with the expected response of the system.

It seems to work sometimes.

Gracias

AB.png
Offline Jean Giraud  
#18 Posted : 11 January 2023 00:08:25(UTC)
Jean Giraud

Rank: Guest

Groups: Registered
Joined: 04/07/2015(UTC)
Posts: 6,866
Canada

Was thanked: 981 time(s) in 809 post(s)
Originally Posted by: pTM Go to Quoted Post
Try / on error does something. The error vanished.
But I am still getting nothing.

Mathcad uses NaN [Not a Number]
T,G has used ^-307 as NaN
I suspect Smath Try on error is 10^-15 or close

Offline pTM  
#19 Posted : 11 January 2023 00:31:01(UTC)
pTM


Rank: Member

Groups: Registered
Joined: 20/05/2022(UTC)
Posts: 22
United States
Location: Sunnyvale

Merci Jean
Offline Jean Giraud  
#20 Posted : 11 January 2023 15:43:34(UTC)
Jean Giraud

Rank: Guest

Groups: Registered
Joined: 04/07/2015(UTC)
Posts: 6,866
Canada

Was thanked: 981 time(s) in 809 post(s)
Merci Jean ... Bienvenue Pierre.
The Smath try/on error appears in 3 applications.
1. Laplace admittance circuit analysis ... works fine.
2. Rotate RGB or gray scale image ... a piece of gold.
3. Thiele interpolation sometimes fails.
Sorry, I could not make your solve bloc work.
Cheers ... Jean.

onError.PNG
Users browsing this topic
3 Pages123>
Forum Jump  
You cannot post new topics in this forum.
You cannot reply to topics in this forum.
You cannot delete your posts in this forum.
You cannot edit your posts in this forum.
You cannot create polls in this forum.
You cannot vote in polls in this forum.