Export class from files other than index.ts - assemblyscript

I made a file called assembly/Vec3.ts with this content:
/**
* #constructor
* #name pc.Vec3
* #classdesc A 3-dimensional vector.
* #description Creates a new Vec3 object.
* #param {Number} [x] The x value. If x is an array of length 3, the array will be used to populate all components.
* #param {Number} [y] The y value.
* #param {Number} [z] The z value.
* #example
* var v = new pc.Vec3(1, 2, 3);
*/
export class Vec3 {
x: number;
y: number;
z: number;
// AS is more strict than TS... need to replace all occuranves of this in PlayCanvasTS at some point
//constructor(x?: any, y?: number, z?: number)
constructor(x: number, y: number, z: number)
{
//if (x && x.length === 3) {
// this.x = x[0];
// this.y = x[1];
// this.z = x[2];
//} else {
// this.x = x || 0;
// this.y = y || 0;
// this.z = z || 0;
//}
this.x = x;
this.y = y;
this.z = z;
}
/**
* #function
* #name pc.Vec3#add
* #description Adds a 3-dimensional vector to another in place.
* #param {pc.Vec3} rhs The vector to add to the specified vector.
* #returns {pc.Vec3} Self for chaining.
* #example
* var a = new pc.Vec3(10, 10, 10);
* var b = new pc.Vec3(20, 20, 20);
*
* a.add(b);
*
* // Should output [30, 30, 30]
* console.log("The result of the addition is: " + a.toString());
*/
add(rhs: Vec3): Vec3 {
this.x += rhs.x;
this.y += rhs.y;
this.z += rhs.z;
return this;
}
/**
* #function
* #name pc.Vec3#add2
* #description Adds two 3-dimensional vectors together and returns the result.
* #param {pc.Vec3} lhs The first vector operand for the addition.
* #param {pc.Vec3} rhs The second vector operand for the addition.
* #returns {pc.Vec3} Self for chaining.
* #example
* var a = new pc.Vec3(10, 10, 10);
* var b = new pc.Vec3(20, 20, 20);
* var r = new pc.Vec3();
*
* r.add2(a, b);
* // Should output [30, 30, 30]
*
* console.log("The result of the addition is: " + r.toString());
*/
add2(lhs: Vec3, rhs: Vec3): Vec3 {
this.x = lhs.x + rhs.x;
this.y = lhs.y + rhs.y;
this.z = lhs.z + rhs.z;
return this;
}
}
Then building it via npm run asbuild
But the file is just ignored and not included inside the untouched.wasm.
Is it possible to export classes from all files?

Currently AssemblyScript support global export only from entry file (index.ts). So you should reexport all your entities to this file. But this may improve in future. See this discussion: https://github.com/AssemblyScript/assemblyscript/issues/464

Currently I solved it by adding the Vec3.ts to asc in doit.sh:
# print the commands via -x/+y
set -x
npx asc assembly/index.ts assembly/Vec3.ts -b build/untouched.wasm -t build/untouched.wat --sourceMap --validate --debug
npx asc assembly/index.ts assembly/Vec3.ts -b build/optimized.wasm -t build/optimized.wat --sourceMap --validate --optimize
set +x

Related

Pass arrays from JS by reference for WASM to edit?

What's the best way to pass and return arrays of floats in AssemblyScript?
Can I pass an array form JS (by reference) for WASM to edit?
export function nBodyForces(data: f64[], result: f64[]): void {}
Below is what I have now. Ignore the implementation details, and it's returning 2000, then incrementing it to 8000ish.
What's the best way to return an array of new values?
export function nBodyForces(data: f64[]): f64[] {
// Each body has x,y,z,m passed in.
if (data.length % bodySize !== 0) return new Array<f64>(10);
const numBodies: i32 = data.length / bodySize;
// return a 3-force x,y,z vector for each body
let ret: f64[] = new Array<f64>(numBodies * forceSize);
/**
* Calculate the 3-vector each unique pair of bodies applies to each other.
*
* 0 1 2 3 4 5
* 0 x x x x x
* 1 x x x x
* 2 x x x
* 3 x x
* 4 x
* 5
*
* Sum those forces together into an array of 3-vector x,y,z forces
*/
// For all bodies:
for (let i: i32 = 0; i < numBodies; i++) {
// Given body i: pair with every body[j] where j > i
for (let j: i32 = i + 1; i < numBodies; j++) {
// Calculate the force the bodies apply to one another
const bI: i32 = i * 4
const bJ: i32 = j * 4
let f: f64[] = twoBodyForces(
// b0
data[bI], data[bI+1], data[bI+2], data[bI+3], // x,y,z,m
// b1
data[bJ], data[bJ+1], data[bJ+2], data[bJ+3], // x,y,z,m
);
// Add this pair's force on one another to their total forces applied x,y,z
// body0
ret[bI] = ret[bI] + f[0];
ret[bI+1] = ret[bI+1] + f[1];
ret[bI+2] = ret[bI+2] + f[2];
// body1
ret[bJ] = ret[bJ] + f[0];
ret[bJ+1] = ret[bJ+1] + f[1];
ret[bJ+2] = ret[bJ+2] + f[2];
}
}
// For each body, return the summ of forces all other bodies applied to it.
return ret;
}
For faster interop with JS I recommend use typed arrays if this possible
export const FLOAT64ARRAY_ID = idof<Float64Array>();
export function nBodyForces(data: Float64Array): Float64Array { ... }
And later on JavaScript side:
const loader = require("assemblyscript/lib/loader");
const imports = {};
const wasm = await loader.instantiateStreaming(fetch("optimized.wasm"), imports);
const dataArray = [... your data ...]
const dataRef = wasm.__retain(wasm.__allocArray(wasm.FLOAT64ARRAY_ID, dataArray));
const resultRef = wasm.nBodyForces(dataRef);
const resultArray = wasm.__getFloat64Array(resultRef);
// release ARC resources
wasm.__release(dataRef);
wasm.__release(resultRef);
console.log("result: " + resultArray);

About SBC function rstan::sbc

Here I use the notations from the following example codes of SBC.
I have two questions about rstan:sbc.
Is it possible to extract the samples y described in y = binomial_rng(N, pi_); in the transformed data block ?
Is it possible to plot the rank statistics of user specified parameters only?.
If multiple parameter such as;
parameters {
real<lower = 0, upper = 1> pi;
real<lower = 0, upper = 1> ppi;
real<lower = 0, upper = 1> pppi;
}
then I want to plot the rank statistics specified parameter only.
E.g., the following manner
plot(output, pars =c("pi","ppi"))
where output is an return value of rstan::sbc.
Example of SBC
data {
int<lower = 1> N;
real<lower = 0> a;
real<lower = 0> b;
}
transformed data { // these adhere to the conventions above
real pi_ = beta_rng(a, b);
int y = binomial_rng(N, pi_);
}
parameters {
real<lower = 0, upper = 1> pi;
}
model {
target += beta_lpdf(pi | a, b);
target += binomial_lpmf(y | N, pi);
}
generated quantities { // these adhere to the conventions above
int y_ = y;
vector[1] pars_;
int ranks_[1] = {pi > pi_};
vector[N] log_lik;
pars_[1] = pi_;
for (n in 1:y) log_lik[n] = bernoulli_lpmf(1 | pi);
for (n in (y + 1):N) log_lik[n] = bernoulli_lpmf(0 | pi);
}
Edit for comments
Let output be a return value of rstan::sbc, then
output$Y is the following:
:
:
:
[[496]]
named numeric(0)
[[497]]
named numeric(0)
[[498]]
named numeric(0)
[[499]]
named numeric(0)
[[500]]
named numeric(0)
Edit for comments 2
Let stanmodel be an object of class stanmodel for the following .stan file. Then the following object output$Y is not functional.
output <- rstan::sbc(stanmodel,
data = list(
ww=-0.81,www =0.001,
mm=0.65,mmm=0.001,
vv=5.31,vvv=0.001,
zz= 1.55,zzz=0.001,
NL = 259, NI = 57,C=3,c=3:1,N=3
), M = 500, refresh = 0)
Stan file
data{ // SBC
//This is not prior truth data, but somedata to run
int <lower=0>N; //This is exactly same as C
int <lower=0>NL; //Number of Binomial trials
int <lower=0>NI; //This is redandunt
int <lower=0>C; // Number of Confidence level
int <lower=0>c[N]; //Each component means confidence level
//Prior which shold be specified
real www;
real mmm;
real vvv;
real zzz;
real zz;
real ww;
real vv;
real mm;
}
transformed data {
int h[C];
int f[C];
real w_ ;
real <lower=0>dz_[C-1] ;
real m_;
real <lower =0> v_;
real <lower=0,upper=1>p_[C];
real <lower=0>l_[C];
real <lower=0>dl_[C];
real z_[C];
real a_;
real <lower=0>b_;
w_ = normal_rng (ww,www);
for(cd in 1:C-1) dz_[cd] = normal_rng (zz,zzz);
m_ = normal_rng (mm,mmm);
v_ = normal_rng (vv,vvv);
a_=m_/v_;
b_=1/v_;
for(cd in 1 : C-1) { z_[1]=w_;
z_[cd+1] =z_[cd] +dz_[cd];
}
for(cd in 1 : C) { if (cd==C) {
p_[cd] = 1 - Phi((z_[cd] - m_)/v_);
}else{
p_[cd] = Phi((z_[cd+1] - m_)/v_)- Phi( (z_[cd] -m_)/v_);
}
}
for(cd in 1 : C) {l_[cd] = (-1)*log(Phi(z_[cd])); }
for(cd in 1:C){
if (cd==C) {dl_[cd]=fabs(l_[cd]-0);
}else{
dl_[cd]=fabs(l_[cd]-l_[cd+1]);
}
}
for(n in 1:N) {
h[n] = binomial_rng(NL, p_[c[n]]);
// fff[n] ~ poisson( l[c[n]]*NL);//Non-Chakraborty's model
f[n] = poisson_rng (dl_[c[n]]*NI);//Chakraborty's model //<-------very very very coution, not n but c[n] 2019 Jun 21
// fff[n] ~ poisson( l[c[n]]*NI);//Non-Chakraborty's model
}
}
parameters{
real w;
real <lower =0>dz[C-1];
real m;
real <lower=0>v;
}
transformed parameters {
real <lower=0,upper=1>p[C];
real <lower=0>l[C];
real <lower=0>dl[C];
real z[C];
real a;
real b;
a=m/v;
b=1/v;
for(cd in 1 : C-1) { z[1] = w;
z[cd+1] = z[cd] +dz[cd];
}
for(cd in 1 : C) {
if (cd==C) { p[cd] = 1 - Phi((z[cd] -m)/v);
}else{
p[cd] = Phi((z[cd+1] -m)/v)- Phi((z[cd] -m)/v);
}
}
for(cd in 1 : C) { l[cd] = (-1)*log(Phi(z[cd])); }
for(cd in 1:C){
if (cd==C) {dl[cd] = fabs(l[cd]-0);
}else{
dl[cd] = fabs(l[cd]-l[cd+1]);
}
}
}
model{
for(n in 1:N) {
h[n] ~ binomial(NL, p[c[n]]);
// fff[n] ~ poisson( l[c[n]]*NL);//Non-Chakraborty's model
f[n] ~ poisson(dl[c[n]]*NI);//Chakraborty's model //<-------very very very coution, not n but c[n] 2019 Jun 21
// fff[n] ~ poisson( l[c[n]]*NI);//Non-Chakraborty's model
}
// priors
w ~ normal(ww,www);
for(cd in 1:C-1) dz[cd] ~ normal(zz,zzz);
m ~ normal(mm,mmm);
v ~ normal(vv,vvv);
}
generated quantities { // these adhere to the conventions above
int h_[C];
int f_[C];
vector [3 + C - 1] pars_;
int ranks_[3 + C - 1];
ranks_[1] = w > w_;
ranks_[2] = m > m_;
ranks_[3] = v > v_;
for (cd in 1:(C - 1)) ranks_[cd+3] = dz[cd] > dz_[cd];
pars_[1] = w_;
pars_[2] = m_;
pars_[3] = v_;
for (cd in 1:(C - 1)) pars_[cd+3] = dz_[cd];
// Here I copy the prior predictive realizations to y_ , and now it is denoted by h_ or f_
h_ = h;
f_ = f;
}
The list produced by sbc has an element called Y that holds realizations of the prior predictive distribution. There is no option (yet) to plot a subset of parameters, but you could make your own plot fairly easily based on the original code
https://github.com/stan-dev/rstan/blob/develop/rstan/rstan/R/SBC.R#L96

Createjs function

I am trying to convert an old simulation from Flash to createjs with animate cc. The only code you have is to rotate a piece but I can not get it to work. This code not work:
function spinit()
{
var ang = myangle * Math.PI / 180;
this.pin1.x = disk1.x + R * Math.cos(ang);
this.pin1.y = disk1.y + R * Math.sin(ang);
this.yoke1.x = pin1.x;
this.disk1.rotate = myangle;
this.myangle = myangle + 1;
if (myangle > 360)
{
myangle = 0;
}
}
var myangle = 0;
var R = 90;
setInterval(spinit, 5);
Chances are good this is a scope issue. Your spinit method is being called anonymously, so it won't have access to any of your frame content referenced with this. You can get around this by scoping your method, and binding your setInterval call.
this.spinit = function() // 1. scope the function
{
var ang = myangle * Math.PI / 180;
this.pin1.x = disk1.x + R * Math.cos(ang);
// etc
setInterval(spinit.bind(this), 5); // 2. bind this so it calls in the right scope.
}
Make sure to call this.spinit().
Hope that helps!

How to compute the cubehelix color scheme in Less.js?

I want to compute the cubehelix color scheme in Less so I can tweak some variables. I believe this necessitates CIE L*a*b color system. I ran across Chroma.js which seems like it would work for computing colors, but now I'd like to integrate this into Less.
Mike Bostock has implemented and extended cubehelix in JavaScript as a plugin for the D3.js visualisation library (see examples).
You can use the code of Bostock's plugin to write a custom function for Less.
Download and unzip the source from github at: https://github.com/less/less.js/archive/master.zip
Run npm install
Create a file called lib/less/functions/cubehelix.js and write down the following content into it:
var Color = require("../tree/color"),
functionRegistry = require("./function-registry");
function d3_interpolate(y) {
return function(a, b) {
a = a.toHSL();
b = b.toHSL();
var radians = Math.PI / 180;
var ah = (a.h + 120) * radians,
bh = (b.h + 120) * radians - ah,
as = a.s,
bs = b.s - as,
al = a.l,
bl = b.l - al;
if (isNaN(bs)) bs = 0, as = isNaN(as) ? b.s : as;
if (isNaN(bh)) bh = 0, ah = isNaN(ah) ? b.h : ah;
return function(t) {
var h = ah + bh * t,
l = Math.pow(al + bl * t, y),
a = (as + bs * t) * l * (1 - l),
cosh = Math.cos(h),
sinh = Math.sin(h);
return "#"
+ hex(l + a * (-0.14861 * cosh + 1.78277 * sinh))
+ hex(l + a * (-0.29227 * cosh - 0.90649 * sinh))
+ hex(l + a * (+1.97294 * cosh));
};
};
}
function hex(v) {
var s = (v = v <= 0 ? 0 : v >= 1 ? 255 : v * 255 | 0).toString(16);
return v < 0x10 ? "0" + s : s;
}
functionRegistry.addMultiple({
cubehelix: function(y,a,b,t) {
return new Color(d3_interpolate(y.value)(a,b)(t.value).slice(1),1);
}
});
Open the lib/less/function/index.js file and append require("./cubehelix"); to the list of register functions, just before return functions;
Run grunt dist (to create a new version of less.js)
Now the following Less code:
p{color: cubehelix(1,red,blue,1);}
p{color: cubehelix(1,red,blue,0.5);}
p{color: cubehelix(1, hsl(300,50%,0%), hsl(-240,50%,100%), 0.3);}
outputs:
p {
color: #766cfd;
}
p {
color: #21ba40;
}
p {
color: #4c4c4c;
}

get an specific object from my arrayList(Java)

hi my problem is that in my code i am calling a method that calculates the different between 2 point and then if that distance is less that 7 it will call another class method that should change the color of the target to red... my problem is that in my arraylist i have 3 or five or depends on the user input targets... so how can i specify the object in my arraylist that is going to be change of color>??? this is my code
package project1;
import java.util.*;
import javax.swing.*;
/**
*
* #author Elvis De Abreu
*/
public class TargetGallery
{
/**ArrayList of Targets initialize as a private*/
private ArrayList<Target> mytargets = new ArrayList<>();
/**Static object for the Target class*/
static Target tg = new Target();
/**Static object for the RifleSite class*/
static RifleSite rs = new RifleSite();
/**Static object for the TargetGallery class*/
static TargetGallery tgy = new TargetGallery();
/**the number of targets input by the user as private*/
private int number = 0;
/**array that store the distance between 2 point for each target*/
private double[] total;
/**
* Method that build the background of the canvas
* with a picture as a environment
*/
private void buildWorld()
{
StdDraw.setXscale(0, 250);
StdDraw.setYscale(0, 250);
StdDraw.picture(75, 130, "bath.jpeg", 450, 285);
}
/**
* Method that draw a weapon in the middle of the
* canvas as a shooter weapon
*/
private void drawShooter()
{
StdDraw.setXscale(0, 250);
StdDraw.setYscale(0, 250);
StdDraw.picture(125, 0, "weapon.png", 80, 45);
}
/**
* randomly generates X locations for the targets
* add them into the array list
*/
private void createTargets()
{
double x = 125;
double y = 175;
double radius = 7;
String input = JOptionPane.showInputDialog("Type a number" +
"between 2 and 5");
number = Integer.parseInt(input);
for(int i = 0; i < number; i++)
{
Target targ = new Target(x, y, radius);
mytargets.add(targ);
Random rand = new Random();
x = rand.nextInt(400) + 10;
for (Target e: mytargets)
{
if ((e.getX() <= (x+10)) || (e.getX() >= (x-10)))
{
mytargets.clear();
i--;
continue;
}
}
}
}
/**
* Method that run different methods which start the program
*/
public void run()
{
tgy.buildWorld(); //call the buildWorld method
tgy.drawShooter(); //call the drawShooter method
tgy.createTargets(); //call the createTarget method
tgy.simulate(); //call the simulate method
}
/**
* calculates the distance between the RifleSite and the Targets
*/
public void calcDistance()
{
//variable declaration/initialization
double distance;
double distance1;
int i = 0;
total = new double[number];
//for each loop to calculate x and y location of RifleSite and Targets
for (Target e: mytargets)
{
distance = Math.pow(e.getX()-rs.getX(), 2.0);
distance1 = Math.pow(e.getY()-rs.getY(), 2.0);
total[i++] = Math.sqrt(distance + distance1);
}
}
/**
* Method that simulates the game
*/
public void simulate()
{
//Variable declaration/initialization
boolean alive = true;
for(Target e: mytargets)
{
e.drawAlive();
}
rs.drawRifleSite();
//loop that will run while there is still targets alive or user press q
while(alive == true)
{
//if user press a key this
if (StdDraw.hasNextKeyTyped())
{
char ch = StdDraw.nextKeyTyped(); //store the key pressed
//if person press Q will quit the program
if (ch == 'q')
{
int done = JOptionPane.showConfirmDialog(null,
"The Program will close now bye :)");
System.exit(0);
}
else if (ch == 'f')
{
tgy.calcDistance(); //calculates the distance
//if statement to check if the distance if less than radius
for(int i = 0; i < number; i++)
{
if (total[i] <= 7)
{
//THIS IS WHERE MY METHOD SHOULD GO
//SHOULD BE SOMETHING LIKE E.drawDead
}
}
}
}
}
}
/**
* Method for the main of the Program
* #param args the command line arguments
*/
public static void main(String[] args)
{
}
}
Like this:mytargets.get(INDEX GO HERE)
i Hope that helps
(the index starts from 0)
For example:
Target t=mytargets.get(0);
if ((t.getX() > 10) && (t.getY() > 10))
{
//blablabla
}