Simplifying calculation of arrays with Ramda - ramda.js

I would like to calculate the three arrays like this.
const Data = {
x : [2,4,6],
y : [10,10,10],
z : [5,5,5]
}
const XtimesYplusZ = zipWith (add, (zipWith (multiply, Data.x, Data.y)), Data.z)
console.log(XtimesYplusZ);//[25,45,65]
This code works ok, but not very good in terms of readability.
So, now I created calculation patterns that could be applied later on:
const calc1 = ({x, y, z}) => x * y + z
console.log(calc1(Data)); //ERROR
This is not working. I have many different patterns such as ({x, y, z}) => x / y - z, ({x, y, z}) => (x + y) * z and so on. What is the standard calculation method for arrays something like this?
REPL

In this example:
const calc1 = ({x, y, z}) => x * y + z
console.log(calc1(Data)); //ERROR
You are trying to add and multiply arrays, and not the arrays' items.
Using R.zipWith won't work as well, since it requires actual arrays, and is limited to zipping 2 arrays at a time.
An easier solution would be to get the sub-arrays using R.props, transpose them ([[2, 10, 5], [4, 10, 5]]...), and then map and combine the values using your calc function (I've replace the object destructuring with array destructuring):
const { pipe, props, transpose, map } = R
const calc = ([x, y, z]) => x * y + z
const fn = pipe(props(['x', 'y', 'z']), transpose, map(calc))
const Data = {
x : [2,4,6],
y : [10,10,10],
z : [5,5,5]
}
const XtimesYplusZ = fn(Data)
console.log(XtimesYplusZ) // [25,45,65]
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.27.1/ramda.min.js" integrity="sha512-rZHvUXcc1zWKsxm7rJ8lVQuIr1oOmm7cShlvpV0gWf0RvbcJN6x96al/Rp2L2BI4a4ZkT2/YfVe/8YvB2UHzQw==" crossorigin="anonymous"></script>
This example show Scott's suggestion of extracting out the combination of R.transpose, and R.map to create a zipAllWith function:
const { curry, map, apply, transpose, pipe, props } = R
const zipAllWith = curry((fn, xss) => map(apply(fn), transpose(xss)));
const fn = pipe(props(['x', 'y', 'z']), zipAllWith((x, y, z) => x * y + z))
const Data = {
x : [2,4,6],
y : [10,10,10],
z : [5,5,5]
}
const XtimesYplusZ = fn(Data)
console.log(XtimesYplusZ) // [25,45,65]
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.27.1/ramda.min.js" integrity="sha512-rZHvUXcc1zWKsxm7rJ8lVQuIr1oOmm7cShlvpV0gWf0RvbcJN6x96al/Rp2L2BI4a4ZkT2/YfVe/8YvB2UHzQw==" crossorigin="anonymous"></script>

Related

Quantile regressing using RcppEnsmallen diverge

I am trying RcppEnsmallen to estimate quantile regression models. I noticed that the results seemed not convergent. Every time it pops up different results. I set up its first order condition in my code. I guess the divergence may be owing to the fact that the objective function is not differentiable at zero. I am not sure about that.
Here the code
#include <RcppEnsmallen.h>
// [[Rcpp::depends(RcppEnsmallen)]]
class QuantileRegressionFunction
{
public:
// Construct the QuantileRegressFunction with the given data.
QuantileRegressionFunction(const arma::mat& X,
const arma::colvec& y,
const double tau
) : X(X),y(y),tau(tau){}
// Define the objective function.
double EvaluateWithGradient(const arma::mat& beta, arma::mat& gradient ){
const arma::mat fit = y - X * beta;
const arma::vec eval =0.5* arma::abs(fit) + (tau - 0.5 )*fit;
const arma::vec v= tau - arma::ones<arma::vec>(y.n_rows) % ( fit < 0 ) ;
gradient = - (X.t() * v)*(1/X.n_rows) ;
return arma::accu( (1/y.n_rows) *eval ) ;
}
private:
const arma::mat& X;
const arma::vec& y;
const double tau;
};
// [[Rcpp::export]]
arma::mat qr_reg(const arma::mat& X, const arma::vec& y,const double& tau){
QuantileRegressionFunction qrf(X,y,tau);
ens::L_BFGS lbfgs;
lbfgs.MaxIterations()= 1000 ;
//lbfgs.MaxLineSearchTrials() = 10000;
//lbfgs.ArmijoConstant() = 1e-18;
arma::mat beta(X.n_cols, 1 , arma::fill::randn);
lbfgs.Optimize(qrf,beta);
return beta;
}
Here is a simple simulation exercise:
n <- 1000
beta <- c(-2, 1.5, 3, 8.2, 6.6)
p <- length(beta)
X <- cbind(1, matrix(rnorm(n), ncol = p - 1))
y <- X %*% beta + rnorm(n / (p - 1))
qr_reg(X,y,0.1)
Every time qr_reg(X,y,.1) report divergent estimates.

How to use a predefined function with R.zipWith

This is the initial data set.
const Main = {
  ratio : [ 0.5, 1, 2 ],
focusPoint : [ 0.1, 0.2, 0.3 ],
}
I want this object calculated with a predefined function.
const width =  window.innerWidth
const height = window.innerHeight
const ratioViewport = width / height
const resultY = ( x, y ) => 0.5 * ( x / ratioViewport ) - y
Here is the final part with R.zipWith to evaluate the function.
const getPositionMain = applySpec ( {
ratio : R.prop ('ratio'),
resultY : R.zipWith ( resultY, R.prop ('ratio') , R.prop ('focusPoint') ),
} )
const positionMain = getPositionMain ( Main )
console.log( 'positionMain : ', positionMain )
// Desired output (positionMain) : [ 0.5 * (1 / ratioViewport) - 0.1, 0.5 * (2 / ratioViewport) - 0.2, 0.5 * (3 / ratioViewport) - 0.3 ]
But, I am not getting it right.
What am I doing wrong at here?
REPL
It's not quite clear to me what you want. Are you looking for something like this?
const getPositionMain = (w, ratioViewport = w.innerWidth / w.innerHeight) => main =>
zipWith ((x, y) => 0.5 * (x / ratioViewport) - y) (main .ratio, main .focusPoint)
const _window = {innerWidth: 600, innerHeight: 400}
const Main = {
ratio : [ 0.5, 1, 2 ],
focusPoint : [ 0.1, 0.2, 0.3 ],
}
console .log (getPositionMain (_window) (Main))
<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.27.1/ramda.js"></script>
<script> const {zipWith} = R </script>
Or something more like this?:
const getPositionMain = (w, ratioViewport = w.innerWidth / w.innerHeight) => (main) => ({
ratio: main .ratio,
resultY: zipWith ((x, y) => 0.5 * (x / ratioViewport) - y) (main .ratio, main .focusPoint)
})
const _window = {innerWidth: 600, innerHeight: 400}
const Main = {
ratio : [ 0.5, 1, 2 ],
focusPoint : [ 0.1, 0.2, 0.3 ],
}
console .log (getPositionMain (_window) (Main))
<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.27.1/ramda.js"></script>
<script> const {zipWith} = R </script>
In either case, the code is much the same, just with a different format for the output results.
The working version I can get to closest to your attempt would look like this:
const getPositionMain = (w, ratioViewport = w.innerWidth / w.innerHeight) => applySpec ({
ratio : prop ('ratio'),
resultY : lift (zipWith ((x, y) => 0.5 * (x / ratioViewport) - y))
(prop ('ratio') , prop ('focusPoint'))
})
Note that zipWith takes a function and two lists. You were passing it the initial function and two functions that would resolve to lists when called properly. Functions that will resolve to specific types can be thought of as containers of those types. lift takes a function that operates on values and lifts it up to become a function that operates on containers of those values. So lift (resultY) (f, g) is approximately main => resultY (f (main), g (main)), and we can then use it in applySpec.
In every version here, I avoid the global variables you have of ratioViewport, calculating it from a Window object as a parameter. I find this much cleaner, but YMMV.
But we could skip that variable altogether by performing the inexpensive viewport calculation inside the main function, like this:
const getPositionMain = ({innerWidth, innerHeight}) => ({ratio, focusPoint}) =>
zipWith ((x, y) => 0.5 * (x / innerWidth * innerHeight) - y, ratio, focusPoint)
or like this:
const getPositionMain = ({innerWidth, innerHeight}) => ({ratio, focusPoint}) => ({
ratio,
resultY: zipWith ((x, y) => 0.5 * (x / innerWidth * innerHeight) - y, ratio, focusPoint)
})
Those are the versions I prefer.

Chapel iterators with conditionals

I am trying to write an iterator with a conditional in Chapel. This works
var x = [1,4,5,2,6,3];
iter dx(x) {
for y in x do yield 2*y;
}
for y in dx(x) {
writeln("y -> ", y);
}
returning
y -> 2
y -> 8
y -> 10
y -> 4
y -> 12
y -> 6
Suppose I want to only return the ones that are greater than 3. None of these will compile. What is the proper syntax?
var x = [1,4,5,2,6,3];
iter dx(x) {
//for y in x do {if x > 3} yield 2*y; // Barf
//for y in x do {if x > 3 yield 2*y }; // Barf
//for y in x do if x > 3 yield 2*y ; // Barf
}
for y in dx(x) {
writeln("y -> ", y);
}
The error is that you are checking against the iterator argument x instead of the current element y in the conditional. Try:
iter dx(x) {
for y in x {
if y > 3 {
yield 2*y;
}
}
}
or in the more concise form:
iter dx(x) {
for y in x do if y > 3 then yield 2*y;
}
Note that when the body of an if statement is a single statement, you may use a then keyword to introduce the body rather than enclosing it in braces { }. Unlike C, the then keyword is required (due to syntactic ambiguities that would occur otherwise).

Collision Angle Detection

I have some questions regarding collision angles. I am trying to code physics for a game and I do not want to use any third party library, actually I want to code each and every thing by myself. I know how to detect collisions between two spheres but I can't figure out, how to find the angle of collision/repulsion between the two spherical objects. I've tried reversing the direction of the objects, but no luck. It would be very nice if you link me to an interesting .pdf file teaching physics programming.
There's a lot of ways to deal with collision
Impulsion
To model a impulsion, you can directly act on the speed of each objects, using the law of reflection, you can "reflect" each speed using the "normal of the impact"
so : v1 = v1 - 2 x ( v1 . n2 ) x n2
and v2 = v2 - 2 x ( v2 . n1 ) x n1
v1 and v2 speeds of sphere s1 and s2
n1 and n2 normal at collision point
Penalty
Here, we have 2 object interpenetrating, and we model the fact that they tend to not interpenetrate anymore, so you create a force that is proportional to the penetration using a spring force
I didn't speak about all the ways, but this are the two simplest I know
the angle between two objects in the 2D or 3D coordinate space can be found by
A * B = |A||B|cosɵ
Both A and B are vectors and ɵ is the angle between both vectors.
the below class can be used to solve basic Vector calculations in games
class 3Dvector
{
private:
float x, y, z;
public:
// purpose: Our constructor
// input: ex- our vector's i component
// why- our vector's j component
// zee- our vector's k component
// output: no explicit output
3Dvector(float ex = 0, float why = 0, float zee = 0)
{
x = ex; y = why; z = zee;
}
// purpose: Our destructor
// input: none
// output: none
~3Dvector() { }
// purpose: calculate the magnitude of our invoking vector
// input: no explicit input
// output: the magnitude of our invoking object
float getMagnitude()
{
return sqrtf(x * x + y * y + z * z);
}
// purpose: multiply our vector by a scalar value
// input: num - the scalar value being multiplied
// output: our newly created vector
3Dvector operator*(float num) const
{
return 3Dvector(x * num, y * num, z * num);
}
// purpose: multiply our vector by a scalar value
// input: num - the scalar value being multiplied
// vec - the vector we are multiplying to
// output: our newly created vector
friend 3Dvector operator*(float num, const 3Dvector &vec)
{
return 3Dvector(vec.x * num, vec.y * num, vec.z * num);
}
// purpose: Adding two vectors
// input: vec - the vector being added to our invoking object
// output: our newly created sum of the two vectors
3Dvector operator+(const 3Dvector &vec) const
{
return 3Dvector(x + vec.x, y + vec.y, z + vec.z);
}
// purpose: Subtracting two vectors
// input: vec - the vector being subtracted from our invoking object
// output: our newly created difference of the two vectors
3Dvector operator-(const 3Dvector &vec) const
{
return 3Dvector(x - vec.x, y - vec.y, z - vec.z);
}
// purpose: Normalize our invoking vector *this changes our vector*
// input: no explicit input
// output: none
void normalize3Dvector(void)
{
float mag = sqrtf(x * x + y * y + z * z);
x /= mag; y /= mag; z /= mag
}
// purpose: Dot Product two vectors
// input: vec - the vector being dotted with our invoking object
// output: the dot product of the two vectors
float dot3Dvector(const 3Dvector &vec) const
{
return x * vec.x + y * vec.y + z * vec.z;
}
// purpose: Cross product two vectors
// input: vec- the vector being crossed with our invoking object
// output: our newly created resultant vector
3Dvector cross3Dvector(const 3Dvector &vec) const
{
return 3Dvector( y * vec.z – z * vec.y,
z * vec.x – x * vec.z,
x * vec.y – y * vec.x);
}
};
I shouldn't be answering my own question but I found what I needed, I guess. It may help other people too. I was just fingering the wikipedia's physics section and I got this.
This link solves my question
The angle in a cartesian system can be found this way:
arctan((Ya-Yb)/(Xa-Xb))
Because this is a retangle triangle where you know the catets (diferences of heights and widths). This will calc the tangent. So the arctan will calc the angle thats have this tangent.
I hope I was helpful.

How to create an own struct and constants for this struct?

I want to create a struct which is like a CGPoint, but with 3 coordinates instead of 2.
I create it in the following way:
typedef struct {CGFloat x;CGFloat y;CGFloat z;} CG3Vector;
CG_INLINE CG3Vector CG3VectorMake(CGFloat x, CGFloat y, CGFloat z)
{
CG3Vector p; p.x = x; p.y = y; p.z = z; return p;
}
It works fine. But I now want to improve this struct so that it has the constants like for CGPoint: CGPointZero
Also what is the way to introduce the limits for particular components of the struct, like it is for the CGSize, where components are never lower than 0?
Thanks.
You could create constants like this:
const CG3Vector CG3VectorZero = { 0, 0, 0 };
If you want limits, I suppose you can do some checking like this:
CG_INLINE CG3Vector CG3VectorMake(CGFloat x, CGFloat y, CGFloat z)
{
// normalize the values
x = fmod(x, 360);
y = fmod(y, 360);
z = fmod(z, 360);
x = (x < 0) ? 360 + x : x;
y = (y < 0) ? 360 + y : y;
z = (z < 0) ? 360 + z : z;
return (CG3Vector) { x, y, z };
}