R: Question about Optimizing - Invalid Function Value in Optimize - r

We have not been able to pinpoint what is causing the error of Invalid Function Value in Optimize in our Optimizing code. If you could offer any insight, it would be appreciated.
H_fun <- function(c)
{
val = -current_c_weight*c - X_counts%*%log(
exp(rep(c,length(current_Theta))*current_Theta) -
current_elongation_rates )
print('#########iteration display#############')
print('c')
print(c)
print('val')
print(val)
print('current_c_weight')
print(current_c_weight)
print('current_Theta')
print(current_Theta)
print('current_elongation_rates')
print(current_elongation_rates)
}
#...snip...
# minimize -H(c) without the non-negativity constraint
#tmp = optim(c(0,1),H_fun,NULL, method = "BFGS", hessian = TRUE);
tmp = optimize(H_fun,interval = c(0,1));
Here is a link to the code:
http://www.text-upload.com/read.php?id=102950&c=8605046

Are you sure H_fun is returning a one-dimensional value?
Look at fcn1() in the R optimize() source code:
static double fcn1(double x, struct callinfo *info)
{
SEXP s;
REAL(CADR(info->R_fcall))[0] = x;
s = eval(info->R_fcall, info->R_env);
switch(TYPEOF(s)) {
case INTSXP:
if (length(s) != 1) goto badvalue;
if (INTEGER(s)[0] == NA_INTEGER) {
warning(_("NA replaced by maximum positive value"));
return DBL_MAX;
}
else return INTEGER(s)[0];
break;
case REALSXP:
if (length(s) != 1) goto badvalue;
if (!R_FINITE(REAL(s)[0])) {
warning(_("NA/Inf replaced by maximum positive value"));
return DBL_MAX;
}
else return REAL(s)[0];
break;
default:
goto badvalue;
}
badvalue:
error(_("invalid function value in 'optimize'"));
return 0;/* for -Wall */
}
goto badvalue occurs if length is not 1. Also, the package summary states that optimize() works on a one-dimensional unconstrained function.

Related

Need help recursion explanation Leetcode

How does this code work? (leetcode 95 question) I don't understand how the 2 recursions work inside the for loop. Does the 2nd inner for loop end when the recursive function returns NULL? Or would it continue executing the 3rd inner for loop?
class Solution {
public:
vector<TreeNode*> generateTrees(int n) {
if(n == 0) {
return {};
}
vector<TreeNode*> ans = generateT(1,n);
return ans;
}
vector<TreeNode*> generateT(int l, int r) {
if(l > r) return {nullptr};
vector<TreeNode*> ans;
for(int i=l; i <= r; ++i) {
for(TreeNode*left: generateT(l, i-1)) {
for(TreeNode* right:generateT(i+1, r)) {
ans.push_back(new TreeNode(i));
ans.back()->left = left;
ans.back()->right = right;
}
}
}
return ans;
}
};
Problem statement:
Given an integer n, return all the structurally unique BST's (binary search trees), which has exactly n nodes of unique values from 1 to n. Return the answer in any order.
Does the 2nd inner for loop end when the recursive function returns NULL?
No. The recursive function is not returing NULL, it is returning vector of nullptr.
Or would it continue executing the 3rd inner for loop?
Of course, it will.
How does this code work? I don't understand how the 2 recursions work inside the loop.
I suppose the following snippet is the cause of confusion, so commented the case when nullptr provided by outer loop.
vector<TreeNode*> generateT(int l, int r) {
if(l > r) return { nullptr };
vector<TreeNode*> ans;
for ( int i = l; i <= r; i++ ) {
// if l = 0, i = 0
for ( TreeNode* left :generateT(l, i-1) ) // if l = 0, i = -1, returns { nullptr } (vector of nullptr)
for (TreeNode* right :generateT(i+1, r)) { // now this snippet will execute
auto node = new TreeNode(i);
ans.push_back(node);
node->left = left; // the nullptr we have from the outer loop, will provide null value for this
node->right = right;
}
}
return ans;
}
Visually, for a combination of node where,
a
\
b
/ \
null c
/
null
the above pattern occurs the provided { nullptr } from outer loop will come in handy setting left node.

Error in .Call(tXPMCpp, x) : first argument must be a string (of length 1) or native symbol reference

I've following R Code
tXPM <- function(x) {
.Call(tXPMCpp, x)
}
and following RCPP code
SEXP tXPMCpp (SEXP xSEXP){
arma::mat GeneExp = Rcpp::as<arma::mat>(xSEXP);
arma::rowvec ColumnSums = sum(GeneExp, 0);
int_fast32_t i=0, n=0;
arma::mat::iterator it_end = GeneExp.end();
//One pass linear regression with one pass variance, skewness
for (arma::mat::iterator it = GeneExp.begin(); it != it_end; ++it) {
//std::cout << (*it) << std::endl;
*it = *it/ColumnSums.at(i);
n++;
if (n == int(GeneExp.n_rows)) {
n=0;
i++;
}
}
return Rcpp::wrap(trans(GeneExp));}
When i call this function by passing it datamatrix it shows following error:
Error in .Call(tXPMCpp, x) : first argument must be a string (of length 1) or native symbol reference
How can i call this function?

Constructing a Sparse Tropical Limit Function in Chapel

Given matrices A and B the tropical product is defined to be the usual matrix product with multiplication traded out for addition and addition traded out for minimum. That is, it returns a new matrix C such that,
C_ij = minimum(A_ij, B_ij, A_i1 + B_1j, A_i2 + B_12,..., A_im + B_mj)
Given the underlying adjacency matrix A_g of a graph g, the nth "power" with respect to the tropical product represents the connections between nodes reachable in at most n steps. That is, C_ij = (A**n)_ij has value m if nodes i and j are separated by m<=n edges.
In general, given some graph with N nodes. The diameter of the graph can only be at most N; and, given a graph with diameter k, A**n = A**k for all n>k and the matrix D_ij = A**k is called the "distance matrix" entries representing the distances between all nodes in the graph.
I have written a tropical product function in chapel and I want to write a function that takes an adjacency matrix and returns the resulting distance matrix. I have tried the following approaches to no avail. Guidance in getting past these errors would be greatly appreciated!
proc tropicLimit(A:[] real,B:[] real) {
var R = tropic(A,B);
if A == R {
return A;
} else {
tropicLimit(R,B);
}
}
which threw a domain mismatch error so I made the following edit:
proc tropicLimit(A:[] real,B:[] real) {
var R = tropic(A,B);
if A.domain == R.domain {
if && reduce (A == R) {
return R;
} else {
tropicLimit(R,B);
}
} else {
tropicLimit(R,B);
}
}
which throws
src/MatrixOps.chpl:602: error: control reaches end of function that returns a value
proc tropicLimit(A:[] real,B:[] real) {
var R = tropic(A,B);
if A.domain == R.domain {
if && reduce (A == R) { // Line 605 is this one
} else {
tropicLimit(R,B);
}
} else {
tropicLimit(R,B);
}
return R;
}
Brings me back to this error
src/MatrixOps.chpl:605: error: halt reached - Sparse arrays can't be zippered with anything other than their domains and sibling arrays (CS layout)
I also tried using a for loop with a break condition but that didn't work either
proc tropicLimit(B:[] real) {
var R = tropic(B,B);
for n in B.domain.dim(2) {
var S = tropic(R,B);
if S.domain != R.domain {
R = S; // Intended to just reassign the handle "R" to the contents of "S" i.o.w. destructive update of R
} else {
break;
}
}
return R;
}
Any suggestions?
src/MatrixOps.chpl:605: error: halt reached - Sparse arrays can't be zippered with anything other than their domains and sibling arrays (CS layout)
I believe you are encountering a limitation of zippering sparse arrays in the current implementation, documented in #6577.
Removing some unknowns from the equation, I believe this distilled code snippet demonstrates the issue you are encountering:
use LayoutCS;
var dom = {1..10, 1..10};
var Adom: sparse subdomain(dom) dmapped CS();
var Bdom: sparse subdomain(dom) dmapped CS();
var A: [Adom] real;
var B: [Bdom] real;
Adom += (1,1);
Bdom += (1,1);
A[1,1] = 1.0;
B[1,1] = 2.0;
writeln(A.domain == B.domain); // true
var willThisWork = && reduce (A == B);
// dang.chpl:19: error: halt reached - Sparse arrays can't be zippered with
// anything other than their domains and sibling arrays (CS layout)
As a work-around, I would suggest looping over the sparse indices after confirming the domains are equal and performing a && reduce. This is something you could wrap in a helper function, e.g.
proc main() {
var dom = {1..10, 1..10};
var Adom: sparse subdomain(dom) dmapped CS();
var Bdom: sparse subdomain(dom) dmapped CS();
var A: [Adom] real;
var B: [Bdom] real;
Adom += (1,1);
Bdom += (1,1);
A[1,1] = 1.0;
B[1,1] = 2.0;
if A.domain == B.domain {
writeln(equal(A, B));
}
}
/* Some day, this should be A.equals(B) ! */
proc equal(A: [], B: []) {
// You could also return 'false' if domains do not match
assert(A.domain == B.domain);
var s = true;
forall (i,j) in A.domain with (&& reduce s) {
s &&= (A[i,j] == B[i,j]);
}
return s;
}
src/MatrixOps.chpl:602: error: control reaches end of function that returns a value
This error is a result of not returning something in every condition. I believe you intended to do:
proc tropicLimit(A:[] real,B:[] real) {
var R = tropic(A,B);
if A.domain == R.domain {
if && reduce (A == R) {
return R;
} else {
return tropicLimit(R,B);
}
} else {
return tropicLimit(R,B);
}
}

Checking if a returned number is an integer in GP/Pari?

This is my first time using GP/Pari and I am having trouble completing this question.
I am asked to print if the return of the function 'wq()' is an integer. Is there a function that can determine if the number passed in is an integer? If not how would I go about checking? I find the syntax somewhat difficult and can't find much information online about it.
I have included what I have so far, any help is appreciated.
wq(x) =
{
[(x-1)! + 1]/x
}
test(r,s) =
{
for (i=r, s, if(isinteger(wq(i)), print("integer"), print("not interger")));
}
If I understand correctly you want to check if (x-1)! + 1 is a multiple of x. You can do that with the modulo operation:
test(r,s) =
{
for (i=r, s, if(Mod((i - 1)! + 1, i) == 0,
print("integer"),
print("not integer")));
}
You can use:
wq(x) =
{
((x-1)! + 1)/x
}
test(r,s) =
{
for (i=r, s, print(if(type(wq(i))=="t_INT", "integer", "not integer")))
}
I changed [] into () since [] gives a row vector (type t_VEC) which is not useful here.
Here is another way to write it:
wq(x) =
{
Mod((x-1)! + 1, x)
}
test(r,s) =
{
for (i=r, s, wq(i) && print1("not "); print("integer"))
}
The function print1 prints and "stays" on the same line. The 'and' operator && "short-circuits". The semicolon ; binds several expressions into one "sequence".

Name for this function invocation style

Functions can be written in a way to permit the "spreading" of invocations
console.assert(add(1,2,3,4) === 10, '1+2+3+4 should be 10');
console.assert(add(1,2)(3)(4)() === 10, '1+2+3+4 should be 10'); // "spread" invocation
What is the name for this pattern?
It is called currying.
Imagine that add is a function that receives 4 arguments:
function add(a,b,c,d);
If you pass exactly 4 arguments, it returns the sum of all of them.
If you pass 3, (e.g. a=1, b=2, c=3) it will return a function that receives one parameter and adds that to 1+2+3 (the values of a,b,c).
If you pass 2, it will return a function that receives two parameters and returns the sum of those with the intial 2 parameters that you passed.
An example, if you, like me, have from a imperative language background.
function add(a, b, c, d){
if(arguments.length < 1){
return add
} else if(arguments.length < 2){
return function(b, c, d) { return add(a,b,c,d) }
} else if(arguments.length < 3){
return function(c, d) { return add(a,b,c,d) }
} else if(arguments.length < 4){
return function(d) { return add(a,b,c,d) }
} else {
return a+b+c+d;
}
}

Resources