I was looking for a function to determine baseline of xy chart. I found some codes that was written in python.
Ex: Python baseline correction library
def baseline_als(y, lam, p, niter=10):
L = len(y)
D = sparse.csc_matrix(np.diff(np.eye(L), 2))
w = np.ones(L)
for i in xrange(niter):
W = sparse.spdiags(w, 0, L, L)
Z = W + lam * D.dot(D.transpose())
z = spsolve(Z, w*y)
w = p * (y > z) + (1-p) * (y < z)
return z
But I don't know how to convert it to C# the result of this code is used to remove the baseline like the following image
This code is based on "Asymmetric Least Squares Smoothing" algorithm by P. Eilers and H. Boelens
If you know any library or sample code for algorithms like "Asymmetric Least Squares Smoothing", please share with me
Related
I'm writing a class which should calculate angles (in degrees), after long trying I don't get it to work.
When r = 45 & h = 0 sum should be around 77,14°
but it returns NaN - Why? I know it must be something with the Math.Atan-Method and a not valid value.
My code:
private int r = 0, h = 0;
public Schutzwinkelberechnung(int r, int h)
{
this.r = r;
this.h = h;
}
public double getSchutzwinkel()
{
double sum = 0;
sum = 180 / Math.PI * Math.Atan((Math.Sqrt(2 * h * r - (h * h)) - r * Math.Sin(Math.Asin((Math.Sqrt(2 * h * r)) / (2 * r)))) / (h - r + r * (Math.Cos(Math.Asin(Math.Sqrt(2 * h * r) / (2 * r))))));
return sum;
}
Does someone see my mistake? I got the formula from an excel sheet.
EDIT: Okay, my problem was that I had a parsing error while creating the object or getting the user input, apparently solved it by accident. Ofc I have to add a simple exception, as Nick Dechiara said. Thank you very much for the fast reply, I appreciate it.
EDIT2: The exception in my excel sheet is:
if(h < 2) {h = 2}
so that's explaining everything and I wasn't paying attention at all. Thanks again for all answers.
int r = 45, h = 2;
sum = 77.14°
A good approach to debugging these kinds of issues is to break the equation into smaller pieces, so it is easier to debug.
double r = 45;
double h = 0;
double sqrt2hr = Math.Sqrt(2 * h * r);
double asinsqrt2hr = Math.Asin((sqrt2hr) / (2 * r));
double a = (Math.Sqrt(2 * h * r - (h * h)) - r * Math.Sin(asinsqrt2hr));
double b = (h - r + r * (Math.Cos(asinsqrt2hr)));
double sum = 180 / Math.PI * Math.Atan(a / b);
Now if we put a breakpoint at sum and let the code run, we see that both a and b are equal to zero. This gives us a / b = 0 / 0 = NaN in the final line.
Now we can ask, why is this happening? Well in the case of b you have h - r + r which is 0 - 45 + 45, evaluates to 0, so b becomes 0. You probably have an error in your math there.
In the case of a, we have 2 * h * r - h * h, which also evaluates to 0.
You probably either A) have an error in your equation, or B) need to include a special case for when h = 0, as that is breaking your math here.
Definitely break up the expression something like
var a = Asin(Sqrt(2 * h * r) / (2 * r));
var b = Sqrt(2 * h * r - h * h) - r * Sin(a);
var c = h - r + r * Cos(a);
var sum = 180 / PI * Atan(b / c);
and you will find b=0 and c=0. You might consider changing the last expression into
var sum = 180 / PI * Atan2(b , c);
which will return a value when b=0 and c=0.
PS. Also, use using static System.Math; in the beginning of the code to shorten such math expressions.
To solve such quadratic programming problem(mean-variance portfolio), I want to use Microsoft.SolverFoundation in C#, but the introduction in
https://msdn.microsoft.com/en-us/library/ff759370(v=vs.93).aspx
is too abstract to understand, can any one give me a specific example or other free libaray I can easily handle?
Here I use accord.net
// Declare symbol variables
double x = 0, y = 0, z = 0;
// Create the function to be optimized
var f = new QuadraticObjectiveFunction(() => x * x - 2 * x * y + 3 * y * y + z * z - 4 * x - 5 * y - z);
// Create some constraints for the solution
var constraints = new List<LinearConstraint>();
constraints.Add(new LinearConstraint(f, () => 6 * x - 7 * y <= 8));
constraints.Add(new LinearConstraint(f, () => 9 * x + 1 * y <= 11));
constraints.Add(new LinearConstraint(f, () => 9 * x - y <= 11));
constraints.Add(new LinearConstraint(f, () => -z - y == 12));
// Create the Quadratic Programming solver
GoldfarbIdnani solver = new GoldfarbIdnani(f, constraints);
// Minimize the function
bool success = solver.Minimize();
double value = solver.Value;
double[] solutions = solver.Solution;
The left question is
how to write x, y, z as a vector x = (x_1, x_2, ... , x_n) since I have a lot of variables(Surely write objective function as the form of matrix f = xMx')?
Can I use the linq query in for the vector in accord.net
Microsoft.SolverFoundation is deprecated.
I would suggest to use Accord.Net if you need to do it in C#.
you can find something in the link below:
http://crsouza.com/2012/04/05/quadratic-programming-in-c/
The part "Manually specifying the QP matrix" will be useful
I have point A (35.163 , 128.001) and point B (36.573 , 128.707)
I need to calculate the points lies within point A and point B
using the standard distance formula between 2 points, I found D = 266.3
each of the points lies within the line AB (the black point p1, p2, ... p8) are separated with equal distance of d = D / 8 = 33.3
How could I calculate the X and Y for p1 , p2, ... p8?
example of Java or C# language are welcomed
or just point me a formula or method will do.
Thank you.
**The above calculation is actually used to calculate the dummy point for shaded level in my map and working for shaded area interpolation purpose*
that's easy but you need some math knowledge.
PointF pointA, pointB;
var diff_X = pointB.X - pointA.X;
var diff_Y = pointB.Y - pointA.Y;
int pointNum = 8;
var interval_X = diff_X / (pointNum + 1);
var interval_Y = diff_Y / (pointNum + 1);
List<PointF> pointList = new List<PointF>();
for (int i = 1; i <= pointNum; i++)
{
pointList.Add(new PointF(pointA.X + interval_X * i, pointA.Y + interval_Y*i));
}
Straitforward trigonometric solution could be something like that:
// I've used Tupple<Double, Double> to represent a point;
// You, probably have your own type for it
public static IList<Tuple<Double, Double>> SplitLine(
Tuple<Double, Double> a,
Tuple<Double, Double> b,
int count) {
count = count + 1;
Double d = Math.Sqrt((a.Item1 - b.Item1) * (a.Item1 - b.Item1) + (a.Item2 - b.Item2) * (a.Item2 - b.Item2)) / count;
Double fi = Math.Atan2(b.Item2 - a.Item2, b.Item1 - a.Item1);
List<Tuple<Double, Double>> points = new List<Tuple<Double, Double>>(count + 1);
for (int i = 0; i <= count; ++i)
points.Add(new Tuple<Double, Double>(a.Item1 + i * d * Math.Cos(fi), a.Item2 + i * d * Math.Sin(fi)));
return points;
}
...
IList<Tuple<Double, Double>> points = SplitLine(
new Tuple<Double, Double>(35.163, 128.001),
new Tuple<Double, Double>(36.573, 128.707),
8);
Outcome (points):
(35,163, 128,001) // <- Initial point A
(35,3196666666667, 128,079444444444)
(35,4763333333333, 128,157888888889)
(35,633, 128,236333333333)
(35,7896666666667, 128,314777777778)
(35,9463333333333, 128,393222222222)
(36,103, 128,471666666667)
(36,2596666666667, 128,550111111111)
(36,4163333333333, 128,628555555556)
(36,573, 128,707) // <- Final point B
Subtract A from B, component-wise, to get the vector from A to B. Multiply that vector by the desired step value and add it to A. (Note that with eight intermediate steps as you've illustrated, the step distance is 1.0 / 9.0.) Something like this, assuming you really want seven points:
vec2 A = vec2 (35.163, 128.001);
vec2 B = vec2 (36.573, 128.707);
vec2 V = B - A;
for (i = 1; i < 8; i++) {
vec2 p[i] = A + V * (float)i / 8.0;
}
(Sorry, don't know any Java or C#.)
let A be point (xa, ya), and B be point (xb, yb)
alpha = tan-1((yb - ya)/(xb - xa))
p1 = (xa + d * cos(alpha), ya + d * sin(alpha))
pk = (xa + kd * cos(alpha), ya + kd * sin(alpha)), k = 1 to 7
(An equivalent way would be to use vector arithmetic)
At first find the slope of AB line. Get help and formula from here: http://www.purplemath.com/modules/slope.htm
Then consider a triangle of Ap1E(think there is a point E which is right to A and below to p1).
You already know the angle AEp1 is 90degree. and you have calculated angle p1AE(from the slope of AB).
Now find AE and Ep1.
Xp1=Xa+AE and Yp1=Ya+Ep1
This will not be very difficult in C# or java.
Once you understand the logic, you will find pleasure implementing on your own way.
I have a (sampled) set of uncalibrated values (x) coming from a device and a set of what they should be (y). I'm looking to find/estimate the cubic polynomial y=ax^3 + bx^2 + cx + d that maps any x to y.
So I think what I need to do is Polynomial Regression first and then find its inverse, but I'm not so sure; and I wonder whether there is a better solution like least squares.
I would appreciate a nudge in the right direction and/or any links to a math library that would be of use.
Have you checked Langrange Interpolation?
It is about the polynomial approximation of a given function.
You can stop the approximation on a given degree of the polynomial (let's say the 3rd degree) on a proper range of the indipendent variable.
Refs:
http://en.wikipedia.org/wiki/Lagrange_polynomial
https://math.stackexchange.com/a/108623
Looks like its just Polynomial Regression; I just need to feed in the raw (x) values and the expected values (y).
Code from Rosetta Code, that uses Math.Net Numerics
using MathNet.Numerics.LinearAlgebra.Double;
using MathNet.Numerics.LinearAlgebra.Double.Factorization;
public static class PolyRegression
{
public static double[] Polyfit(double[] x, double[] y, int degree)
{
// Vandermonde matrix
var v = new DenseMatrix(x.Length, degree + 1);
for (int i = 0; i < v.RowCount; i++)
for (int j = 0; j <= degree; j++) v[i, j] = Math.Pow(x[i], j);
var yv = new DenseVector(y).ToColumnMatrix();
QR qr = v.QR();
// Math.Net doesn't have an "economy" QR, so:
// cut R short to square upper triangle, then recompute Q
var r = qr.R.SubMatrix(0, degree + 1, 0, degree + 1);
var q = v.Multiply(r.Inverse());
var p = r.Inverse().Multiply(q.TransposeThisAndMultiply(yv));
return p.Column(0).ToArray();
}
}
I am having four set of values,namely
S(which ranges from x to y with a variation of .5),
C(which ranges from a to b with a variation of .25),
A(which ranges from p to q with a variation of 1)
Ad(which ranges from c to d with a variation of 1.5).
For each value of S, I should get all possible combinations of values from the other three sets.Can u help me please by suggesting suitable code........
Multiply all values with some constant so that you came into "integer problem domain". Then make 4 nested loops, for Si, Ci, Ai and Adi (S-integer, C-integer, ...). This way you will get all combinations. To get back to "float domain" divide with before mentioned constant.
EDIT:
Forget about previous suggestion. Try something like this:
double x = 1.1, y = 5.1, a = 6.1, b = 7.1, p = 8.1, q = 9.1, c = 10.1, d = 15.1;
double S, C, A, Ad;
for (S=x; S <= y; S = S + .5)
for (C=a; C <= b; C = C + .25)
for (A=p; A <= q; A = A + 1.0)
for (Ad=c; Ad <= d; Ad = Ad + 1.5)
Console.WriteLine("S={0} C={1} A={2}, Ad={3}", S, C, A, Ad);
Console.ReadLine();