I have a model for a mining problem. I am working on adding into the model to use the shortest path inside a mine(open pit) for hauling ore and waste. For this, I was thinking of Dijkstra's algorithm. I could not find any example of the use of Dijkstra's algorithm in OPL. Has anyone done it before and can you share some ideas, please.
if you need to write Dijsktra's algorithm then Daniel is right and you d rather use the scripting part. Now if you need a shortest path within an existing OPL model you could use the following shortest path example:
.mod
tuple edge
{
key int o;
key int d;
int weight;
}
{edge} edges=...;
{int} nodes={i.o | i in edges} union {i.d | i in edges};
int st=1; // start
int en=8; // end
dvar int obj; // distance
dvar boolean x[edges]; // do we use that edge ?
minimize obj;
subject to
{
obj==sum(e in edges) x[e]*e.weight;
forall(i in nodes)
sum(e in edges:e.o==i) x[e]
-sum(e in edges:e.d==i) x[e]
==
((i==st)?1:((i==en)?(-1):0));
}
{edge} shortestPath={e | e in edges : x[e]==1};
execute
{
writeln(shortestPath);
}
.dat
edges=
{
<1,2,9>,
<1,3,9>,
<1,4,8>,
<1,10,18>,
<2,3,3>,
<2,6,6>,
<3,4,9>,
<3,5,2>,
<3,6,2>,
<4,5,8>,
<4,7,7>,
<4,9,9>,
<4,10,10>,
<5,6,2>,
<5,7,9>,
<6,7,9>,
<7,8,4>,
<7,9,5>,
<8,9,1>,
<8,10,4>,
<9,10,3>,
};
which gives
// solution (optimal) with objective 19
{<1 4 8> <4 7 7> <7 8 4>}
If you have a problem that can be solved using Dijkstra's algorithm then it seems a bit of overkill to use OPL or CPLEX to solve it. You could code up the algorithm in any programming language and use it from there. I guess that is why you don't find any examples.
If you still want to implement in OPL then use a scripting (execute) or a main block. The scripting code you can provide there is a superset of JavaScript, so you can implement Dijkstra's algorithm in JavaScript and put it there.
Related
Solving a triangle means finding all possible triangles when some of its sides a,b and c and angles A,B,C (A is the the angle opposite to a, and so on...) are known. This problem has 0, 1, 2 or infinitely many solutions.
I want to write a procedure to solve triangles. The user would feed the procedure with some datas amongst a,b,c,A,B,and C (if it is necessary for the sake of simplicity, you can assume that the user will avoid situations where there are infinitely many solutions) and the procedure will compute the other ones. The usual requires to use the Law of Sines or the Law of Cosines, depending on the situation.
Since it is for a Maths class where I also want to show graphs of functions, I will implement it in Maple. If Maple is not suitable for your answer, please suggest another language (I am reasonably competent in Java and beginner in Python for example).
My naive idea is to use conditional instructions if...then...else to determine the case in hand but it is a little bit boring. Java has a switch that could make things shorter and clearer, but I am hoping for a smarter structure.
Hence my question: Assume that some variables are related by known relations. Is there a simple and clear way to organize a procedure to determine missing variables when only some values are given?
PS: not sure on how I should tag this question. Any suggestion is welcome.
One approach could be to make all of the arguments to your procedure optional with default values that correspond to the names: A, B, C, a, b, c.
Since we can make the assumption that all missing variables are those that are not of type 'numeric', it is easy for us to then quickly determine which variables do not yet have values and give those as the values to a solve command that finds the remaining sides or angles.
Something like the following could be a good start:
trisolve := proc( { side1::{positive,symbol} := A, side2::{positive,symbol} := B, side3::{positive,symbol} := C,
angle1::{positive,symbol} := a, angle2::{positive,symbol} := b, angle3::{positive,symbol} := c } )
local missing := remove( hastype, [ side1, side2, side3, angle1, angle2, angle3 ], numeric );
return solve( { 180 = angle1 + angle2 + angle3,
side1/sin(angle1*Pi/180)=side2/sin(angle2*Pi/180),
side1/sin(angle1*Pi/180)=side3/sin(angle3*Pi/180),
side2/sin(angle2*Pi/180)=side3/sin(angle3*Pi/180),
side1^2=side2^2+side3^2-2*side2*side3*cos(angle1) },
missing );
end proc:
The following call:
trisolve( side1 = 1, angle1 = 90, angle2 = 45 );
returns:
[B = (1/2)*sqrt(2), C = (1/2)*sqrt(2), c = 45]
Could somebody give me a working Ullman's graph isomorphism problem implementation in MATLAB, or link to it. Or if you have at least in C so I would try to implement it in MATLAB.
Thanks
i'm lookign for it too. I've been loking in the web but with no luck so far, but i've found this:
Algorithm, where the algorithm is explained.
On another hand, i found this:
def search(graph,subgraph,assignments,possible_assignments):
update_possible_assignments(graph,subgraph,possible_assignments)
i=len(assignments)
# Make sure that every edge between assigned vertices in the subgraph is also an
# edge in the graph.
for edge in subgraph.edges:
if edge.first<i and edge.second<i:
if not graph.has_edge(assignments[edge.first],assignments[edge.second]):
return False
# If all the vertices in the subgraph are assigned, then we are done.
if i==subgraph.n_vertices:
return True
for j in possible_assignments[i]:
if j not in assignments:
assignments.append(j)
# Create a new set of possible assignments, where graph node j is the only
# possibility for the assignment of subgraph node i.
new_possible_assignments = deep_copy(possible_assignments)
new_possible_assignments[i] = [j]
if search(graph,subgraph,assignments,new_possible_assignments):
return True
assignments.pop()
possible_assignments[i].remove(j)
update_possible_assignments(graph,subgraph,possible_assignments)
def find_isomporhism(graph,subgraph):
assignments=[]
possible_assignments = [[True]*graph.n_vertices for i in range(subgraph.n_vertices)]
if search(graph,subgraph,asignments,possible_assignments):
return assignments
return None
here: implementation. I do not have the skills to transform this into Matlab, if you have them , i would really appreciate if you could share your code when you're done.
I have been trying to learn neural networking and all the examples I saw on the internet gave examples of emulating logic gates say XOR gate. But what I want to do is create a network that can be trained to emulate functions say the x^2 or e^x. Is this possible? What changes in the network do I need to make?
Here's my code for a neural network consisting of 1 input node, one hidden layer consisting of 3 nodes, and one output node.
#include <iostream.h>
#include <fstream.h>
#include <math.h>
#include <time.h>
const double eeta=0.9;
const int n=5;
struct Net_elem
{
double weights1[3];
double weights2[3];
double bias1,bias2;
};//structure to store network paramenters
Net_elem net_elem;
double sigma(double input)
{
return 1/(1+exp(-input));
}
void show_net_elem()
{
cout.precision(15);
for(int i=0;i<3;i++)
{
cout<<"weights1["<<i<<"]="<<net_elem.weights1[i];
cout<<endl;
}
for(int i=0;i<3;i++)
{
cout<<"weights2["<<i<<"]="<<net_elem.weights2[i];
cout<<endl;
}
cout<<"bias1="<<net_elem.bias1<<" bias2="<<net_elem.bias2<<endl;
system("pause");
system("cls");
}
//function to train the network
void train(double input,double expected)
{
double Output,output[3],Delta,delta[3],delta_bias1,delta_bias2;
//Propogate forward
double sum=0;
for(int i=0;i<3;i++)
output[i]=sigma(input*net_elem.weights1[i]+net_elem.bias1);
sum=0;
for(int i=0;i<3;i++)
sum=sum+output[i]*net_elem.weights2[i];
Output=sigma(sum+net_elem.bias2);
cout<<"Output="<<Output<<endl;
//Backpropogate
Delta=expected-Output;
for(int i=0;i<3;i++)
delta[i]=net_elem.weights2[i]*Delta;
delta_bias2=net_elem.bias2*Delta;
//Update weights
for(int i=0;i<3;i++)
net_elem.weights1[i]=net_elem.weights1[i]+eeta*delta[i]*output[i]*(1-output[i])*input;
for(int i=0;i<3;i++)
net_elem.weights2[i]=net_elem.weights2[i]+eeta*Delta*Output*(1-Output)*output[i];
net_elem.bias2=net_elem.bias2+eeta*delta_bias2;
double sum1=0;
for(int i=0;i<3;i++)
sum1=sum1+net_elem.weights1[i]*delta[i];
net_elem.bias1=net_elem.bias1+eeta*sum1;
show_net_elem();
}
void test()
{
cout.precision(15);
double input,Output,output[3];
cout<<"Enter Input:";
cin>>input;
//Propogate forward
double sum=0;
for(int i=0;i<3;i++)
output[i]=sigma(input*net_elem.weights1[i]+net_elem.bias1);
for(int i=0;i<3;i++)
sum=sum+output[i]*net_elem.weights2[i];
Output=sigma(sum+net_elem.bias2);
cout<<"Output="<<Output<<endl;
}
I have tried to run it to emulate the square root function. But the output simply jumps between 0 and 1, alternating.
Main:
int main()
{
net_elem.weights1[0]=(double)(rand()%100+0)/10;
net_elem.weights1[1]=(double)(rand()%100+0)/10;
net_elem.weights1[2]=(double)(rand()%100+0)/10;
net_elem.weights2[0]=(double)(rand()%100+0)/10;
net_elem.weights2[1]=(double)(rand()%100+0)/10;
net_elem.weights2[2]=(double)(rand()%100+0)/10;;
net_elem.bias1=(double)(rand()%100+0)/10;
net_elem.bias2=(double)(rand()%100+0)/10;
double output[n],input[n];
int ch;
for(int i=1;i<n;i++)
{
input[i]=100;
output[i]=sqrt(input[i]);
}
do
{
cout<<endl<<"1. Train"<<endl;
cout<<"2. Test"<<endl;
cout<<"3. Exit"<<endl;
cin>>ch;
switch(ch)
{
case 1:for(int i=1;i<n;i++)
{
train(input[i],output[i]);
}
break;
case 2:test();break;
case 3:break;
default:cout<<"Enter Proper Choice"<<endl;
}
}while(ch!=3);
}
I think you are missing the point of using a neural network. Neural networks don't imitate known functions. They separate areas in an unknown vector space. The XOR problem is often given as an example, because it is the minimal non-linearly separable problem: A simple perceptron is simply a line separating two areas in you problem
In this case, the blue dots can be separated from the red dots using a simple line (the problem is linearly separable). However, in the XOR problem, the dots are situated like this:
Here, a single line (a perceptron) is not enough. However, a multi-layer perceptron (most probably the type of neural network you are using) can use multiple perceptrons, (in this case two) to separate the blue and red dots. In a similar manner, a neural network can separate any space.
However, the XOR problem produces two types of output, and we use a neural network to separate them. On the other hand, x^2 produces a continuous lines of points, so there's nothing to separate. Also, keep in mind that imitating the XOR function is given as an example of such problems. In practice, nobody ever uses a neural network to replace the XOR function. If you want to use a function, just use it, instead of building something that approximates it.
PS: If you still want to emulate the x^2 function for practice, you need regression. What you are doing is classification (since you are using a sigma function in you output). However, for practicing you'd better stick with classification problems. They are by far more common. Also, for such problems try Matlab, or, if you want to write in C++ use some linear algebra library (eg EIGEN 3) to make it easier writing without a thousand for loops.
I am working on a Java project, and I have to compute a multiple linear regression, but I want the gotten parameters to be non-negative. Is there an existing commercial-friendly-licensed library to do such a thing? I've been looking for Non-Negative Least Squares libs, without success.
Well, I could not find any pure java library so I built it myself from the article of [1], wich can be found in [2] and [3]. I give the algorithm:
P, R are the active and the passive sets. t() is transpose
The problem is to solve Ax = b under the condition x>0
P=null
R = {1,2,...,m}
x = 0
w = t(A)*(b-A*x)
while R<>null and max{wi|i in R}>0 do:
j = argmax{wi|i in R}
P = P U {j}
R = R\{j}
s[P] = invert[t(A[P])A[P]]t(A[P])b
while sp<=0 do:
a = -min{xi/(di-xi)|i in P and di<0}
x = x + a*s -x
update(P)
update(R)
sP = invert[t(A[P])A[P]]t(A[P])b
sR = 0
x = s
w = t(A)*(b-A*x)
return x
For the other definitions, I strongly advise to read the papers [2] and [3], which are online (see below for the links ;) )
[1] Lawson, C. L., & Hanson, R. J. (1974). Solving least squares problems (Vol. 161). Englewood Cliffs, NJ: Prentice-hall.
[2] Rasmus Bro et Sijmen De Jong : A fast non-negativity-constrained least squares
algorithm. Journal of chemometrics, 11(5) :393–401, 1997. http://www.researchgate.net/publication/230554373_A_fast_non-negativity-constrained_least_squares_algorithm/file/79e41501a40da0224e.pdf
[3] Donghui Chen et Robert J Plemmons : Nonnegativity constraints in numerical analysis. In Symposium on the Birth of Numerical Analysis, pages 109–140, 2009. http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.157.9203&rep=rep1&type=pdf
You can use Apache Commons Math, making your constraints an additional cost to the objective function. See section 14.4 here: http://commons.apache.org/proper/commons-math/userguide/leastsquares.html
Have your tried Weka? It's Java and under GNU General Public License. It's mainly a GUI-Tool for experiments, but you can use it as a library too. It should have implementations of linear regressions.
As George Foreman pointed out you can use apache commons math.
In particular there is the object OLSMultipleLinearRegression which provides tha methods for performing multiple regression analysis.
Here is some code on how to do it.
OLSMultipleLinearRegression ols = new OLSMultipleLinearRegression();
double[] data = new double[75];
int numberOfObservations = 25;
int numberOfIndependentVariables = 3;
try {
ols.newSampleData(data, numberOfObservations, numberOfIndependentVariables);
} catch (IllegalArgumentException e) {
e.printStackTrace();
return;
}
And here is the whole github project from where you can download a working example on how to use multiple regression in Java : https://github.com/tekrar/MultRegressionInJava
hey guys i want your suggestion that how can change value of two variables without 3rd one. in objective cc.
is there any way so please inform me,
it can be done in any language. x and y are 2 variables and we want to swap them
{
//lets say x , y are 1 ,2
x = x + y; // 1+2 =3
y = x - y; // 3 -2 = 1
x = x -y; // 3-1 = 2;
}
you can use these equation in any language to achieve this
Do you mean exchange the value of two variables, as in the XOR swap algorithm? Unless you're trying to answer a pointless interview question, programming in assembly language, or competing in the IOCCC, don't bother. A good optimizing compiler will probably handle the standard tmp = a; a = b; b = tmp; better than whatever trick you might come up with.
If you are doing one of those things (or are just curious), see the Wikipedia article for more info.
As far as number is concerned you can swap numbers in any language without using the third one whether it's java, objective-C OR C/C++,
For more info
Potential Problem in "Swapping values of two variables without using a third variable"
Since this is explicitly for iPhone, you can use the ARM instruction SWP, but it's almost inconceivable why you'd want to. The complier is much, much better at this kind of optimization. If you just want to avoid the temporary variable in code, write an inline function to handle it. The compiler will optimize it away if it can be done more efficiently.
NSString * first = #"bharath";
NSString * second = #"raj";
first = [NSString stringWithFormat:#"%#%#",first,second];
NSRange needleRange = NSMakeRange(0,
first.length - second.length);
second = [first substringWithRange:needleRange];
first = [first substringFromIndex:second.length];
NSLog(#"first---> %#, Second---> %#",first,second);