Python Forum

Full Version: Need to fix SyntaxError in cycle try
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Pages: 1 2
Hi!
In this block, I need to try all combinations of variables in the ht expression and save only those combinations that ensure the equality of the ht to zero.
I have lists of values for each variable used in expression ht. The variable o is an array whose columns contain interrelated values for 2 variables and that values should to be sorted line by line.

I got a SyntaxError in try (invalid syntax). I also used to change the condition with "try" by using the construction with "if" and "insclose(ht, 0)" instead of "ht == 0", but I get the same syntax error.
Please tell me where this error came from and how to fix it.

for i in z30:
  for o in zres:
    for l in z70:
      def function_gam0(et0, y30, ph0b, o, l):
        ht = o[0] * et0 * cos(i) / sqrt(ph0b) + o[1] * -et0 * sin(i) / sqrt(ph0b) + l * sqrt(1 / ph0b) * et0 * sin(i) + funct_labt(i, o[1], l, o[0]) * (sqrt(1 / ph0b) * (1 + et0 * cos(i) * (1 + et0 * cos(i)**2) / ph0b**2
        try:
          ht == 0
          if True:
            lh0 = i, o[0], o[1], l
            return lh0
            print(lh0)
        except:
          pass
There is so much wrong that this really can't be called Python code.

In response to one of your earlier posts I mentioned that you do not define functions inside loops. Instead of this:
for i in range(10):
    def square():
        return i**2
Do this:
def square(number):  # Declare function outside of loop
    return number**2

for i in range(10):
    print(square(i))   # Call function inside of loop.
I don't know what you are trying to do with this:
try:
    ht == 0
    if True:
        lh0 = i, o[0], o[1], l
        return lh0
        print(lh0)
except:
    pass
Are you trying to do this?
if ht == 0:
    return i, o[0], o[1], l
try/except catch exceptions. An exception is raised when your program tries to do something but fails. An example is trying to open a file. Your program has a reasonable expectation that opening a file should work, but maybe the file was deleted. Exceptions are not used to fix bad code, they are used to handle potential errors that can occur when executing correct code.

Syntax errors are not exceptions, they are invalid code. You need to correct the code. Try/except cannot catch a syntax error because syntax errors prevent running your program.

You should not use == when comparing float numbers. Your equation may return a value really close to zero, but it is unlikely any combination of arguments will produce a result that is exactly zero. That is just the nature of floating point math on computers; ridiculous resolution, but almost never results that are exactly right. Read about it here:

https://docs.python.org/3/tutorial/floatingpoint.html

Instead of testing == 0, use math.is_close() or numpy.is_close().

https://docs.python.org/3/library/math.html
https://numpy.org/doc/stable/reference/g...close.html
if math.isclose(ht, 0, abs_tol=1.0e-9)
Try to clean up some of these errors and if you are still having problems post your updated code and an explanation of what you are trying to do. Last time I tried to help I was hindered by never really knowing what you wanted to do, and your code was not helping my understanding.
I transfer a solved physics problem to python. Its task is to solve a system of differential equations with conditions (the Cauchy problem) in a cycle for different vectors of initial values (y0 in solve_ivp). After this, I have to define the optimal solution among these obtained - i.e. the one that satisfies the optimality condition.

What I am doing now: I applied basics conditions for variables and I have collected all possible variables' values for t0 - i.e. a set of values for each variable (these combinations are a set of y0 vectors that can be provided in solve_ivp, but these are many that aren't solution). Now, in order to form vectors y0 that will be provided to solve_ivp, I need to apply the condition that ht is equal to zero (this is the main condition of the problem) and to collect (in list format) only these combinations of elements that satisfy the condition. There are indeed combinations of elements that will ensure that ht is equal to zero (with a given accuracy).

I have the following difficulty: each set of variable' values is a list or an array and I have to iterate each variable through the elements i.e. through the values. Otherwise, the function try to accept lists or arrays instead of one value and this leads to an error. So I made this mistake with function definition.

My updated code is below, it seems to work, but takes a really long time.

def function_gam(et, y3, phb, kj, y7):
  ht = kj[0] * et * cos(y3) / sqrt(phb) + kj[1] * -et0 * sin(y3) / sqrt(phb) + y7 * sqrt(1 / phb) * et0 * sin(y3) + funct_labt(y3, kj[1], y7, kj[0]) * (sqrt(1 / phb) * (1 + et * cos(y3) * (1 + et * cos(y3)**2) / phb**2))
  return ht

for i in z30: # iteratation through values for variable z30
  for o in zres: # iteratation through values for array zres which includes 2 interconnected variales. The values of the first are in zres[0], for the other - in zres[1]
    for l in z70: # iteratation through values for variable z70
      ht0 = function_gam(et0, i, ph0b, o, l)
      if isclose(ht0, 0, abs_tol=1.0e-9): # only these combinations of variables values are collected that satisfy the condition ht == 0
        lh0 = i, o[0], o[1], l
        print(lh0)
Line 2 is 219 characters long. It is way too long. A good rule of thumb is that a line should not exceed 70 or 80 characters. In Python, one can achieve this by enclosing long expressions in parentheses, for example
idef function_gam(et, y3, phb, kj, y7):
  ht = (
      kj[0] * et * cos(y3) / sqrt(phb)
      + kj[1] * -et0 * sin(y3) / sqrt(phb)
      + y7 * sqrt(1 / phb) * et0 * sin(y3)
      + funct_labt(y3, kj[1], y7, kj[0])
        * (sqrt(1 / phb) * (
            1 + et * cos(y3) * (1 + et * cos(y3)**2) / phb**2)))
  return ht
 
This line could perhaps be further divided in several lines.
(Mar-24-2022, 10:17 AM)Gribouillis Wrote: [ -> ]Line 2 is 219 characters long. It is way too long. A good rule of thumb is that a line should not exceed 70 or 80 characters. In Python, one can achieve this by enclosing long expressions in parentheses, for example
idef function_gam(et, y3, phb, kj, y7):
  ht = (
      kj[0] * et * cos(y3) / sqrt(phb)
      + kj[1] * -et0 * sin(y3) / sqrt(phb)
      + y7 * sqrt(1 / phb) * et0 * sin(y3)
      + funct_labt(y3, kj[1], y7, kj[0])
        * (sqrt(1 / phb) * (
            1 + et * cos(y3) * (1 + et * cos(y3)**2) / phb**2)))
  return ht
 
This line could perhaps be further divided in several lines.

Thank you!
The code was running over 2 hours, and during that time, I haven't received any results. But once I tried to accelerate the code by using @njit, already few minutes later the first result occurred. However, now it works over 2 hours in the way presented below, and I received only 10 vectors. How can I accelerate loops by using F2PY?

@njit
def function_gam(et0, y30, ph0b, ot, y70):
  ht = ot[0] * et0 * np.cos(y30) / np.sqrt(ph0b) + ot[1] * -et0 * np.sin(y30) / np.sqrt(ph0b) + y70 * np.sqrt(1 / ph0b) * et0 * np.sin(y30) + funct_labt(y30, ot, y70) * (np.sqrt(1 / ph0b) * (1 + et0 * np.cos(y30) * (1 + et0 * np.cos(y30)**2) / ph0b**2))
  return ht

@njit
def funct_labt(y30, ot, y70):
  y80 = ot[1] * et0 *(np.sin(y30)) / np.sqrt(ph0b) - y70 * (ph0b * et0 * (np.sin(y30)) / (1 + et0 * np.cos(y30)))**2 + (-ot[0] * et0 *(np.cos(y30)) / np.sqrt(ph0b))
  return y80

tol = E-5

for i in z30:
  # iteratation through values for variable z30
  for o in zres: # iteratation through values for array zres which includes 2 interconnected variales. The values of the first are in zres[0], for the other - in zres[1]
    for l in z70: # iteratation through values for variable z70
      ht0 = function_gam(et0, i, ph0b, o, l)
      if np.isclose(ht0, 0): # only these combinations of variables values are collected that satisfy the condition ht == 0
        lh0 = i, o[0], o[1], l
        print(lh0)
Write your code in C++. You aren't deriving any benefit from Python, so why use it?
(Mar-24-2022, 05:23 PM)deanhystad Wrote: [ -> ]Write your code in C++. You aren't deriving any benefit from Python, so why use it?

Python seems to be more convenient for me as for beginner and it is good as a visualization tool. I think about using libraries for C++ or Fortran that may contribute to productivity. Are there ways to accelerate my loops by using F2PY?
(Mar-24-2022, 05:23 PM)deanhystad Wrote: [ -> ]Write your code in C++. You aren't deriving any benefit from Python, so why use it?

I know that Numba can be successfully used for accelerating loops and the calculation will be even faster than C++, but cannot find how to apply it. Probably you know?
Perhaps the following will help (perhaps not):
Solve Differential Equations in Python

In this link, search for Cauchy problem
Experiments with SymPy to solve first-order ordinary differential equations
Pages: 1 2