Skip to content

Instantly share code, notes, and snippets.

@jgillis
Last active January 4, 2017 20:18
Show Gist options
  • Save jgillis/5aebf6b09ada29355418783e8f60e8ef to your computer and use it in GitHub Desktop.
Save jgillis/5aebf6b09ada29355418783e8f60e8ef to your computer and use it in GitHub Desktop.
function ret = classify_linear(e,v)
%
% Takes vector expression e, and symbolic primitives v
% Returns classification vector
% For each element in e, determines if:
% - element is nonlinear in v (2)
% - element is linear in v (1)
% - element does not depend on v at all (0)
%
% This method can be sped up a lot with JacSparsityTraits::sp
%
% Example:
% x =SX.sym('x');
% y =SX.sym('y');
% p =SX.sym('p');
% e = [0 x y p x*y x*p sin(x) cos(y) sqrt(x+y) p*p*x x*y*p]';
% classify_linear(e,[x;y])
%
% > 0 1 1 0 2 1 2 2 2 1 2
import casadi.*
f = Function('f',{v},{jacobian(e,v)});
ret = ((sum2(IM(f.sparsity_out(0),1))==0)==0);
ret = ret.nonzeros();
pattern = IM(f.sparsity_jac(0,0),1).reshape(size(e,1),-1);
pattern_sum = sum2(pattern);
for k=pattern_sum.row()
ret(k+1)=2;
end
end
from casadi import *
def classify_linear(e,v):
"""
Takes vector expression e, and symbolic primitives v
Returns classification vector
For each element in e, determines if:
- element is nonlinear in v (2)
- element is linear in v (1)
- element does not depend on v at all (0)
This method can be sped up a lot with JacSparsityTraits::sp
"""
f = Function("f",[v],[jacobian(e,v)])
ret = ((sum2(IM(f.sparsity_out(0),1))==0)==0).nonzeros()
pattern = IM(f.sparsity_jac(0,0),1).reshape((e.shape[0],-1))
for k in sum2(pattern).row():
ret[k]=2
return ret
x =SX.sym("x")
y =SX.sym("y")
p =SX.sym("p")
e = vertcat(0,x,y,p,x*y,x*p,sin(x),cos(y),sqrt(x+y),p*p*x,x*y*p)
print classify_linear(e,vertcat(x,y))
def classify_linear(e,v):
"""
Takes vector expression e, and symbolic primitives v
Returns classification vector
For each element in e, determines if:
- element is nonlinear in v (2)
- element is linear in v (1)
- element does not depend on v at all (0)
This method can be sped up a lot with JacSparsityTraits::sp
"""
try:
f = SXFunction("f",[v],[jacobian(e,v)])
except:
f = MXFunction("f",[v],[jacobian(e,v)])
ret = ((sumCols(IMatrix(f.outputSparsity(0),1))==0)==0).nonzeros()
pattern = DMatrix(f.jacSparsity(0,0),1).reshape((e.shape[0],-1))
s2 = sumCols(pattern)
if pattern.isscalar() and pattern.size()==0:
s2 = pattern
for k in s2.row():
ret[k]=2
return ret
x =SX.sym("x")
y =SX.sym("y")
p =SX.sym("p")
e = vertcat([0,x,y,p,x*y,x*p,sin(x),cos(y),sqrt(x+y),p*p*x,x*y*p])
print classify_linear(e,vertcat([x,y]))
x =MX.sym("x")
y =MX.sym("y")
p =MX.sym("p")
e = vertcat([0,x,y,p,x*y,x*p,sin(x),cos(y),sqrt(x+y),p*p*x,x*y*p])
print classify_linear(e,vertcat([x,y]))
print classify_linear(x,x)
print classify_linear(y,x)
print classify_linear(x**2,x)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment