Using fxrand() for p5 project? - p5.js

I used the p5 editor to build an nft, and I'm working on getting it working in the fxhash sandbox. Using p5's random() function worked great when I uploaded my project to the sandbox, but quickly realized I needed to implement the fxrand() function to ensure that each individual iteration is the same when refreshing with the same hash.
Simply replacing all instances of the p5 random() function with fxrand() did not work, and I'm assuming because fxrand() simply generates a random number, whereas p5's random() function can be used in other ways (ie; random(-50, 50)).
How do I need to incorporate the fxrand() function into my project in a way that still works the same way as p5's random() function?

You may have already figured this out, and there's probably far better solutions (I'm very new to this), but here is what I figured out.
If I need a number from 0 to 9 then I can use this:
let randChoose1 = Math.floor(fxrand() * 10;
Anywhere I need to call that number I can simply use randChoose1 in place. For example, if I have an array named "bg" with 10 entries in the array, and I want to choose something from the array I can do this:
let randoBg = bg[randChoose1];
Maybe that's an image that I want to center on the canvas, I can call it with:
image(randoBg, width / 2, height / 2);
If I have 23 items in the array then I just need to declare randChoose1 with:
let randChoose1 = Math.floor(fxrand() * 23);
If you want to be able to have negative numbers be chosen, such as your example of a range from -50 to 50, it's just a matter of multiplying by rough total range you want and then subtracting half that.
let randChoose1 = Math.floor(fxrand() * 101 - 50;
In this case, randChoose1 will give you that range of results from -50 to 50. You have to multiply by 101 in order to make it possible for Math.floor to deliver 100 since it always rounds down.
If you found a better solution I'd love to hear it! This is something I'm struggling with as well, and my total experience with p5.js is less than a week at this point.

If you use randomSeed(int(fxrand()*987654321)) at the beginning of the setup function every time you call to the random function it will depend on fxrand

Related

How to include an array of weights to adjust importance of observed data in sm.tsa.UnobservedComponents?

I have used the following 5 lines to achieve a kalman filter with your work for a smoothed pricing model, and it worked great.
mod = sm.tsa.UnobservedComponents(obs, 'local level')
lm = sm.OLS(obs, xlm, missing='drop').fit()
obs_noise = abs(lm.resid).mean()
params = [obs_noise, obs_noise / obs_noise_level]
mod_filter, mod_smooth = mod.filter(params), mod.smooth(params)
However currently I would like to adjust the filtering smoothness at certain time, for example, when unemployment rate or interest rate made a big surge, I would like to make the output (Kalman filtered/smoothed) value closer to the observed value, while in most other time I will keep the what it is from the model. So, I have created an array, while a few items greater than 1, and the others will be exactly 1.
e.g.: ir_coeff = np.array([1,1,1,1,1.345,1.23,1.78,1,1,1])
What could be the best approach to achieve this? Thank you a lot in advance.
I have tried to include it in the output file with a dot product operation, however it is not reasonable to do this.

Parameters for dlib::find_min_bobyqa

I'm working on the C++ version of Matt Zucker's Page dewarping. So far everything works fine, but I have a problem with optimization. In line 748 of Github repo Matt uses optimize function from Scipy. My C++ equivalent is find_min_bobyqa from dlib.net. The code is:
auto f = [&](const column_vector& ppts) { return objective( dstpoints, ppts, keypoint_index); };
dlib::find_min_bobyqa(f,
params,
2 * params.nr() + 1, // npt - number of interpolation points: x.size() + 2 <= npt && npt <= (x.size()+1)*(x.size()+2)/2
dlib::uniform_matrix<double>(params.nr(), 1, -2), // lower bound constraint
dlib::uniform_matrix<double>(params.nr(), 1, 2), // upper bound constraint
1, // initial trust region radius
1e-5, // stopping trust region radius
4000 // max number of objective function evaluations
);
In my concrete example params is a dlib::column_vector with double values and length = 189. Every element of params is less than 2.0 and greater than -2.0. Function objective() returns double value and "alone" it works properly because I get the same value as in the Python version. But after running fin_min_bobyqa function I usually get the message:
Terminate called after throwing an instance of 'dlib:bobyqa_failure', return from BOBYQA because the objective function has been called max_f_evals times.
I set max_f_evals to quite big value to see if it optimizes at all, but it doesn't. I did some tweaking with parameters but without good results. How should I set the parameters of find_min_bobyqa to get the right solution?
I am very interested in this issue as well. Zucker's work, with very minor tweaks, is ideal for straightening sheet music images, and I was looking for ways to implement it in a mobile platform when I came across your question.
My research so far suggests that BOBYQA is not the equivalent of Powell's method in scipy. BOBYQA is constrained, and the one in scipy is not.
See these links for more information, and a possible way to compile the right supporting library - I would try UOBYQA or NEWUOA.
https://github.com/jacobwilliams/PowellOpt
https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.minimize.html#rdd2e1855725e-3
(See the Notes section)
EDIT: see C version here:
https://github.com/emmt/Algorithms/tree/master/newuoa
I wanted to post this as a comment, but I don't have enough points for that.
I am very interested in your progress. If you're willing, please keep me posted.
I finally solved this problem. I used PRAXIS library, because it doesn't need derivative information and is fast.
I modified the code a little to my needs and now it is faster around few seconds than original version written in Python.

GameMaker studio 2. Player Knockback

trying to create a player damage indication when a collision with an enemy occurs.
I used this code within a collision event of the player object:
direction = point_direction(other.x,other.y,x,y);
hsp = lengthdir_x(6,direction);
vsp = lengthdir_y(4,direction)-2;
if (sign(hsp) !=0) image_xscale = sign(hsp);
However, the player object is simply pushed upward vertically rather than backwards in a parabola.
Any, ideas on how to implement a basic knockback system?
If you want a parabola, you can add an upward force afterward, like so:
direction = point_direction(other.x, other.y, x , y);
speed = 6
motion_add(90, 3)
If you don't and you'd rather a more "repeatable" parabola that always look the same, maybe you should use another method, something like
if other.x>x {hdirection=1}else{hdirection=-1}
hspeed = hdirection*6
vspeed = -2
I believe this would work better for what you're trying to achieve, unless you want to implement knockback variable depending on the angle of collision.
So I would need to see all the rest of your player physics to be sure, but I can tell you right now that direction = point_direction(other.x,other.y,x,y); is probable not what you mean, and same goes for lengthdir(). The exact origins of the colliding objects at the moment of collision have a huge effect on what that direction is, which can cause a lot of screwiness. For example: if the line is perfectly horizontal (because other.y == y) then lengthdir_y() will always be equal to zero for any input value no matter how huge.
But more importantly direction is a built-in variable of GameMaker, so using it with a custom physics system can also cause some screwiness. Fox's answer might help if you are using built-ins, but based on the fact that you have an "hsp" and "vsp" instead of hspeed and vspeed, my guess is you want to avoid built-ins.
If you just want to get the horizontal direction of the collision, you should use sign(x - other.x). Then, instead of using lengthdir(), you can just use a constant. Here it is all together:
var dir = sign(x - other.x)
hsp = 6*dir; //I'm assuming that 6 is how much horizontal you wanted
vsp = -4;
if (sign(hsp) !=0) image_xscale = sign(hsp); //This line could just go in your step event
Hope that helps! Feel free to comment if you have more questions.

(Using Julia) How can I reduce my data matrix by averaging values from the same hour?

I am trying to reduce the size of my data and I cannot make it work. I have data points taken every minute over 1 month. I want to reduce this data to have one sample for every hour. The problem is: Some of my runs have "NA" value, so I delete these rows. There is not exactly 60 points for every hour - it varies.
I have a 'Timestamp' column. I have used this to make a 'datehour' column which has the same value if the data set has the same date and hour. I want to average all the values with the same 'datehour' value.
How can I do this? I have tried using the if and for loop below, but it takes so long to run.
Thanks for all your help! I am new to Julia and come from a Matlab background.
======= CODE ==========
uniquedatehour=unique(datehour,1)
index=[]
avedata=reshape([],0,length(alldata[1,:]))
for j in uniquedatehour
for i in 1:length(datehour)
if datehour[i]==j
index=vcat(index,i)
else
rows=alldata[index,:]
rows=convert(Array{Float64,2},rows)
avehour=mean(rows,1)
avedata=vcat(avedata,avehour)
index=[]
continue
end
end
end
There are several layers to optimizing this code. I am assuming that your data is sorted on datehour (your code assumes this).
Layer one: general recommendation
Wrap your code in a function. Executing code in global scope in Julia is much slower than within a function. By wrapping it make sure to either pass data to your function as arguments or if data is in global scope it should be qualified with const;
Layer two: recommendations to your algorithm
Statement like [] creates an array of type Any which is slow, you should use type qualifier like index=Int[] to make it fast;
Using vcat like index=vcat(index,i) is inefficient, it is better to do push!(index, i) in place;
It is better to preallocate avedata with e.g. fill(NA, length(uniquedatehour), size(alldata, 2)) and assign values to an existing matrix than to do vcat on it;
Your code will produce incorrect results if I am not mistaken as it will not catch the last entry of uniquedatehour vector (assume it has only one element and check what happens - avedata will have zero rows)
Line rows=convert(Array{Float64,2},rows) is probably not needed at all. If alldata is not Matrix{Float64} it is better to convert it at the beginning with Matrix{Float64}(alldata);
You can change line rows=alldata[index,:] to a view like view(alldata, index, :) to avoid allocation;
In general you can avoid creation of index vector as it is enough that you remember start s and end e position of the range of the same values and then use range s:e to select rows you want.
If you correct those things please post your updated code and maybe I can help further as there is still room for improvement but requires a bit different algorithmic approach (but maybe you will prefer option below for simplicity).
Layer three: how I would do it
I would use DataFrames package to handle this problem like this:
using DataFrames
df = DataFrame(alldata) # assuming alldata is Matrix{Float64}, otherwise convert it here
df[:grouping] = datehour
agg = aggregate(df, :grouping, mean) # maybe this is all what you need if DataFrame is OK for you
Matrix(agg[2:end]) # here is how you can convert DataFrame back to a matrix
This is not the fastest solution (as it converts to a DataFrame and back but it is much simpler for me).

How do I create random in Eclipse?

I have 10 images and I want them to be prompt out randomly. What code should I use? I'm still an amateur so I hope I could get some answers here... The images are named like 'pic1', 'pic2' and so on. is it possible to get the number from the file name and use Math.random() ?
Store the pics in an Array.
Say array index is from 0 to 9
Use Java Math.random to get random number.
You need to multiply its result by 10 get indexes in your range

Resources