Has anyone built a program slicer in Java? - java

I have to build a program slicer in java to slice source code based on a slicing criterion. I see there are a very few libraries out there for this purpose. Notwithstanding, I would like to try this myself. I have read some publications on the topic that include the use of a dependence graph to work out the data and control dependencies in a program. A slicing algorithm can then be used in conjunction with a slicing criterion to generate slices of the java program. Has anyone done this type of thing before? If so, could you perhaps point me in the right direction to get started with this? I have searched and search and cannot figure out where to start, what APIs exist (if any).
An Example would be:
public class Foo {
public void fooBar() {
int x = 10;
int y = 12;
String s = "";
for(int j=0; j<10; j++) {
s += x;
x++;
y += 3;
}
System.out.println("y value " + y);
}
}
If a slicing criterion (13, y) is choosen, where 13 is the last line in the above code, then the result will be
public class Foo {
public void fooBar() {
int y = 12;
for(int j=0; j<10; j++) {
y += 3;
}
}
}
The slicing criterion returns all of the statements that may affect variable 'y' at line 13.

There is very less work in this area. You can reuse code of some open source utility like checkstyle or yasca. Then you can apply your own implementation logic for the slicing.

Late, but maybe useful for others: Wala. WALA includes a slicer, based on context-sensitive tabulation of reachability in the system dependence graph.

Related

JAVA for loop: all except a specified number

I need this for an array, but basically the idea is that a for loop will run, and whatever number you tell it to skip, it won't do. So for(int x=0; x<50; x++) if I want 1-50 except 22, how would I write that?
This would give me the ability to skip a certain number in my array.
Sorry if this is an extremely simple question, I am not too familiar with Java.
Make use of continue, something like this:
for(int x=0; x<50; x++) {
if(x == 22)
continue;
// do work
}
Suggested reading: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/branch.html
public static final void doSkippedIteration(final int[] pArray, final int pSkipIndex) {
for(int i = 0; i < pSkipindex; i++) {
// Do something.
}
for(int i = pSkipIndex + 1; i < pArray.length; i++) {
// Do something.
}
}
You would have to do some basic check to see whether pIndex lies within the confines of the array. This saves you from having to perform a check for every single iteration, but does require you to duplicate your code in this specific example. You could of course avoid this by wrapping the code in a wider control block which handles the two iterations in a cleaner manner.

Finding everything that affects a variable

I'm trying to make a program that will read in a class file and if you give it a variable for example you give it "i" in the following example:
public class Example {
public static void main( String[] args) {
int i = 1;
int j = 5;
int k = 2;
i = i + k;
System.out.println(i);
}
}
Then my program will return
int i = 1;
int k = 2;
i = i + k;
System.out.println(i);
Since these are variables that affect i.
I'm not sure how to do this. So far I've tried using javaparser which takes in the file and finds all the VariableDeclarationExpr using a visitor pattern. However, this won't print out the bottom two cases in the code above.
Can anyone give me any hints to how to find them?
The VariableDeclarationExpr represents only declarations (like in your case int i = 1;). But the other two statements in your code are not declarations. They are assignments (probably AssignmentExpr) and a method call (probably MethodCallExpr). So I would first think about where the variable i can appear and then cover all the cases individually. I hope that helps

How do I know that my neural network is being trained correctly

I've written an Adaline Neural Network. Everything that I have compiles, so I know that there isn't a problem with what I've written, but how do I know that I have to algorithm correct? When I try training the network, my computer just says the application is running and it just goes. After about 2 minutes I just stopped it.
Does training normally take this long (I have 10 parameters and 669 observations)?
Do I just need to let it run longer?
Hear is my train method
public void trainNetwork()
{
int good = 0;
//train until all patterns are good.
while(good < trainingData.size())
{
for(int i=0; i< trainingData.size(); i++)
{
this.setInputNodeValues(trainingData.get(i));
adalineNode.run();
if(nodeList.get(nodeList.size()-1).getValue(Constants.NODE_VALUE) != adalineNode.getValue(Constants.NODE_VALUE))
{
adalineNode.learn();
}
else
{
good++;
}
}
}
}
And here is my learn method
public void learn()
{
Double nodeValue = value.get(Constants.NODE_VALUE);
double nodeError = nodeValue * -2.0;
error.put(Constants.NODE_ERROR, nodeError);
BaseLink link;
int count = inLinks.size();
double delta;
for(int i = 0; i < count; i++)
{
link = inLinks.get(i);
Double learningRate = value.get(Constants.LEARNING_RATE);
Double value = inLinks.get(i).getInValue(Constants.NODE_VALUE);
delta = learningRate * value * nodeError;
inLinks.get(i).updateWeight(delta);
}
}
And here is my run method
public void run()
{
double total = 0;
//find out how many input links there are
int count = inLinks.size();
for(int i = 0; i< count-1; i++)
{
//grab a specific link in sequence
BaseLink specificInLink = inLinks.get(i);
Double weightedValue = specificInLink.weightedInValue(Constants.NODE_VALUE);
total += weightedValue;
}
this.setValue(Constants.NODE_VALUE, this.transferFunction(total));
}
These functions are part of a library that I'm writing. I have the entire thing on Github here. Now that everything is written, I just don't know how I should go about actually testing to make sure that I have the training method written correctly.
I asked a similar question a few months ago.
Ten parameters with 669 observations is not a large data set. So there is probably an issue with your algorithm. There are two things you can do that will make debugging your algorithm much easier:
Print the sum of squared errors at the end of each iteration. This will help you determine if the algorithm is converging (at all), stuck at a local minimum, or just very slowly converging.
Test your code on a simple data set. Pick something easy like a two-dimensional input that you know is linearly separable. Will your algorithm learn a simple AND function of two inputs? If so, will it lean an XOR function (2 inputs, 2 hidden nodes, 2 outputs)?
You should be adding debug/test mode messages to watch if the weights are getting saturated and more converged. It is likely that good < trainingData.size() is not happening.
Based on Double nodeValue = value.get(Constants.NODE_VALUE); I assume NODE_VALUE is of type Double ? If that's the case then this line nodeList.get(nodeList.size()-1).getValue(Constants.NODE_VALUE) != adalineNode.getValue(Constants.NODE_VALUE) may not really converge exactly as it is of type double with lot of other parameters involved in obtaining its value and your convergence relies on it. Typically while training a neural network you stop when the convergence is within an acceptable error limit (not a strict equality like you are trying to check).
Hope this helps

Knapsack Dynamic Programming

this is a typical Knapsack problem requiring dynamic programming and there is no constraint on the supply of items. I've been working on this for my class and I tried to play around with the algorithm for hours and I'm still not getting there.
public static int fitBackPack(int[] W, int[] V, int T){
int[] Opt = new int[T+1];
Opt[0]=0;
for (int i=1; i<=T; i++){
int localMax=0;
int globalMax=0;
for (int j=0; j<W.length; j++){
if (W[j]<=i){
localMax = (T%W[j]<=W[j]) ? V[j] : V[j]+Opt[T-W[j]];
globalMax = (localMax>=globalMax) ? localMax : globalMax;
}
}
Opt[i]=globalMax;
}
//debugging purposes
for (int k=0; k<Opt.length; k++){
System.out.println("Opt["+k+"] = "+Opt[k]);
}
return Opt[T];
}
This method is supposed to take a sorted array of W and V, containing the weight and the value of the item respectively, and an integer T representing the max weight. For my output, everything up until T=21 works, however, after that it just seems to be working like a greedy algorithm, which is completely not what I was hoping for. Any hints will be appreciated, thanks!
Hints:
(x % y <= y) == true
Every now and then a truth table through your conditions with test cases will help you find these.
Better still set up some automated tests for general usage and edge cases.
Since your algorithm is acting like a greedy one, you problem is probably on the calculation of localMax (since greedy algorithms look for the highest local value). By looking at your code, you seem to be getting localMax in the wrong way. Hint, see Math.max() function.

Accessing instance variables from objects in a list

I'm working on a self-assigned project over break, and am running into one major sticking point. This is a basic line-recognition program in Java.
I have a Points class which creates the Point from the ordered pairs & sends it to the Line class for slope & intercept calculation. The results are sent back to the Points class which deposits the results into the ArrayList linelist. There are three parts to each Line object: the slope & intercept integers and the Point from which they were calculated from.
From a loop, how can I access the slope & intercept variables from each object in the linelist for comparison? Since I don't want to compare the points, just the slope & intercept, the equals() method is not what I need.
It sounds like you want something like this:
class Point {
final int x;
final int y;
Point(int x, int y) { this.x = x; this.y = y; }
}
class Line {
final int slope;
final int intercept;
Line(Point p1, Point p2) {
this.slope = ...;
this.intercept = ...;
}
}
class Points {
public void doIt(ArrayList<Point> points) {
ArrayList<Line> lines = new ArrayList<Line>();
for (int i = 0; i < points.size(); i++) {
for (int j = i + 1; j < points.size(); j++) {
lines.add(new Line(points.get(i), points.get(j));
}
}
for (int i = 0; i < lines.size(); i++) {
for (int j = i + 1; j < lines.size(); j++) {
Line line1 = lines.get(i);
Line line2 = lines.get(j);
if (line1.slope == line2.slope && line1.intercept == line2.intercept) {
// blah blah blah
}
}
}
}
}
(For the peanut gallery, yes there is scope for micro-optimization. But no, it isn't worth the effort unless you've profiled the program and found there to be a real and significant bottleneck.)
[For a more elegant and scalable solution, override the equals(Object) (and hashcode()) methods on Line class and replace the lines list with a TreeSet. This will reduce O(N**2) comparisons to O(NlogN) comparisons. But that's overkill for a basic programming exercise.]
From a loop, how can I access the slope & intercept variables from each object in the linelist for comparison?
Just add another loop over the same list inside the loop and do the comparison in there.
You could have your Line object implement the Comparable interface. You could then put the comparison logic within the Line class in the compareTo method. The logic there will test whether the slope and the intercept match, and if so return 0. Other results could return 1 or -1 to enforce ordering, if you want.
Obviously, you don't need to implement this interface to effect your desired results. However, as this is homework, doing so will allow you to play around with some features of the JDK, like using sorted Lists, etc. With a sorted list, for example, you could obviate the need for a nested loop, as you would only need to compare the object in question against one you just removed from the Iterator in the previous iteration to see if you need to add it to an existing linelist or start a new one.

Categories