I am new to Mathematica and this gives me headache. I was modeling spherical pendulum using rotationary matrices and it gives me reclim exception at forming lagrangian (L=T-V). Any idea where is the recursion and where is the problem? (I studied documentation but i can see nothing helpful there). File: Download
In[55]:= Clear["Global`*"]
p2 = {0, 0, -L}
Out[56]= {0, 0, -L}
In[57]:= R10 = {{Cos[\[Theta][t]], -Sin[\[Theta][t]],
0}, {Sin[\[Theta][t]], Cos[\[Theta][t]], 0}, {0, 0, 1}}
Out[57]= {{Cos[\[Theta][t]], -Sin[\[Theta][t]], 0}, {Sin[\[Theta][t]],
Cos[\[Theta][t]], 0}, {0, 0, 1}}
In[58]:= Grid[R10]
Out[58]= \!\(
TagBox[GridBox[{
{
RowBox[{"Cos", "[",
RowBox[{"\[Theta]", "[", "t", "]"}], "]"}],
RowBox[{"-",
RowBox[{"Sin", "[",
RowBox[{"\[Theta]", "[", "t", "]"}], "]"}]}], "0"},
{
RowBox[{"Sin", "[",
RowBox[{"\[Theta]", "[", "t", "]"}], "]"}],
RowBox[{"Cos", "[",
RowBox[{"\[Theta]", "[", "t", "]"}], "]"}], "0"},
{"0", "0", "1"}
},
AutoDelete->False,
GridBoxItemSize->{
"Columns" -> {{Automatic}}, "ColumnsIndexed" -> {},
"Rows" -> {{Automatic}}, "RowsIndexed" -> {}, "Items" -> {},
"ItemsIndexed" -> {}}],
"Grid"]\)
In[59]:= R21 = {{Cos[\[Phi][t]], 0, -Sin[\[Phi][t]]}, {0, 1,
0}, {Sin[\[Phi][t]], 0, Cos[\[Phi][t]]}}
Out[59]= {{Cos[\[Phi][t]], 0, -Sin[\[Phi][t]]}, {0, 1,
0}, {Sin[\[Phi][t]], 0, Cos[\[Phi][t]]}}
In[60]:= Grid[R21]
Out[60]= \!\(
TagBox[GridBox[{
{
RowBox[{"Cos", "[",
RowBox[{"\[Phi]", "[", "t", "]"}], "]"}], "0",
RowBox[{"-",
RowBox[{"Sin", "[",
RowBox[{"\[Phi]", "[", "t", "]"}], "]"}]}]},
{"0", "1", "0"},
{
RowBox[{"Sin", "[",
RowBox[{"\[Phi]", "[", "t", "]"}], "]"}], "0",
RowBox[{"Cos", "[",
RowBox[{"\[Phi]", "[", "t", "]"}], "]"}]}
},
AutoDelete->False,
GridBoxItemSize->{
"Columns" -> {{Automatic}}, "ColumnsIndexed" -> {},
"Rows" -> {{Automatic}}, "RowsIndexed" -> {}, "Items" -> {},
"ItemsIndexed" -> {}}],
"Grid"]\)
In[61]:= p0 = R10 . R21 . p2
Out[61]= {L Cos[\[Theta][t]] Sin[\[Phi][t]],
L Sin[\[Theta][t]] Sin[\[Phi][t]], -L Cos[\[Phi][t]]}
In[62]:= v0 = D[p0, t]
Out[62]= {-L Sin[\[Theta][t]] Sin[\[Phi][t]] Derivative[1][\[Theta]][
t] + L Cos[\[Theta][t]] Cos[\[Phi][t]] Derivative[1][\[Phi]][t],
L Cos[\[Theta][t]] Sin[\[Phi][t]] Derivative[1][\[Theta]][t] +
L Cos[\[Phi][t]] Sin[\[Theta][t]] Derivative[1][\[Phi]][t],
L Sin[\[Phi][t]] Derivative[1][\[Phi]][t]}
In[63]:= T = 1/2 m v0 . v0 // Simplify
Out[63]= 1/2 L^2 m (Sin[\[Phi][t]]^2 Derivative[1][\[Theta]][t]^2 +
Derivative[1][\[Phi]][t]^2)
In[64]:= V = m {0, 0, g} . p0
Out[64]= -g L m Cos[\[Phi][t]]
In[65]:= L = T - V
During evaluation of In[65]:= $RecursionLimit::reclim: Recursion depth of 1024 exceeded. >>
Out[65]= Hold[g L m Cos[\[Phi][t]]]
Related
I have two dictionaries:
dict_A = {"a": 25, "b": 2, "c": 4}
dict_B = {"r": 2, "t": 25, "g": 4}
I want to make a new dictionary, dict_C, that merges them on their values but makes dict_B's keys the new values, ie.
dict_C = {"a": "t", "b": "r", "c": "g"}
You can make inverted dictionary from dict_A and dict_B and then do merge:
dict_A = {"a": 25, "b": 2, "c": 4}
dict_B = {"r": 2, "t": 25, "g": 4}
inv_dict_A = {v: k for k, v in dict_A.items()}
inv_dict_B = {v: k for k, v in dict_B.items()}
dict_C = {inv_dict_A[k]: inv_dict_B[k] for k in inv_dict_A if k in inv_dict_B}
print(dict_C)
Prints:
{'a': 't', 'b': 'r', 'c': 'g'}
my problem is summarized in finding a vector X with the best solution to the problem:
L is the profits,
R is the restrictions,
P is a constraint parameters matrix,
max SUM_i (x_i * l_i)
or max(t(L)%*%X)
restriction
SUM_i(x_i*p_ij)<=r_j
or P%*%X <= R.
I find a solution for X, but not the best, which would be
fb = c(.217,0,0,23,2865,0,13,427).
How do I find the best solution?
code:
X<-matrix(rep(1,6),6,1)
P<-matrix(c(
1, 1, 1, 2, 0, 0,
0, 1, 1, 2, 1, 1,
99.4, 37.75, 19.75, 54.40, 74.75, 53,
2.400, 1.540, 0, 0, 0, 0,
2.400, 1.960, 0, 0, 0, 0,
1.800, 3.300, 5.330, 0, 0, 0,
0, 0, 2.070, 0, 8.700, 0,
0, 0, .436, 0, 19.100, 12.363,
0, 3.000, .364, 0, 9.100, 26.737 ),
9,6,1)
L <- matrix(c(83.4, 72.35, 27.3, 72.05, 217.25, 455), 6,1)
R <- matrix(c(60,60,2000,351,448,479,338,424,359),9,1)
farm<- function(par, P,R, L){
trues<- P%*%par<=R
if (min(trues)==1 && min(par)>=0) {
return(-t(L)%*%par)
}
else{
return(0)
}
}
mtds = c("Nelder-Mead", "BFGS", "CG", "L-BFGS-B", "SANN","Brent")
out <- optim(par = X, # initial guess
fn = farm,
P = P,
R = R ,
L = L,
method = mtds[5])
# my result
t(L)%*%out$par
#A matrix: 1 × 1 of type dbl
#7419.596
# the first best
fb<- matrix(c(.217,0,0,23.2865,0,13.427),6,1)
t(L)%*%fb
#A matrix: 1 × 1 of type dbl
#7805.175
I think you can try fmincon from package pracma
library(pracma)
objfun <- function(x) -t(L)%*%x
res <- fmincon(x0 = X,fn = objfun,A = P,b = R,lb = rep(0,length(X)))
and you will see that
> res$par
[1] 4.201711e-16 -1.239088e-15 1.863081e-17 2.310286e+01
[5] 5.566620e-01 1.323762e+01
> -res$value
[,1]
[1,] 7808.615
That looks very much like a model that could be solved by a linear programme.
library("Rglpk")
Rglpk_solve_LP(obj = L,
mat = P,
dir = rep("<=", 9),
rhs = R,
max = TRUE)
I need to convert a dataframe to JSON. There are several nested dataframes as variables in the dataframe to convert to JSON.
But, when converting to JSON, I need the data for Values1 described below to be an object (enclosed in {} only) instead of an array (enclosed in []).
The code below is a reprex to show my current workflow and problem.
library(dplyr)
library(tidyr)
library(jsonlite)
df1 <- data.frame(name = c("a", "b", "c"),
v = c(1, 2, 3),
w = c(10, 20, 30)) %>%
group_by(name) %>%
nest_legacy(.key = "Values1")
df2 <- data.frame(name = c("a", "b", "c"),
x = c(5, 10, 15),
y = c(100, 200, 300),
z = c(1000, 2000, 3000)) %>%
group_by(name) %>%
nest_legacy(.key = "Values2")
df3 <- df1 %>%
left_join(df2)
json <- toJSON(df3, dataframe = "rows", pretty = TRUE)
json
This is what the json from the above looks like:
> json
[
{
"name": "a",
"Values1": [
{
"v": 1,
"w": 10
}
],
"Values2": [
{
"x": 5,
"y": 100,
"z": 1000
}
]
},
{
"name": "b",
"Values1": [
{
"v": 2,
"w": 20
}
],
"Values2": [
{
"x": 10,
"y": 200,
"z": 2000
}
]
},
{
"name": "c",
"Values1": [
{
"v": 3,
"w": 30
}
],
"Values2": [
{
"x": 15,
"y": 300,
"z": 3000
}
]
}
]
But, this is what I need it to look like:
> json
[
{
"name": "a",
"Values1": {
"v": 1,
"w": 10
},
"Values2": [
{
"x": 5,
"y": 100,
"z": 1000
}
]
},
{
"name": "b",
"Values1": {
"v": 2,
"w": 20
},
"Values2": [
{
"x": 10,
"y": 200,
"z": 2000
}
]
},
{
"name": "c",
"Values1": {
"v": 3,
"w": 30
},
"Values2": [
{
"x": 15,
"y": 300,
"z": 3000
}
]
}
]
Any ideas how to convert Values1 from arrays to objects? They cannot be in arrays as the API does not accept the [.
I have looked at using unbox() from jsonlite but this only works on singletons. I have also tried to construct my final dataframe in various ways.
Any tips/ideas greatly appreciated!
This should return what you desire:
...
df3 <- left_join(df1, df2, by = "name")
json <- mutate(df3, Values1 = purrr::map(Values1, as.list)) %>%
jsonlite::toJSON(auto_unbox = TRUE, pretty = TRUE)
Can you confirm?
I am trying to reproduce some of the examples given by the ROI creators.
For example in http://statmath.wu.ac.at/courses/optimization/Presentations/ROI-2011.pdf (slides 15-17) there is the example:
library("ROI")
#ROI: R Optimization Infrastructure
#Installed solver plugins: cplex, lpsolve, glpk, quadprog, symphony, nlminb.
#Default solver: glpk.
(constr1 <- L_constraint(c(1, 2), "<", 4))
#An object containing 1 linear constraints.
(constr2 <- L_constraint(matrix(c(1:4), ncol = 2), c("<", "<"), c(4, 5)))
#An object containing 2 linear constraints.
rbind(constr1, constr2)
#An object containing 3 linear constraints.
(constr3 <- Q_constraint(matrix(rep(2, 4), ncol = 2), c(1, 2), "<", 5))
#An object containing 1 constraints.
#Some constraints are of type quadratic.
foo <- function(x) {sum(x^3) - seq_along(x) %*% x}
F_constraint(foo, "<", 5)
lp <- LP(objective = c(2, 4, 3), L_constraint(L = matrix(c(3, 2, 1, 4, 1, 3, 2, 2, 2), nrow = 3), dir = c("<=", "<=", "<="), rhs = c(60, 40, 80)), maximum = TRUE)
qp <- QP(Q_objective(Q = diag(1, 3), L = c(0, -5, 0)), L_constraint(L = matrix(c(-4, -3, 0, 2, 1, 0, 0, -2, 1), ncol = 3, byrow = TRUE), dir = rep(">=", 3), rhs = c(-8, 2, 0)))
When I run it I get the errors
Error in LP(objective = c(2, 4, 3), L_constraint(L = matrix(c(3, 2, 1, :
could not find function "LP"
and
Error in QP(Q_objective(Q = diag(1, 3), L = c(0, -5, 0)), L_constraint(L = matrix(c(-4, :
could not find function "QP"
In fact the functions are not in ROI's namespace. e.g.
ROI::LP
Error: 'LP' is not an exported object from 'namespace:ROI'
The same syntax appears in other examples I found on the web but the functions LP and QP are never defined.
I am using ROI 0.3.0
Can someone tell me what is going wrong?
The commands LP and QP were both changed to OP.
library("ROI")
## ROI: R Optimization Infrastructure
## Registered solver plugins: nlminb, alabama, cbc, cccp, clp, deoptim, ecos, glpk, ipop, lpsolve, msbinlp, neos, nloptr, ucminf, spg, cgm, vmm, bobyqa, newuoa, uobyqa, hjk, nmk, lbfgs, optimx, qpoases, quadprog, scs, symphony.
## Default solver: auto.
(constr1 <- L_constraint(c(1, 2), "<", 4))
## An object containing 1 linear constraint.
(constr2 <- L_constraint(matrix(c(1:4), ncol = 2), c("<", "<"), c(4, 5)))
## An object containing 2 linear constraints.
rbind(constr1, constr2)
## An object containing 3 linear constraints.
(constr3 <- Q_constraint(matrix(rep(2, 4), ncol = 2), c(1, 2), "<", 5))
## An object containing 0 linear constraints
## 1 quadratic constraint.
foo <- function(x) {sum(x^3) - seq_along(x) %*% x}
F_constraint(foo, "<", 5)
## An object containing 1 nonlinear constraint.
lp <- OP(objective = c(2, 4, 3),
L_constraint(L = matrix(c(3, 2, 1, 4, 1, 3, 2, 2, 2), nrow = 3),
dir = c("<=", "<=", "<="),
rhs = c(60, 40, 80)), maximum = TRUE)
qp <- OP(Q_objective(Q = diag(1, 3), L = c(0, -5, 0)),
L_constraint(L = matrix(c(-4, -3, 0, 2, 1, 0, 0, -2, 1), ncol = 3, byrow = TRUE),
dir = rep(">=", 3), rhs = c(-8, 2, 0)))
The slides you refer to are outdated. The new documentation is on http://roi.r-forge.r-project.org !
How can I write a program which can solve a system of linear equations with Givens rotation in mathematica .
Code attempt:
ar = CoefficientArrays[
{x + y + z == 2, 3 x - 2 y + z == 4, x - y + 5 z == 6},
{x, y, z}];
an = Normal[ar];
b = an[[2]];
n = Length[b];
Do[Do[a[i, j] = b[[i]][[j]], {j, 1, n}], {i, 1, n}];
r1 = (a[1, 1]^2 + a[1, 2]^2)^(1/2);
c = a[1, 1]/r1;
s = a[1, 2]/r1;
Are you looking for something like this?
Following your code.
{r1, c, s}
{Sqrt[2], 1/Sqrt[2], 1/Sqrt[2]}
{a, b} = LinearSolve[{{c, -s}, {s, c}}, {r1, 0}]
{1, -1}
algorithm from wikipedia
GivensRotation[a_, b_] := Which[
b == 0, c = Sign[a]; s = 0; r = Abs[a],
a == 0, c = 0; s = -Sign[b]; r = Abs[b],
Abs[a] > Abs[b],
t = b/a; u = Sign[a]*Abs[Sqrt[1 + t*t]];
c = 1/u; s = -c*t; r = a*u,
True,
t = a/b;
u = Sign[b]*Abs[Sqrt[1 + t*t]];
s = -1/u; c = -s*t; r = b*u
]
GivensRotation[a, b];
{r, c, s}
{Sqrt[2], 1/Sqrt[2], 1/Sqrt[2]}
Edit
I'm not familiar with solving with Givens rotation. Here are other methods for solving the simultaneous equations, just for interest.
Solve[{
x + y + z == 2,
3 x - 2 y + z == 4,
x - y + 5 z == 6},
{x, y, z}]
{{x -> 1, y -> 0, z -> 1}}
also
LinearSolve[{{1, 1, 1}, {3, -2, 1}, {1, -1, 5}}, {2, 4, 6}]
{1, 0, 1}
or
Inverse[{{1, 1, 1}, {3, -2, 1}, {1, -1, 5}}].{2, 4, 6}
{1, 0, 1}