How to find objective function for a Particle Swarm Optimization - particle-swarm

I am new to Particle Swarm Optimization and trying to write a code in octave.
swarm_size=10; %number of the swarm particles
maxIter = 50; %maximum number of iterations
inertia = 1.0; %i dont know what it does
correction_factor = 2.0 ; % i dont know what it does too
X=csvread('batting_data.csv'); %load file into octave
x=X(:,2:columns(X));
D=reshape(x,[],2);
plotObjFcn=1; %make it 0 if you dont want to plot a grpah
for i =1: columns(x)
local_best=mean(x(:,i));
particle_init=x(randi(x(:,i),1,swarm_size),
initial_vel=0;
end
Now having reached here i need to have an objective function (I am hoping that i am correct till here)
The data i have used here can be downloaded from
www.amstat.org/publications/jse/v21n3/scariano/batting_data.csv
Now i am not getting how to write an objective function to maximize value in each column. and at the end i want these five values in matrix form.
Help is deeply appreciated and if you find that my concepts are not correct kindly enlighten me

Related

Spline binary logistic regression in R

I am beginner in using R. I want to run a binary logistic regression and I guess some variables have nonlinearities. So I want to use splines method to understand affect of each range in a continuous variable. I am confused about it.
How can I do it in R ?
Knots (cut points) will determine automatically or I should determine manually ?
How can I know overall p-value of variable ?
model<- lrm(formula = PA ~ rcs(HEIGHT) + SLOPE + ASPECT, data=data, x=TRUE, y=TRUE)
I do not know "rcs" is helpful or not.. I found it by searching here. I will grateful if you guide me about it.

Using libigl's uniformly_sample_two_manifold

I'm trying to use the function of libigl uniformly_sample_two_manifold, but it does not work as described and there is no documentation whatsoever to help me understand why.
I have a 3D mesh represented as Eigen::MatrixXd V with vertices and Eigen::MatrixXi F with faces. I'm attempting to use the function as follows:
igl::uniformly_sample_two_manifold(V, F, 20, 1.0, Out);
... giving the function my vertices, faces, and asking for 20 uniform samples in the Out structure. I set the "push factor" to 1 since I donĀ“t think I have any use for it now.
I noticed that the function specifically askes for "positions of mesh in weight space", which I presumed means the vertex positions. If I use it like this, however, the function returns the expected amount of vertices which are clustered very close to each other and are by no means uniformly distributed across the mesh.
Does anyone happen to know how to correctly use this function? Or would anyone know what does this "weight space" mean?
Thanks!

Physics - Projectile get launch angle to hit desired location?

I am programming a simple ball projectile in a game.
the update pretty much looks like:
velocity += gravity;
velocity *=0.9;
pos += vel;
Is there a way to set the angle and power of the launch in order to hit a point that is specified with the mouse?
like peggle, http://youtu.be/4KbNiWsgJck?t=45s
I know there is a solution that I have used several years ago, but I can't find it.
I believed it turned my update into a quadratic formula, or derived it or something.
It had two solutions that was solved with the quadratic equation.
ps- hopefully this could be in 3D, but I could use a 2D solution too because my curve would be 2D
any help?
thanks,
Dan
Yes, you can do this. If you can change the angle and speed, you have more variability than you need, so you have to find a reasonable set of parameters that will work, which isn't hard. The basic equations are:
x = x0 + t*v0x
y = y0 + v0yt + (1/2)ayt2
Here, x and y will be the points you want to hit, and t will be the time that you hit them. t won't show up in the final solution, but you'll use it as in intermediary to calculate the values you want.
Basically, then, pick a reasonable value for v0x. Using the x-equation, find what t will be when the target is hit. Then plug this value into the y-equation, and solve for v0y. This then will give you a pair of values of v0x and v0y that will work to hit the target.

LabView cos fitting

I am working on a program that needs to fit numerous cosine waves in order to determine one of the parameters for the function. The equation that I am using is y = y_0 + Acos((4*pi*L)/x + pi) where L is the value that I am trying to obtain from the best fit line.
I know that it is possible to do this correctly by hand for each set of data, but what is the best way to automate this process? I am currently reading in the data from text files, and running a loop with the initial paramiters changing until I have an array of paramater values that have an amplitude similar to the data, then I check the percent difference between points on the center peak and two end peaks to try to pick the best one. It in consistently picking lower values than what I get when fitting by hand (almost exactly one phase off). So is there a way to improve this method, or another method that works better?
Edit: My LabVIEW version has a cos fitting VI which is what I am using, the problem is when I try to automate the fitting by changing the initial parameters using a loop, I cant figure out how to get the program to pick the same best fit line as a human would pick.
Why not just use a Fast Fourier Transform? This should be way faster than fitting a cosine. In the result vector of complex numbers look for the largest peak of in the totals. You're given frequency (position in the FFT result vector), amplitude and phase.
You can evaluate the goodness of the fit by computing the difference between fitting curve and your data. A VI does this in the "Advanced curve fitting" palette. Then all you have to do is pick up the best fit.

Normal Distribution function

edit
So based on the answers so far (thanks for taking your time) I'm getting the sense that I'm probably NOT looking for a Normal Distribution function. Perhaps I'll try to re-describe what I'm looking to do.
Lets say I have an object that returns a number of 0 to 10. And that number controls "speed". However instead of 10 being the top speed, I need 5 to be the top speed, and anything lower or higher would slow down accordingly. (with easing, thus the bell curve)
I hope that's clearer ;/
-original question
These are the times I wish I remembered something from math class.
I'm trying to figure out how to write a function in obj-C where I define the boundries, ex (0 - 10) and then if x = foo y = ? .... where x runs something like 0,1,2,3,4,5,6,7,8,9,10 and y runs 0,1,2,3,4,5,4,3,2,1,0 but only on a curve
Something like the attached image.
I tried googling for Normal Distribution but its way over my head. I was hoping to find some site that lists some useful algorithms like these but wasn't very successful.
So can anyone help me out here ? And if there is some good sites which shows useful mathematical functions, I'd love to check them out.
TIA!!!
-added
I'm not looking for a random number, I'm looking for.. ex: if x=0 y should be 0, if x=5 y should be 5, if x=10 y should be 0.... and all those other not so obvious in between numbers
alt text http://dizy.cc/slider.gif
Okay, your edit really clarifies things. You're not looking for anything to do with the normal distribution, just a nice smooth little ramp function. The one Paul provides will do nicely, but is tricky to modify for other values. It can be made a little more flexible (my code examples are in Python, which should be very easy to translate to any other language):
def quarticRamp(x, b=10, peak=5):
if not 0 <= x <= b:
raise ValueError #or return 0
return peak*x*x*(x-b)*(x-b)*16/(b*b*b*b)
Parameter b is the upper bound for the region you want to have a slope on (10, in your example), and peak is how high you want it to go (5, in the example).
Personally I like a quadratic spline approach, which is marginally cheaper computationally and has a different curve to it (this curve is really nice to use in a couple of special applications that don't happen to matter at all for you):
def quadraticSplineRamp(x, a=0, b=10, peak=5):
if not a <= x <= b:
raise ValueError #or return 0
if x > (b+a)/2:
x = a + b - x
z = 2*(x-a)/b
if z > 0.5:
return peak * (1 - 2*(z-1)*(z-1))
else:
return peak * (2*z*z)
This is similar to the other function, but takes a lower bound a (0 in your example). The logic is a little more complex because it's a somewhat-optimized implementation of a piecewise function.
The two curves have slightly different shapes; you probably don't care what the exact shape is, and so could pick either. There are an infinite number of ramp functions meeting your criteria; these are two simple ones, but they can get as baroque as you want.
The thing you want to plot is the probability density function (pdf) of the normal distribution. You can find it on the mighty Wikipedia.
Luckily, the pdf for a normal distribution is not difficult to implement - some of the other related functions are considerably worse because they require the error function.
To get a plot like you showed, you want a mean of 5 and a standard deviation of about 1.5. The median is obviously the centre, and figuring out an appropriate standard deviation given the left & right boundaries isn't particularly difficult.
A function to calculate the y value of the pdf given the x coordinate, standard deviation and mean might look something like:
double normal_pdf(double x, double mean, double std_dev) {
return( 1.0/(sqrt(2*PI)*std_dev) *
exp(-(x-mean)*(x-mean)/(2*std_dev*std_dev)) );
}
A normal distribution is never equal to 0.
Please make sure that what you want to plot is indeed a
normal distribution.
If you're only looking for this bell shape (with the tangent and everything)
you can use the following formula:
x^2*(x-10)^2 for x between 0 and 10
0 elsewhere
(Divide by 125 if you need to have your peek on 5.)
double bell(double x) {
if ((x < 10) && (x>0))
return x*x*(x-10.)*(x-10.)/125.;
else
return 0.;
}
Well, there's good old Wikipedia, of course. And Mathworld.
What you want is a random number generator for "generating normally distributed random deviates". Since Objective C can call regular C libraries, you either need a C-callable library like the GNU Scientific Library, or for this, you can write it yourself following the description here.
Try simulating rolls of dice by generating random numbers between 1 and 6. If you add up the rolls from 5 independent dice rolls, you'll get a surprisingly good approximation to the normal distribution. You can roll more dice if you'd like and you'll get a better approximation.
Here's an article that explains why this works. It's probably more mathematical detail than you want, but you could show it to someone to justify your approach.
If what you want is the value of the probability density function, p(x), of a normal (Gaussian) distribution of mean mu and standard deviation sigma at x, the formula is
p(x) = exp( ((x-mu)^2)/(2*sigma^2) ) / (sigma * 2 * sqrt(pi))
where pi is the area of a circle divided by the square of its radius (approximately 3.14159...). Using the C standard library math.h, this is:
#include <math>
double normal_pdf(double x, double mu, double sigma) {
double n = sigma * 2 * sqrt(M_PI); //normalization factor
p = exp( -pow(x-mu, 2) / (2 * pow(sigma, 2)) ); // unnormalized pdf
return p / n;
}
Of course, you can do the same in Objective-C.
For reference, see the Wikipedia or MathWorld articles.
It sounds like you want to write a function that yields a curve of a specific shape. Something like y = f(x), for x in [0:10]. You have a constraint on the max value of y, and a general idea of what you want the curve to look like (somewhat bell-shaped, y=0 at the edges of the x range, y=5 when x=5). So roughly, you would call your function iteratively with the x range, with a step that gives you enough points to make your curve look nice.
So you really don't need random numbers, and this has nothing to do with probability unless you want it to (as in, you want your curve to look like a the outline of a normal distribution or something along those lines).
If you have a clear idea of what function will yield your desired curve, the code is trivial - a function to compute f(x) and a for loop to call it the desired number of times for the desired values of x. Plot the x,y pairs and you're done. So that's your algorithm - call a function in a for loop.
The contents of the routine implementing the function will depend on the specifics of what you want the curve to look like. If you need help on functions that might return a curve resembling your sample, I would direct you to the reading material in the other answers. :) However, I suspect that this is actually an assignment of some sort, and that you have been given a function already. If you are actually doing this on your own to learn, then I again echo the other reading suggestions.
y=-1*abs(x-5)+5