What is this operator *= -1 - python

I'm going through some Python activities and was given example code with this operator: y *= -1
I had a look through the relevant Python docs, to no avail.
I know y += 1, for example, is short for y = y + 1. So is this y = y * -1 y equals y times -1 maybe?
Closest thing in Python docs I could find is this: x * y: product of x and y
Is this it?

In the vast majority of the cases
y *= <expr>
is the same as
y = y * <expr>
but in the general case, it is interpreted as:
y = imul(y, <expr>)
which is then equivalent to:
y = y.__imul__(<expr>)
if y's type overrides __imul__.
This means that if y's type overrides the inplace multiplication operator, y*=<expr> is performed inplace, while y=y*<expr> is not.
EDIT
It might not be immediately clear why the assignment is needed, i.e. why it is intrepreted as y = imul(y, <expr>), and not just imul(y, <expr>).
The reason is that it makes a lot of sense for the following two scenarios to give the same result:
c = a * b
and
c = a
c *= b
Now, this of course works if a and b are of the same type (e.g. floats, numpy arrays, etc.), but if they aren't, it is possible for the result of the operation to have the type of b, in which case the operation cannot be an inplace operation of a, thus the result needs to be assigned to a, in order to achieve the correct behavior.
For example, this works, thanks to the assignment:
from numpy import arange
a = 2
a *= arange(3)
a
=> array([0, 2, 4])
Whereas if the assignment is dropped, a remains unchanged:
a = 2
imul(a, arange(3))
=> array([0, 2, 4])
a
=> 2

Yes that's correct. It just means multiply the left-hand value by negative the right-hand value. They're both arithmetic operators that differ simply by operation and expression binding, so I believe +/* are parallel everywhere else in overloads.
y = y * -1

Related

CVXPY set Z to 1 if B is positive

So here's the problem. I have this variable Z which follows the following rule:
I'm guessing Z should be defined as so:
Z = cvxpy.Variable(shape=shape_j_t, name="Z", boolean=True)
So Z is constrained(?) to the balance "B". How do I inform the solver that Z should be 1 if B is positive and 0 otherwise? Especially given that B itself is composed of other cvxpy.Variables.
The general approach, assuming a-priori knowledge about bounds (which are needed in general) on B looks like:
b <= UB * z
b >= LB * z
z in {0, 1}
which describes:
z = 0 <-> b = 0
z = 1 <-> LB <= b <= UB
But this is just something general and these things usually are designed having the full model in mind. Here we don't know what you are doing exactly. Sometimes we don't need equivalence but just implication (e.g. ignore the LB-constraint...)
Maybe it's not trivial to define the notion of positive balance as you only got inequalities and using LB=0 would express non-negativity, but not strict positiveness. For the latter, some a-priori definition of some epsilon (e.g. 0.001) would be needed.

inverted indicator constraint in gurobipy

I am a beginner in gurobipy. I would like to add an inverted indicator constraint.
Indicator constraint is nothing but depending on a binary variable a constraint does or does not hold.
In gurobipy this is written as
model.addConstr((x == 1) >> (y + z <= 5))
where x is a binary variable, y and z are integer variables. This statement says that if x is True then the constraint y+z <= 5 holds.
But I would like to have an inverted constraint like this.
If y+z <= 5 then x == 1. But gurobi does not allow the lhs part of the statement to be an inequality. It can only be a binary variable equal to a constant (0 or 1).
So the inverted statement throws an error.
model.addConstr((y + z <= 5) >> (x == 1))
Any ideas how to rewrite such a conditional constraint in gurobipy?!
The implication
y+z ≤ 5 ⇒ x = 1
can be rewritten as:
x = 0 ⇒ y+z ≥ 6
This can be directly implemented as an indicator constraint.
This is based on propositional logic. This is called transposition:
A ⇒ B
⇔
not B ⇒ not A
So in theory we have
y+z ≤ 5 ⇒ x = 1
⇔
x = 0 ⇒ y+z > 5
If x and y are integers we can say x = 0 ⇒ y+z ≥ 6 If they are continuous variables you could do: x = 0 ⇒ y+z ≥ 5.0001 (in practice I would do: x = 0 ⇒ y+z ≥ 5 and keep things ambiguous at y+z = 5).
This is kind of a standard trick when using indicator constraints. It seems not everyone is aware of or appreciates this.
The indicator syntax is
binary expression >> linear constraint
So your constraint is invalid. You need a different model that forces x to 1 when y + z ≤ 5. Assuming y, z are non-negative integers, try 6x + y + z ≥ 6.
I think the best way to go with this one is to use the big-M approach
Let reconsider the problem you are trying to model
If y+z <= 5 then x == 1
It is equivalent to if y+z-5 <= 0 then x==1
From here we need a logic that will turn on and off the variable x depending on the condition on the y+z-5
y + z - 5 <= M(1-x)
will do the trick. Note that the x will need to be 1 for the relationship to hold if y+z-5 <= 0 which is what we want. Similarly, x will be turned off (set to 0) if y+z-5 >= 0
I hope this helps

How to find negative imaginary parts of values in an array then turning them to positive?

I have a function a=x*V where x assumes thousands of values as x = arange(1,1000,0.1) and V is a combination of other constants. These make a always complex (has nonzero real and imaginary parts). However, because a depends on other values, the imag(a) can be negative for some x's.
For what I am doing, however, I need imag(a) to be always positive, so I need to take the negative values and turn them into positive.
I have tried doing
if imag(a)<0:
imag(a) = -1*imag(a)
That didn't seem to work because it gives me the error: SyntaxError: Can't assign to function call. I thought it was because it's an array so I tried any() and all(), but that didn't work either.
I'm out of options now.
IIUC:
In [35]: a = np.array([1+1j, 2-2j, 3+3j, 4-4j])
In [36]: a.imag *= np.where(a.imag < 0, -1, 1)
In [37]: a
Out[37]: array([ 1.+1.j, 2.+2.j, 3.+3.j, 4.+4.j])
You can't redefine a function that way. It would be like saying
sqrt(x) = 2*sqrt(x)
What you can do is reassign the value of a (not imag(a)).
if imag(a) < 0
a = a - 2*imag(a)*j
For example, if a = 3 - 5j, then it would give you
3 - 5j - 2(-5)j = 3 + 5j
It appears to be faster than doing subtraction. For a full function:
import numpy as np
def imag_abs(x):
mask = x.imag < 0
x[mask] = np.conj(x[mask])
return x

Evaluating first-order arithmetic formulas

Is there a python package for evaluating bounded first-order arithmetic formulas?
For example, it gets a bounded first-order arithmetic expression
>>> exp = 'forall x < z exists y < x ((2 * y + 1 = x) or (2 * y = x))'
and a value for the free variable z
>>> tau = [(z,20)]
and returns its value
>>> eval(exp, tau)
False
Maybe what you are looking for is something called "quantifier elimination". If so, take a look at QEPCAD. [1] It may be easier to create a Python interface for QEPCAD than to find a Python implementation.
[1] http://www.usna.edu/CS/~qepcad/B/QEPCAD.html

What does *= mean in python? [duplicate]

This question already has answers here:
What is this operator *= -1
(2 answers)
Closed 9 years ago.
For example in this code:
def product(list):
p =1
for i in list:
p *= i
return p
I found this code, but I need to be able to explain each and every part of it.
It's shorthand for
p = p * i
It's analogous to the more frequently encountered p += i
Taken from the first result in google:
Multiply AND assignment operator, It multiplies right operand with the left operand and assign the result to left operand
*= is the same as saying p = p * i.
This link contains a list of all the operators in their various, wonderful combinations.
Example
A pseudo-code explanation of your code is as follows:
assume list := {4, 6, 5, 3, 5, 1}
p := 1.
for(each number in list)
p = the current value of p * the current number.
// So: 1 * 4, 4 * 6, 24 * 5, 120 * 3...
return p.
Usually p *= i is the same as p = p * i.
Sometimes it can be different, and I think the explanations already posted aren't clear enough for that, so:
It can be different when p is a mutable object. In that case the in-place *= may modify the original object instead of creating a new one. Compare what happens to q in each of these:
>>> p = q = [2]
>>> p *= 5
>>> p
[2, 2, 2, 2, 2]
>>> q
[2, 2, 2, 2, 2]
>>> p = q = [2]
>>> p = p * 5
>>> p
[2, 2, 2, 2, 2]
>>> q
[2]
If can also be different when p is a complex expression with side effects as the in-place version only evaluates sub-expressions once. So for example:
aList[randint(0, 5)] *= 3
is not the same as:
aList[randint(0, 5)] = aList[randint(0, 5)] * 3
It's not exactly the same as p = p * i:
>>> class A(int):
... def __imul__(self, item):
... print '__imul__ is running!'
...
... def __mul__(self, item):
... print '__mul__ is running!'
>>> mynumber = A(10)
>>> mynumber *= 5
__imul__ is running!
>>> mynumber = A(10)
>>> mynumber * 5
__mul__ is running!
However the output is mostly the same, so you should probably treat it so
The idea behind the operator a *= b is to mean the same as a = a * b. In most cases (as in yours) it will do exactly this, so it multiplies a variable with a value and stores the result in the variable again.
The notation using *= might be faster (depending on the classes involved), and it is, in any case, the clearer version, so it should be favored. Its main advantage shows if the variable a is itself already a complex expression like myGiantValueField[f(42)].getValue()[3]:
myGiantValueField[f(42)].getValue()[3] = myGiantValueField[f(42)].getValue()[3] * 3
is certainly less readable and due to code doubling more prone to fixing-errors than
myGiantValueField[f(42)].getValue()[3] *= 3
In general, though, the operator *= calls the method __imul__() of the variable a and hands over the argument b, so it means exactly the same as a.__imul__(b) (which isn't as intuitive).
Why could there be a difference between a = a * b and a *= b? Three reasons come two mind at once, but there might be more.
A class could implement only the *= operator (so a * b could be undefined although a *= b exists) due to performance aspects. Multiplying a very large value (e. g. a giant matrix) with a number is sometimes better done in-place to avoid having to allocate memory for the result (which might at once after computation be copied into the original variable by the assignment). That a = a * b is internally sth like tmp = a * b and a = tmp.
A class might find its use unintuitive using the direct multiplication, hence it could leave the * operator unimplemented. An example might be a class representing the volume of the computer speaker. Doubling the volume might make sense (volumeKnob *= 2) whereas computing it without using (assigning) it is not recommended (x = volumeKnob * 2? ← makes no sense as it does nothing).
If the type of the result of the multiplication differs from the type of a, I would not expect or recommend implementing the *= operator as it would be misleading. An example might be if a and b are vectors whose multiplication result would be a matrix (or a number). The name __imul__ already suggests that it is meant for being applied iteratively, i. e. more than once. But if a's type changed, this would be problematic.

Categories

Resources