Sympy - fraction manipulation - latex

I basically want Sympy to generate latex code \frac{x-1}{3} = y but whenever I ask it generate the Tex component of things Sympy always returns \frac{x}{3} - \frac{1}{3} .
How do I avoid splitting up the equations, and assign an equals operator to another variable.
I have not attempted to add the "y =" part to the code yet as I wanted to clarify the fraction situation first, but since I have had to come cap in hand to stack exchange I thought I would ask both questions. I have been through every tutorial page I could find but to no avail.
Any help would be much appreciated although I would ask you keep it relatively simple !!!
Thanks in advance .
import sympy
from sympy import *
x = Symbol("x")
a = (x-Integer(1))
b = (3)
c = a/b
print(latex(c))

The issue comes from sympy automatically expanding (x-1)/3 into x/3-1/3. So one solution is to ask sympy to factor this back:
In [18]: c = a/b; c
Out[18]: x/3 - 1/3
In [19]: d = c.factor(); d
Out[19]: (x - 1)/3
In [20]: print(latex(d))
\frac{1}{3} \left(x - 1\right)

Related

Provide custom gradient to drake::MathematicalProgram

Drake has an interface where you can give it a generic function as a constraint and it can set up the nonlinearly-constrained mathematical program automatically (as long as it supports AutoDiff). I have a situation where my constraint does not support AutoDiff (the constraint function conducts a line search to approximate the maximum value of some function), but I have a closed-form expression for the gradient of the constraint. In my case, the math works out so that it's difficult to find a point on this function, but once you have that point it's easy to linearize around it.
I know many optimization libraries will allow you to provide your own analytical gradient when available; can you do this with Drake's MathematicalProgram as well? I could not find mention of it in the MathematicalProgram class documentation.
Any help is appreciated!
It's definitely possible, but I admit we haven't provided helper functions that make it pretty yet. Please let me know if/how this helps; I will plan to tidy it up and add it as an example or code snippet that we can reference in drake.
Consider the following code:
from pydrake.all import AutoDiffXd, MathematicalProgram, Solve
prog = MathematicalProgram()
x = prog.NewContinuousVariables(1, 'x')
def cost(x):
return (x[0]-1.)*(x[0]-1.)
def constraint(x):
if isinstance(x[0], AutoDiffXd):
print(x[0].value())
print(x[0].derivatives())
return x
cost_binding = prog.AddCost(cost, vars=x)
constraint_binding = prog.AddConstraint(
constraint, lb=[0.], ub=[2.], vars=x)
result = Solve(prog)
When we register the cost or constraint with MathematicalProgram in this way, we are allowing that it can get called with either x being a float, or x being an AutoDiffXd -- which is simply a wrapping of Eigen's AutoDiffScalar (with dynamically allocated derivatives of type double). The snippet above shows you roughly how it works -- every scalar value has a vector of (partial) derivatives associated with it. On entry to the function, you are passed x with the derivatives of x set to dx/dx (which will be 1 or zero).
Your job is to return a value, call it y, with the value set to the value of your cost/constraint, and the derivatives set to dy/dx. Normally, all of this happens magically for you. But it sounds like you get to do it yourself.
Here's a very simple code snippet that, I hope, gets you started:
from pydrake.all import AutoDiffXd, MathematicalProgram, Solve
prog = MathematicalProgram()
x = prog.NewContinuousVariables(1, 'x')
def cost(x):
return (x[0]-1.)*(x[0]-1.)
def constraint(x):
if isinstance(x[0], AutoDiffXd):
y = AutoDiffXd(2*x[0].value(), 2*x[0].derivatives())
return [y]
return 2*x
cost_binding = prog.AddCost(cost, vars=x)
constraint_binding = prog.AddConstraint(
constraint, lb=[0.], ub=[2.], vars=x)
result = Solve(prog)
Let me know?

mosek parameter settings in cvxpy

I am trying to set "mosek_param" settings, but, am getting errors. For instance, for the following case
MSK_IPAR_INTPNT_SOLVE_FORM
Controls whether the primal or the dual problem is solved.
Default:
"FREE"
Accepted:
"FREE", "PRIMAL", "DUAL"
Example:
param.MSK_IPAR_INTPNT_SOLVE_FORM = 'MSK_SOLVE_FREE'
Groups:
Interior-point method
from https://docs.mosek.com/9.0/toolbox/parameters.html --> I tried
prob.solve(solver=MOSEK,
mosek_params={mosek.iparam.intpnt_solve_form: mosek.solve.primal}, # mosek.iparam.presolve_use:mosek.presolvemode.off
verbose=True)
but, run into errors .... the commented part works.
When I was working in Matlab --> using
cvx_solver_settings('MSK_IPAR_INTPNT_SOLVE_FORM','MSK_SOLVE_PRIMAL')
worked well for me. But, doesn't work in the present case. Also, I was able to set precision as follows
cvx_precision low
but, cannot do so now. Is there another way to do both of these in cvxpy? thank you.
PS: this question has also been posted in the CVXPY forum --> https://groups.google.com/forum/#!topic/cvxpy/MEAewGMlqjI
Below is an example
# Solves a bounded least-squares problem.
import mosek
from cvxpy import *
import numpy
# Problem data.
m = 10
n = 5
numpy.random.seed(1)
A = numpy.random.randn(m, n)
b = numpy.random.randn(m)
# Construct the problem
x = Variable(n)
objective = Minimize(sum_squares(A*x - b))
constraints = [0 <= x, x <= 1]
prob = Problem(objective, constraints)
prob.solve(solver=MOSEK,
mosek_params={mosek.iparam.intpnt_solve_form: mosek.solve.primal}, # mosek.iparam.presolve_use:mosek.presolvemode.off
verbose=True)
which gives me the error. I also tried using 'MSK_IPAR_INTPNT_SOLVE_FORM' = 'MSK_SOLVE_PRIMAL' but to no avail.
Look at
https://docs.mosek.com/9.1/pythonapi/parameters.html#mosek.iparam.intpnt_solve_form
The correct form is
mosek.solveform.primal

Matrix calculator - pascal program - command line

I would like to make matrix calculator, but I struggle a little bit, how to make an input of the program. I have commands that user can use in calculator. Some takes 1 argument, 2 arguments or 3 arguments. I was inspired by program on this website http://www.ivank.net/blogspot/matrix_pascal/matrices.pas
But I don't really understand, how the input is made. Program from the website use parse, split procedures, but I don't know, how does it work. Does it exists some website, where it is good explained (Parse in Pascal)? I would like to really understand it.
This is, how it should looks like:
command: sum X Y
command: multiply X
command: transpose X
In the sample which inspired you, all the calculation is realized by the 'procedure parse(command:String);'.
The first step consists to extract the command and all parameters by:
com := Split(command, ' ');
In your case, you will obtain for 'command: sum X Y':
Length(com) = 3
com[0] = 'sum'; com[1] = 'X'; com[2] = 'Y';
But, be carefull, the 'X' and 'Y' parameters shall not have characters between numbers.

F# Compiler Services incorrectly parses program

UPDATE:
I now realize that the question was stupid, I should have just filed the issue. In hindsight, I don't see why I even asked this question.
The issue is here: https://github.com/fsharp/FSharp.Compiler.Service/issues/544
Original question:
I'm using FSharp Compiler Services for parsing some F# code.
The particular piece of code that I'm facing right now is this:
let f x y = x+y
let g = f 1
let h = (g 2) + 3
This program yields a TAST without the (+) call on the last line. That is, the compiler service returns TAST as if the last line was just let h = g 2.
The question is: is this is a legitimate bug that I ought to report or am I missing something?
Some notes
Here is a repo containing minimal repro (I didn't want to include it in this question, because Compiler Services require quite a bit of dancing around).
Adding more statements after the let h line does not change the outcome.
When compiled to IL (as opposed to parsed with Compiler Services), it seems to work as expected (e.g. see fiddle)
If I make g a value, the program parses correctly.
If I make g a normal function (rather than partially applied one), the program parses correctly.
I have no priori experience with FSharp.Compiler.Services but nevertheless I did a small investigation using Visual Studio's debugger. I analyzed abstract syntax tree of following string:
"""
module X
let f x y = x+y
let g = f 1
let h = (g 2) + 3
"""
I've found out that there's following object inside it:
App (Val (op_Addition,NormalValUse,D:\file.fs (6,32--6,33) IsSynthetic=false),TType_forall ([T1; T2; T3],TType_fun (TType_var T1,TType_fun (...,...))),...,...,...)
As you can see, there's an addition in 6th line between characters 32 and 33.
The most likely explanation why F# Interactive doesn't display it properly is a bug in a library (maybe AST is in an inconsistent state or pretty-printing is broken). I think that you should file a bug in project's issue tracker.
UPDATE:
Aforementioned object can be obtained in a debbuger in a following way:
error.[0]
(option of Microsoft.FSharp.Compiler.SourceCodeServices.FSharpImplementationFileDeclaration.Entity)
.Item2
.[2]
(option of Microsoft.FSharp.Compiler.SourceCodeServices.FSharpImplementationFileDeclaration.MemberOrFunctionOrValue)
.Item3
.f (private member)
.Value
(option of Microsoft.FSharp.Compiler.SourceCodeServices.FSharpExprConvert.ConvExprOnDemand#903)
.expr

py3k print significant figures

In python3 is there a nice way to set significant figures - i.e if I have a list:
l = [2.2738257169723513, 2.2725769281387329, 2.3101812601089478]
I can use the nice new print system and do
print(*l,sep="\t")
But I'm unclear as to how to set the sigfig with out doing
m = "%.2f, %.2f, %.2f" % (l[0], l[1], l[2])
print(m)
I was wondering if there was an option to print to just say - print all floats to 2 dp?
I guess I could use a loop but that seems not very Python like
Actually, it is definitely pythonic, and it is the only way to do what you're asking. That said, you can still use a comprehension to make this more concise (in this cause a tuple, but you can use a list or use list(map():
# I've changed the name to float_list because l should not be
# used as a variable name in Python according to the standard
# style recommendations
print(*('{0:.2f}'.format(x) for x in float_list), sep="\t")

Resources