Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

Access to all the coefficients of an expression seems to fail

I would like to know how is an expression store internally to capture the coefficients of complex expressions. In Mathematica, an expression is store as a tree and descending it you can have access to any part.

The following shows the difficulty I have encounter in trying to find the coefficients of an equation to restructure it.

var('x y p w_0 θ I')
assume(p>=0)
assume(p<=1)
assume(θ>=1)
U = function('U')#déclare U comme le nom d'une fonction
EU(x,y,p) = p * U(x) + (1-p) * U(y)
w_1 = function('w_1')
w_1(w_0, π) = (w_0-π)
w_2 = function('w_2')
w_2(w_0, π, x, I, p) = (w_0 - π) - x + I 
π = function('π')
π(p,I,θ)=θ*p*I
U = function('U')
EU(x, y, p) = p*U(x) + (1 - p)*U(y)
x, y, p, w_0, θ, I, = SR.var('x y p w_0 θ I')
f = EU(w_1(w_0, π(p,I,θ)),w_2(w_0, π, x, I, π(p,I,θ)) )
h = diff(f, I)
hh = use_prime(h)
k = diff(f, I,2)
kk = use_prime(k)
show(LatexExpr(r'''\text{La condition d'optimalité du premier ordre est } dEU = 0 \text{, soit : } ''' ))
show(LatexExpr(r'\,\,\,\,\,\,\,\,\,\,\,\,\,\, dEU = '),hh, ' = 0')
d2EU=diff(EU(w_1(w_0, π),w_2(w_0, π, x, I, p),p),I,2)
show(LatexExpr(r'''\text{La condition d'optimalité du second ordre est } dEU = 0 \text{, soit : } ''' ))
def latex_with_few_minuses(frac):
    numer, denom = frac.numerator_denominator()
    permutations = ((1, numer, denom), (-1, numer, -denom), (-1, -numer, denom), (1, -numer, -denom))
    total_minuses = lambda args: sum(str(latex(arg)).count('-') for arg in args)
    prefactor, numer, denom = min(permutations, key=total_minuses)
    return LatexExpr(('-' if prefactor == -1 else '') + r'\frac{' + latex(numer) + '}{' + latex(denom) + '}')


show(LatexExpr(r'\,\,\,\,\,\,\,\,\,\,\,\,\,\,'),kk, ' < 0')
show(kk.coefficient(p^3).coefficient(θ^2)) # <-- this works
show(kk.coefficient((p*θ - 1)^2)) # <-- this works showing that composition works
show(kk.coefficient((p*θ - 1)^2).coefficient((p - 1))) # <-- this returns 0

Access to all the coefficients of an expression seems to fail

I would like to know how is an expression store internally to capture the coefficients of complex expressions. In Mathematica, an expression is store as a tree and descending it you can have access to any part.

The following shows the difficulty I have encounter in trying to find the coefficients of an equation to restructure it.

var('x y p w_0 θ I')
assume(p>=0)
assume(p<=1)
assume(θ>=1)
U = function('U')#déclare U comme le nom d'une fonction
EU(x,y,p) = p * U(x) + (1-p) * U(y)
w_1 = function('w_1')
w_1(w_0, π) = (w_0-π)
w_2 = function('w_2')
w_2(w_0, π, x, I, p) = (w_0 - π) - x + I 
π = function('π')
π(p,I,θ)=θ*p*I
U = function('U')
EU(x, y, p) = p*U(x) + (1 - p)*U(y)
x, y, p, w_0, θ, I, = SR.var('x y p w_0 θ I')
f = EU(w_1(w_0, π(p,I,θ)),w_2(w_0, π, x, I, π(p,I,θ)) )
h = diff(f, I)
hh = use_prime(h)
k = diff(f, I,2)
kk = use_prime(k)
show(LatexExpr(r'''\text{La condition d'optimalité du premier ordre est } dEU = 0 \text{, soit : } ''' ))
show(LatexExpr(r'\,\,\,\,\,\,\,\,\,\,\,\,\,\, dEU = '),hh, ' = 0')
d2EU=diff(EU(w_1(w_0, π),w_2(w_0, π, x, I, p),p),I,2)
show(LatexExpr(r'''\text{La condition d'optimalité du second ordre est } dEU = 0 \text{, soit : } ''' ))
def latex_with_few_minuses(frac):
    numer, denom = frac.numerator_denominator()
    permutations = ((1, numer, denom), (-1, numer, -denom), (-1, -numer, denom), (1, -numer, -denom))
    total_minuses = lambda args: sum(str(latex(arg)).count('-') for arg in args)
    prefactor, numer, denom = min(permutations, key=total_minuses)
    return LatexExpr(('-' if prefactor == -1 else '') + r'\frac{' + latex(numer) + '}{' + latex(denom) + '}')


show(LatexExpr(r'\,\,\,\,\,\,\,\,\,\,\,\,\,\,'),kk, ' < 0')
show(kk.coefficient(p^3).coefficient(θ^2)) # <-- this works
show(kk.coefficient((p*θ - 1)^2)) # <-- this works showing that composition works
show(kk.coefficient((p*θ - 1)^2).coefficient((p - 1))) # <-- this returns 0

Access to all the coefficients of an expression seems to fail

I would like to know how is an a complex expression store stored internally to capture the its coefficients of complex expressions. composed variable. In Mathematica, an expression is store as a tree and and, descending it it, you can have access to any part.

The following shows the difficulty I have encounter encounterd in trying to find the coefficients of an equation to restructure it.

var('x y p w_0 θ I')
assume(p>=0)
assume(p<=1)
assume(θ>=1)
U = function('U')#déclare U comme le nom d'une fonction
EU(x,y,p) = p * U(x) + (1-p) * U(y)
w_1 = function('w_1')
w_1(w_0, π) = (w_0-π)
w_2 = function('w_2')
w_2(w_0, π, x, I, p) = (w_0 - π) - x + I 
π = function('π')
π(p,I,θ)=θ*p*I
U = function('U')
EU(x, y, p) = p*U(x) + (1 - p)*U(y)
x, y, p, w_0, θ, I, = SR.var('x y p w_0 θ I')
f = EU(w_1(w_0, π(p,I,θ)),w_2(w_0, π, x, I, π(p,I,θ)) )
h = diff(f, I)
hh = use_prime(h)
k = diff(f, I,2)
kk = use_prime(k)
show(LatexExpr(r'''\text{La condition d'optimalité du premier ordre est } dEU = 0 \text{, soit : } ''' ))
show(LatexExpr(r'\,\,\,\,\,\,\,\,\,\,\,\,\,\, dEU = '),hh, ' = 0')
d2EU=diff(EU(w_1(w_0, π),w_2(w_0, π, x, I, p),p),I,2)
show(LatexExpr(r'''\text{La condition d'optimalité du second ordre est } dEU = 0 \text{, soit : } ''' ))
def latex_with_few_minuses(frac):
    numer, denom = frac.numerator_denominator()
    permutations = ((1, numer, denom), (-1, numer, -denom), (-1, -numer, denom), (1, -numer, -denom))
    total_minuses = lambda args: sum(str(latex(arg)).count('-') for arg in args)
    prefactor, numer, denom = min(permutations, key=total_minuses)
    return LatexExpr(('-' if prefactor == -1 else '') + r'\frac{' + latex(numer) + '}{' + latex(denom) + '}')


show(LatexExpr(r'\,\,\,\,\,\,\,\,\,\,\,\,\,\,'),kk, ' < 0')
show(kk.coefficient(p^3).coefficient(θ^2)) # <-- this works
show(kk.coefficient((p*θ - 1)^2)) # <-- this works showing that composition works
show(kk.coefficient((p*θ - 1)^2).coefficient((p - 1))) # <-- this returns 0

And the last return is obviously false.

Access to all the coefficients of an expression seems to fail

I would like to know how is a complex expression stored internally to capture its coefficients of composed variable. In Mathematica, an expression is store as a tree and, descending it, you can have access to any part.

The following shows the difficulty I have encounterd in trying to find the coefficients of an equation to restructure it.

var('x y p w_0 θ I')
assume(p>=0)
assume(p<=1)
assume(θ>=1)
U = function('U')#déclare U comme le nom d'une fonction
EU(x,y,p) = p * U(x) + (1-p) * U(y)
w_1 = function('w_1')
w_1(w_0, π) = (w_0-π)
w_2 = function('w_2')
w_2(w_0, π, x, I, p) = (w_0 - π) - x + I 
π = function('π')
π(p,I,θ)=θ*p*I
U = function('U')
EU(x, y, p) = p*U(x) + (1 - p)*U(y)
x, y, p, w_0, θ, I, = SR.var('x y p w_0 θ I')
f = EU(w_1(w_0, π(p,I,θ)),w_2(w_0, π, x, I, π(p,I,θ)) )
h = diff(f, I)
hh = use_prime(h)
k = diff(f, I,2)
kk = use_prime(k)
show(LatexExpr(r'''\text{La condition d'optimalité du premier ordre est } dEU = 0 \text{, soit : } ''' ))
show(LatexExpr(r'\,\,\,\,\,\,\,\,\,\,\,\,\,\, dEU = '),hh, ' = 0')
d2EU=diff(EU(w_1(w_0, π),w_2(w_0, π, x, I, p),p),I,2)
show(LatexExpr(r'''\text{La condition d'optimalité du second ordre est } dEU = 0 \text{, soit : } ''' ))
def latex_with_few_minuses(frac):
    numer, denom = frac.numerator_denominator()
    permutations = ((1, numer, denom), (-1, numer, -denom), (-1, -numer, denom), (1, -numer, -denom))
    total_minuses = lambda args: sum(str(latex(arg)).count('-') for arg in args)
    prefactor, numer, denom = min(permutations, key=total_minuses)
    return LatexExpr(('-' if prefactor == -1 else '') + r'\frac{' + latex(numer) + '}{' + latex(denom) + '}')


show(LatexExpr(r'\,\,\,\,\,\,\,\,\,\,\,\,\,\,'),kk, ' < 0')
show(kk.coefficient(p^3).coefficient(θ^2)) kk_0=kk.coefficient(p^3).coefficient(θ^2)
kk_1=kk.coefficient((p*θ - 1)^2)
show(kk_0) # <-- this works
show(kk.coefficient((p*θ - 1)^2)) show(kk_1) # <-- this works showing that composition works
show(kk.coefficient((p*θ - 1)^2).coefficient((p - 1))) composit show(kk_2) # <-- this returns 0

0 kk_1.coefficient((p-1)) And the last return is obviously false.

false.

Access to all the coefficients of an expression seems to fail

#################################### 0

I would like to know how is a complex expression stored internally to capture its coefficients of composed variable. In Mathematica, an expression is store as a tree and, descending it, you can For at least 3 days, I have access to any part.

The following shows the difficulty I have encounterd in trying to find the coefficients of an equation to restructure it.fightes with SageMath to construct this code which works nicely.

    def use_prime(expr):
    """
    Return the expression with one-variable function derivatives "prime
    """
    op = expr.operator()
    if op:
        args = expr.operands()
        aargs = (use_prime(a) for a in args)
        opp = op
        if (isinstance(op, sage.symbolic.operators.FDerivativeOperator)and len(args) == 1):
            name = op.function().name()
            primes = "’" * len(op.parameter_set())
            opp = function(f"{name}{primes}")
        return opp(*aargs)
    else:
        return expr


###################################### 1

var('x y p w_0 θ I')
assume(p>=0)
assume(p<=1)
assume(θ>=1)
U = function('U')#déclare U comme le nom d'une fonction
EU(x,y,p) = p * U(x) + (1-p) * U(y)
w_1 = function('w_1')
w_1(w_0, π) = (w_0-π)
w_2 = function('w_2')
w_2(w_0, π, x, I, p) = (w_0 - π) - x + I 
π = function('π')
π(p,I,θ)=θ*p*I
π(p,I,θ)=θ*(1-p)*I
U = function('U')
EU(x, y, p) = p*U(x) + (1 - p)*U(y)
x, y, p, w_0, θ, I, = SR.var('x y p w_0 θ I')
f = EU(w_1(w_0, π(p,I,θ)),w_2(w_0, π, x, I, π(p,I,θ)) )
h = diff(f, I)
hh = use_prime(h)
k = diff(f, I,2)
kk = use_prime(k)
show(LatexExpr(r'''\text{L'assuré cherche à résoudre le programme suivant :} '''))
show(LatexExpr(r'''I^\star=  \textrm{argmax}_{\{I\}}\left\{pU(w_1)+(1-p) U(w_2)| w_1=w_0 - \pi, w_2=w_0 - \pi -x + I, \pi = \theta(1-p)I \right\} '''))     
show(LatexExpr(r'''\text{ou encore : } I^\star = \textrm{argmax}_{\{I\}}\{'''), f,LatexExpr(r'\}'))     
show(LatexExpr(r'''\text{La condition d'optimalité du premier ordre est } dEU d\mathbb{E}U = 0 \text{, soit : } ''' ))
show(LatexExpr(r'\,\,\,\,\,\,\,\,\,\,\,\,\,\, dEU d\mathbb{E}U = '),hh, ' = 0')
d2EU=diff(EU(w_1(w_0, π),w_2(w_0, π, x, I, p),p),I,2)
show(LatexExpr(r'''\text{La condition d'optimalité du second ordre est } dEU d\mathbb{E}U = 0 \text{, soit : } ''' ))
def latex_with_few_minuses(frac):
    numer, denom = frac.numerator_denominator()
    permutations = ((1, numer, denom), (-1, numer, -denom), (-1, -numer, denom), (1, -numer, -denom))
    total_minuses = lambda args: sum(str(latex(arg)).count('-') for arg in args)
    prefactor, numer, denom = min(permutations, key=total_minuses)
    return LatexExpr(('-' if prefactor == -1 else '') + r'\frac{' + latex(numer) + '}{' + latex(denom) + '}')


show(LatexExpr(r'\,\,\,\,\,\,\,\,\,\,\,\,\,\,'),kk, ' < 0')
kk_0=kk.coefficient(p^3).coefficient(θ^2)
kk_1=kk.coefficient((p*θ - 1)^2)
show(kk_0) # <-- this works
show(kk_1) # <-- this works showing that composit show(kk_2) # <-- this returns 0  
kk_1.coefficient((p-1))
And the last return is obviously false.

######################################################## 2

show(LatexExpr(r'\text{Commençons par vérifier si la condition du second ordre est vérifiée}'))
show(LatexExpr(r'\text{On va réécrire à la main la condition du second ordre de manière à obtenir une équation algébrique en substituant une variable positive}'))
show(LatexExpr(r'U2 > 0. \text{ Pour ce faire, il faut réussir à isoler } U^{\prime\prime}.'))
var('A')
U1=hh.expand().coefficient(θ).coefficient(p).subs(2==A).coefficient(A)
U2=hh.coefficient(θ).coefficient(p)
show(U1)
show(U2)
eqn=(U1/U2==(p - 1)*p*θ/ ((p - 1)*θ + 1)*(p - 1))
eqn1=((U1/U2)==(p - 1)*p*θ/ ((p - 1)*θ + 1)*(p - 1))
show(eqn1)

subs(2==A) is not self evident since a priori replace a constant by an other doesn't come naturaly in mind. I have been oblige to take some contournment road since I cannot ask what is he coefficient of say $(p-1)^2*\theta$. My question is why ?

Secondly, I would like to know if there is a more automatic way to arrive to the eqn equation. That is if there is a solution to transform an equation 'eqn = (A-B==0)' in a second one 'eqn1 = (A==B)' (of course if 'A' and 'B' where only parameters or variables I could do it with solve(A==B, A) but I use 'A' and 'B' to save typping.

Thirdly, I would like to substitute 'x' to 'I' and '1' to '\theta' and look what is the result. But nothing I have tried works. Thanks for your help

Access to all the coefficients of an expression seems to fail

#################################### 0

For at least 3 days, I have fightes with SageMath to construct this code which works nicely.

    def use_prime(expr):
    """
    Return the expression with one-variable function derivatives "prime
    """
    op = expr.operator()
    if op:
        args = expr.operands()
        aargs = (use_prime(a) for a in args)
        opp = op
        if (isinstance(op, sage.symbolic.operators.FDerivativeOperator)and len(args) == 1):
            name = op.function().name()
            primes = "’" * len(op.parameter_set())
            opp = function(f"{name}{primes}")
        return opp(*aargs)
    else:
        return expr


###################################### 1

var('x y p w_0 θ I')
assume(p>=0)
assume(p<=1)
assume(θ>=1)
U = function('U')#déclare U comme le nom d'une fonction
EU(x,y,p) = p * U(x) + (1-p) * U(y)
w_1 = function('w_1')
w_1(w_0, π) = (w_0-π)
w_2 = function('w_2')
w_2(w_0, π, x, I, p) = (w_0 - π) - x + I 
π = function('π')
π(p,I,θ)=θ*(1-p)*I
U = function('U')
EU(x, y, p) = p*U(x) + (1 - p)*U(y)
x, y, p, w_0, θ, I, = SR.var('x y p w_0 θ I')
f = EU(w_1(w_0, π(p,I,θ)),w_2(w_0, π, x, I, π(p,I,θ)) )
h = diff(f, I)
hh = use_prime(h)
k = diff(f, I,2)
kk = use_prime(k)
show(LatexExpr(r'''\text{L'assuré cherche à résoudre le programme suivant :} '''))
show(LatexExpr(r'''I^\star=  \textrm{argmax}_{\{I\}}\left\{pU(w_1)+(1-p) U(w_2)| w_1=w_0 - \pi, w_2=w_0 - \pi -x + I, \pi = \theta(1-p)I \right\} '''))     
show(LatexExpr(r'''\text{ou encore : } I^\star = \textrm{argmax}_{\{I\}}\{'''), f,LatexExpr(r'\}'))     
show(LatexExpr(r'''\text{La condition d'optimalité du premier ordre est } d\mathbb{E}U = 0 \text{, soit : } ''' ))
show(LatexExpr(r'\,\,\,\,\,\,\,\,\,\,\,\,\,\, d\mathbb{E}U = '),hh, ' = 0')
d2EU=diff(EU(w_1(w_0, π),w_2(w_0, π, x, I, p),p),I,2)
show(LatexExpr(r'''\text{La condition d'optimalité du second ordre est } d\mathbb{E}U = 0 \text{, soit : } ''' ))
show(LatexExpr(r'\,\,\,\,\,\,\,\,\,\,\,\,\,\,'),kk, ' < 0')

######################################################## 2

show(LatexExpr(r'\text{Commençons par vérifier si la condition du second ordre est vérifiée}'))
show(LatexExpr(r'\text{On va réécrire à la main la condition du second ordre de manière à obtenir une équation algébrique en substituant une variable positive}'))
show(LatexExpr(r'U2 > 0. \text{ Pour ce faire, il faut réussir à isoler } U^{\prime\prime}.'))
var('A')
U1=hh.expand().coefficient(θ).coefficient(p).subs(2==A).coefficient(A)
U2=hh.coefficient(θ).coefficient(p)
show(U1)
show(U2)
eqn=(U1/U2==(p - 1)*p*θ/ ((p - 1)*θ + 1)*(p - 1))
eqn1=((U1/U2)==(p - 1)*p*θ/ ((p - 1)*θ + 1)*(p - 1))
show(eqn1)

subs(2==A) is not self evident since a priori replace a constant by an other doesn't come naturaly in mind. I have been oblige to take some contournment road since I cannot ask what is he coefficient of say $(p-1)^2*\theta$. My question is why ?

Secondly, I would like to know if there is a more automatic way to arrive to the eqn equation. That is if there is a solution to transform an equation 'eqn = (A-B==0)' eqn = (A-B==0) in a second one 'eqn1 = (A==B)' eqn1 = (A==B) (of course if 'A' A and 'B' B where only parameters or variables I could do it with solve(A==B, A) but I use 'A' A and 'B' B to save typping.

Thirdly, I would like to substitute 'x' to 'I' x to I and '1' to '\theta' 1 to \theta and look what is the result. But nothing I have tried works. Thanks for your help

Access to all the coefficients of an expression seems to fail

#################################### 0

For at least 3 days, I have fightes fighted with SageMath to construct this code which works nicely.

    def use_prime(expr):
    """
    Return the expression with one-variable function derivatives "prime
    """
    op = expr.operator()
    if op:
        args = expr.operands()
        aargs = (use_prime(a) for a in args)
        opp = op
        if (isinstance(op, sage.symbolic.operators.FDerivativeOperator)and len(args) == 1):
            name = op.function().name()
            primes = "’" * len(op.parameter_set())
            opp = function(f"{name}{primes}")
        return opp(*aargs)
    else:
        return expr


###################################### 1

var('x y p w_0 θ I')
assume(p>=0)
assume(p<=1)
assume(θ>=1)
U = function('U')#déclare U comme le nom d'une fonction
EU(x,y,p) = p * U(x) + (1-p) * U(y)
w_1 = function('w_1')
w_1(w_0, π) = (w_0-π)
w_2 = function('w_2')
w_2(w_0, π, x, I, p) = (w_0 - π) - x + I 
π = function('π')
π(p,I,θ)=θ*(1-p)*I
U = function('U')
EU(x, y, p) = p*U(x) + (1 - p)*U(y)
x, y, p, w_0, θ, I, = SR.var('x y p w_0 θ I')
f = EU(w_1(w_0, π(p,I,θ)),w_2(w_0, π, x, I, π(p,I,θ)) )
h = diff(f, I)
hh = use_prime(h)
k = diff(f, I,2)
kk = use_prime(k)
show(LatexExpr(r'''\text{L'assuré cherche à résoudre le programme suivant :} '''))
show(LatexExpr(r'''I^\star=  \textrm{argmax}_{\{I\}}\left\{pU(w_1)+(1-p) U(w_2)| w_1=w_0 - \pi, w_2=w_0 - \pi -x + I, \pi = \theta(1-p)I \right\} '''))     
show(LatexExpr(r'''\text{ou encore : } I^\star = \textrm{argmax}_{\{I\}}\{'''), f,LatexExpr(r'\}'))     
show(LatexExpr(r'''\text{La condition d'optimalité du premier ordre est } d\mathbb{E}U = 0 \text{, soit : } ''' ))
show(LatexExpr(r'\,\,\,\,\,\,\,\,\,\,\,\,\,\, d\mathbb{E}U = '),hh, ' = 0')
d2EU=diff(EU(w_1(w_0, π),w_2(w_0, π, x, I, p),p),I,2)
show(LatexExpr(r'''\text{La condition d'optimalité du second ordre est } d\mathbb{E}U = 0 \text{, soit : } ''' ))
show(LatexExpr(r'\,\,\,\,\,\,\,\,\,\,\,\,\,\,'),kk, ' < 0')

######################################################## 2

show(LatexExpr(r'\text{Commençons par vérifier si la condition du second ordre est vérifiée}'))
show(LatexExpr(r'\text{On va réécrire à la main la condition du second ordre de manière à obtenir une équation algébrique en substituant une variable positive}'))
show(LatexExpr(r'U2 > 0. \text{ Pour ce faire, il faut réussir à isoler } U^{\prime\prime}.'))
var('A')
U1=hh.expand().coefficient(θ).coefficient(p).subs(2==A).coefficient(A)
U2=hh.coefficient(θ).coefficient(p)
show(U1)
show(U2)
eqn=(U1/U2==(p - 1)*p*θ/ ((p - 1)*θ + 1)*(p - 1))
eqn1=((U1/U2)==(p - 1)*p*θ/ ((p - 1)*θ + 1)*(p - 1))
show(eqn1)

subs(2==A) is not self evident since a priori replace a constant by an other doesn't come naturaly in mind. I have been oblige to take some contournment road since I cannot ask what is he coefficient of say $(p-1)^2*\theta$. My question is why ?

Secondly, I would like to know if there is a more automatic way to arrive to the eqn equation. That is if there is a solution to transform an equation eqn = (A-B==0) in a second one eqn1 = (A==B) (of course if A and B where only parameters or variables I could do it with solve(A==B, A) but I use A and B to save typping.

Thirdly, I would like to substitute x to I and 1 to \theta and look what is the result. But nothing I have tried works. Thanks for your help

Access to all the coefficients of an expression seems to fail

#################################### 0

For at least 3 days, I have fighted been fighting with SageMath to construct this code which works nicely.

 def use_prime(expr):
    """
    Return the expression with one-variable function derivatives "prime
    """
    op = expr.operator()
    if op:
        args = expr.operands()
        aargs = (use_prime(a) for a in args)
        opp = op
        if (isinstance(op, sage.symbolic.operators.FDerivativeOperator)and sage.symbolic.operators.FDerivativeOperator)
                and len(args) == 1):
            name = op.function().name()
            primes = "’" * len(op.parameter_set())
            opp = function(f"{name}{primes}")
        return opp(*aargs)
    else:
        return expr


###################################### ### 1

var('x y p w_0 θ I')
assume(p>=0)
assume(p<=1)
assume(θ>=1)
assume(p >= 0)
assume(p <= 1)
assume(θ >= 1)
U = function('U')#déclare function('U')  # déclare U comme le nom d'une fonction
EU(x,y,p) EU(x, y, p) = p * U(x) + (1-p) (1 - p) * U(y)
w_1 = function('w_1')
w_1(w_0, π) = (w_0-π)
(w_0 - π)
w_2 = function('w_2')
w_2(w_0, π, x, I, p) = (w_0 - π) - x + I 
π = function('π')
π(p,I,θ)=θ*(1-p)*I
π(p, I, θ)=θ*(1-p)*I
U = function('U')
EU(x, y, p) = p*U(x) p * U(x) + (1 - p)*U(y)
p) * U(y)
x, y, p, w_0, θ, I, = SR.var('x y p w_0 θ I')
f = EU(w_1(w_0, π(p,I,θ)),w_2(w_0, π, x, I, π(p,I,θ)) π(p, I, θ)) )
h = diff(f, I)
hh = use_prime(h)
k = diff(f, I,2)
I, 2)
kk = use_prime(k)
show(LatexExpr(r'''\text{L'assuré show(LatexExpr(r'''\text{L’assuré cherche à résoudre le programme suivant :} '''))
show(LatexExpr(r'''I^\star=  show(LatexExpr(r'''I^\star = \textrm{argmax}_{\{I\}}\left\{pU(w_1)+(1-p) U(w_2)| w_1=w_0 w_1'''
               r'''=w_0 - \pi, w_2=w_0 w_2 = w_0 - \pi -x + I, \pi = \theta(1-p)I \right\} '''))     
'''))
show(LatexExpr(r'''\text{ou encore : } I^\star = \textrm{argmax}_{\{I\}}\{'''), f,LatexExpr(r'\}')) \textrm{argmax}_{\{I\}}\{'''),
     f, LatexExpr(r'\}'))     
show(LatexExpr(r'''\text{La condition d'optimalité d’optimalité du premier ordre est } d\mathbb{E}U '''
               r'''d\mathbb{E}U = 0 \text{, soit : } ''' ))
'''))
show(LatexExpr(r'\,\,\,\,\,\,\,\,\,\,\,\,\,\, d\mathbb{E}U = '),hh, ' = 0')
d2EU=diff(EU(w_1(w_0, π),w_2(w_0, d2EU = diff(EU(w_1(w_0, π), w_2(w_0, π, x, I, p),p),I,2)
p), p), I, 2)
show(LatexExpr(r'''\text{La condition d'optimalité d’optimalité du second ordre est } d\mathbb{E}U '''
               r'''d\mathbb{E}U = 0 \text{, soit : } ''' ))
show(LatexExpr(r'\,\,\,\,\,\,\,\,\,\,\,\,\,\,'),kk, '''))
show(LatexExpr(r'\,\,\,\,\,\,\,\,\,\,\,\,\,\,'), kk, ' < 0')

######################################################## ### 2

show(LatexExpr(r'\text{Commençons par vérifier si la condition du '
               r'du second ordre est vérifiée}'))
show(LatexExpr(r'\text{On va réécrire à la main la condition du second ordre de '
               r'de manière à obtenir une équation algébrique en '
               r'en substituant une variable positive}'))
show(LatexExpr(r'U2 > 0. \text{ Pour ce faire, il faut réussir à isoler } U^{\prime\prime}.'))
'
               r'U^{\prime\prime}.'))
var('A')
U1=hh.expand().coefficient(θ).coefficient(p).subs(2==A).coefficient(A)
U2=hh.coefficient(θ).coefficient(p)
U1 = hh.expand().coefficient(θ).coefficient(p).subs(2 == A).coefficient(A)
U2 = hh.coefficient(θ).coefficient(p)
show(U1)
show(U2)
eqn=(U1/U2==(p - 1)*p*θ/ eqn = (U1/U2 == (p - 1) * p * θ / ((p - 1)*θ 1) * θ + 1)*(p 1) * (p - 1))
eqn1=((U1/U2)==(p - 1)*p*θ/ eqn1 = ((U1/U2) == (p - 1) * p * θ / ((p - 1)*θ 1) * θ + 1)*(p 1) * (p - 1))
show(eqn1)

subs(2==A) is not self evident since a priori replace replacing a constant by an other another one doesn't a priori come naturaly in mind. to mind naturally. I have been oblige forced to take some contournment road detours since I cannot ask what is he coefficient of say $(p-1)^2*\theta$. $(p-1)^2*\theta$. My question is why ?why.

Secondly, I would like to know if there is a more automatic way to arrive to at the eqn equation. equation. That is is, if there is a solution to transform an equation eqn = (A-B==0) in a second one eqn1 = (A==B) (of course if A and B where only parameters or variables I could do it with solve(A==B, A) but I use A and B to save typping.typing.

Thirdly, I would like to substitute x to I and 1 to \theta and look what is the result. result. But nothing I have tried works. Thanks for your helphelp.

Access to all the coefficients of an expression seems to fail

For at least 3 days, I have been fighting with SageMath to construct this code which works nicely.

def use_prime(expr):
    """
    Return the expression with one-variable function derivatives "prime
in prime notation.
    """
    op = expr.operator()
    if op:
        args = expr.operands()
        aargs = (use_prime(a) for a in args)
        opp = op
        if (isinstance(op, sage.symbolic.operators.FDerivativeOperator)
                and len(args) == 1):
            name = op.function().name()
            primes = "’" * len(op.parameter_set())
            opp = function(f"{name}{primes}")
        return opp(*aargs)
    else:
        return expr

### 1

var('x y p w_0 θ I')
assume(p >= 0)
assume(p <= 1)
assume(θ >= 1)
U = function('U')  # déclare U comme le nom d'une fonction
EU(x, y, p) = p * U(x) + (1 - p) * U(y)
w_1 = function('w_1')
w_1(w_0, π) = (w_0 - π)
w_2 = function('w_2')
w_2(w_0, π, x, I, p) = (w_0 - π) - x + I 
π = function('π')
π(p, I, θ)=θ*(1-p)*I
U = function('U')
EU(x, y, p) = p * U(x) + (1 - p) * U(y)
x, y, p, w_0, θ, I, = SR.var('x y p w_0 θ I')
f = EU(w_1(w_0, π(p,I,θ)),w_2(w_0, π, x, I, π(p, I, θ)) )
h = diff(f, I)
hh = use_prime(h)
k = diff(f, I, 2)
kk = use_prime(k)
show(LatexExpr(r'''\text{L’assuré cherche à résoudre le programme suivant :} '''))
show(LatexExpr(r'''I^\star = \textrm{argmax}_{\{I\}}\left\{pU(w_1)+(1-p) U(w_2)| w_1'''
               r'''=w_0 - \pi, w_2 = w_0 - \pi -x + I, \pi = \theta(1-p)I \right\} '''))
show(LatexExpr(r'''\text{ou encore : } I^\star = \textrm{argmax}_{\{I\}}\{'''),
     f, LatexExpr(r'\}'))     
show(LatexExpr(r'''\text{La condition d’optimalité du premier ordre est } '''
               r'''d\mathbb{E}U = 0 \text{, soit : } '''))
show(LatexExpr(r'\,\,\,\,\,\,\,\,\,\,\,\,\,\, d\mathbb{E}U = '),hh, ' = 0')
d2EU = diff(EU(w_1(w_0, π), w_2(w_0, π, x, I, p), p), I, 2)
show(LatexExpr(r'''\text{La condition d’optimalité du second ordre est } '''
               r'''d\mathbb{E}U = 0 \text{, soit : } '''))
show(LatexExpr(r'\,\,\,\,\,\,\,\,\,\,\,\,\,\,'), kk, ' < 0')

### 2

show(LatexExpr(r'\text{Commençons par vérifier si la condition '
               r'du second ordre est vérifiée}'))
show(LatexExpr(r'\text{On va réécrire à la main la condition du second ordre '
               r'de manière à obtenir une équation algébrique '
               r'en substituant une variable positive}'))
show(LatexExpr(r'U2 > 0. \text{ Pour ce faire, il faut réussir à isoler } '
               r'U^{\prime\prime}.'))
var('A')
U1 = hh.expand().coefficient(θ).coefficient(p).subs(2 == A).coefficient(A)
U2 = hh.coefficient(θ).coefficient(p)
show(U1)
show(U2)
eqn = (U1/U2 == (p - 1) * p * θ / ((p - 1) * θ + 1) * (p - 1))
eqn1 = ((U1/U2) == (p - 1) * p * θ / ((p - 1) * θ + 1) * (p - 1))
show(eqn1)

subs(2==A) is not self evident since replacing a constant by another one doesn't a priori come to mind naturally. I have been forced to take some detours since I cannot ask what is he coefficient of say $(p-1)^2*\theta$. My question is why.

Secondly, I would like to know if there is a more automatic way to arrive at the eqn equation. That is, if there is a solution to transform an equation eqn = (A-B==0) in a second one eqn1 = (A==B) (of course if A and B where only parameters or variables I could do it with solve(A==B, A) but I use A and B to save typing.

Thirdly, I would like to substitute x to I and 1 to \theta and look what is the result. But nothing I have tried works. Thanks for your help.