0

I have one more question on numpy python module syntax, which I would like to convert into regular python 2.7 syntax. Here is the numpy version:

if any((var.theta < 0) | (var.theta >= 90)):
    print('Input incident angles <0 or >=90 detected For input angles with absolute value greater than 90, the ' + 'modifier is set to 0. For input angles between -90 and 0, the ' + 'angle is changed to its absolute value and evaluated.')
    var.theta[(var.theta < 0) | (var.theta >= 90)]=abs((var.theta < 0) | (var.theta >= 90))

source code: https://github.com/Sandia-Labs/PVLIB_Python/blob/master/pvlib/pvl_physicaliam.py#L93-95

If we pretend that numpy arrays are one dimensional, would regular python 2.7 syntax look something like this:

newTheta = []
for item in var.theta:
    if (item < 0) and (item >= 90):
        print('Input incident angles <0 or >=90 detected For input angles with absolute value greater than 90, the ' + 'modifier is set to 0. For input angles between -90 and 0, the ' + 'angle is changed to its absolute value and evaluated.')
        newItem = abs(item)
        newTheta.append(newItem)

?? Thank you for the reply.

Will Holmgren
  • 696
  • 5
  • 12
marco
  • 899
  • 5
  • 13
  • 21

1 Answers1

2

In words, what the if any((var.theta < 0) | (var.theta >= 90)) expression means: "If any of the entries in var.theta are less than zero or are greater than or equal to 90, do..."

What your flow of control statement says is "If an entry of var.theta is less than 0 and greater than or equal to 90, do...".

If you really meant or in the plain Python example, then yes, it would look like this. Alternatively though, you could use list comprehension:

newTheta = [abs(item) for item in var.theta if (item < 0 or item >= 90)]

List comprehension is more compact, which for simple operations is easier to read, and is easier for the interpreter to optimize.

mobiusklein
  • 1,403
  • 9
  • 12
  • Thank you for the reply MobiusKlein. So in numpy `|` replaces `or`. What about `and`? What is the replacement syntax for `and`? – marco Nov 10 '14 at 09:58
  • 1
    Numpy overloads the binary and operator '&' to do vectorized logical ands. The code would be like so `cond_1 & cond_2`, and in the plain Python case, the and keyword is all you need. – mobiusklein Nov 10 '14 at 13:05