id
stringlengths 36
36
| text
stringlengths 1
1.25M
|
---|---|
73f97b5e-e571-452e-89cb-90bebf8a0e1c | public static void main (String[] args) throws IOException {
long startTime = System.currentTimeMillis();
if(args.length == 2){
trainingDirectory = args[0];
testingDirectory = args[1];
} else if (args.length == 0){
//trainingDirectory = "D:/cs571data/data/train";
//testingDirectory = "D:/cs571data/data/test";
trainingDirectory = "/aut/proj/ir/eugene/Data/CS571/project2/data/train";
testingDirectory = "/aut/proj/ir/eugene/Data/CS571/project2/data/test";
} else {
System.err.println("Argument Wrong, please provide valid "
+ "[TrainingDirectory] [TestingDirectory]");
}
try{
TrainCRF trainer = new TrainCRF(trainingDirectory, testingDirectory);
} catch (IOException e) {
System.err.println("File Not Found");
}
long endTime = System.currentTimeMillis();
long totalTime = endTime - startTime;
System.out.println();
System.out.println("Total time : " + totalTime + "mSec");
} |
5a880465-c18c-4a58-b9fd-64d4e1d4e804 | public SimpleLabelNERdata2TokenSequence ()
{
super (null, new LabelAlphabet());
} |
d346105f-baf2-4bf6-831d-61a8bac9fc32 | public SimpleLabelNERdata2TokenSequence (boolean extraFeatures)
{
super (null, new LabelAlphabet());
if (!extraFeatures) {
doDigitCollapses = doConjunctions = doSpelling = doPhrases = doTags = false;
doDowncasing = true;
}
} |
f60cfb6d-8bcb-4c0f-af1b-87a1625fcb3c | public Instance pipe (Instance carrier)
{
String sentenceLines = carrier.getData().toString();
String[] tokens = sentenceLines.split ("\n");
TokenSequence data = new TokenSequence (tokens.length);
LabelSequence target = new LabelSequence ((LabelAlphabet)getTargetAlphabet(), tokens.length);
boolean [][] ending = new boolean[3][endings.length];
boolean [][] endingp1 = new boolean[3][endings.length];
boolean [][] endingp2 = new boolean[3][endings.length];
StringBuffer source = saveSource ? new StringBuffer() : null;
String prevLabel = "NOLABEL";
Pattern ipattern = Pattern.compile ("I-.*");
String sentenceNum, wordNum, word, POStag, phrase, label;
for (int i = 0; i < tokens.length; i++) {
if (tokens[i].length() != 0) {
String[] features = tokens[i].split ("\t");
if (features.length != 7){
//throw new IllegalStateException ("Line \""+tokens[i]+"\" doesn't have 7 elements");
continue;
}
//sentenceNum = features[0];
//wordNum = features[1];
word = features[2];
POStag = features[3];
phrase = features[5];
label = labelSimplifier(features[6]);
//System.out.println(word + " - " + label);
} else {
//sentenceNum = "-<S>-";
//wordNum = "-<S>-";
word = "-<S>-";
POStag = "-<S>-";
phrase = "-<S>-";
label = "O";
}
// Transformations
if (doDigitCollapses) {
if (word.matches ("19\\d\\d"))
word = "<YEAR>";
else if (word.matches ("19\\d\\ds"))
word = "<YEARDECADE>";
else if (word.matches ("19\\d\\d-\\d+"))
word = "<YEARSPAN>";
else if (word.matches ("\\d+\\\\/\\d"))
word = "<FRACTION>";
else if (word.matches ("\\d[\\d,\\.]*"))
word = "<DIGITS>";
else if (word.matches ("19\\d\\d-\\d\\d-\\d--d"))
word = "<DATELINEDATE>";
else if (word.matches ("19\\d\\d-\\d\\d-\\d\\d"))
word = "<DATELINEDATE>";
else if (word.matches (".*-led"))
word = "<LED>";
else if (word.matches (".*-sponsored"))
word = "<LED>";
}
if (doDowncasing)
word = word.toLowerCase();
Token token = new Token (word);
// Word and tag unigram at current time
if (doSpelling) {
for (int j = 0; j < endings.length; j++) {
ending[2][j] = ending[1][j];
ending[1][j] = ending[0][j];
ending[0][j] = endingPatterns[j].matcher(word).matches();
if (ending[0][j]) token.setFeatureValue (endingNames[0][0][j], 1);
}
}
if (doTags) {
token.setFeatureValue ("T="+POStag, 1);
}
if (doPhrases) {
token.setFeatureValue ("P="+phrase, 1);
}
//************//
boolean addLabelPrefix = false;
if (addLabelPrefix) {
// Change so each segment always begins with a "B-",
// even if previous token did not have this label.
String oldLabel = label;
if (ipattern.matcher(label).matches ()
&& (prevLabel.length() < 3 // prevLabel is "O"
|| !prevLabel.substring(2).equals (label.substring(2)))) {
label = "B" + oldLabel.substring(1);
}
prevLabel = oldLabel;
}
// Append
data.add (token);
//target.add (bigramLabel);
target.add (label);
//System.out.print (label + ' ');
if (saveSource) {
source.append (word); source.append (" ");
//source.append (bigramLabel); source.append ("\n");
source.append (label); source.append ("\n");
}
}
//System.out.println ("NERED");
carrier.setData(data);
carrier.setTarget(target);
if (saveSource)
carrier.setSource(source);
return carrier;
} |
95043c1c-3a82-43f7-be57-dd8a4b7f32f0 | public static String labelSimplifier(String label){
if(label.toLowerCase().contains("Peo".toLowerCase())) {
return "PER";
} else if(label.toLowerCase().contains("Loc".toLowerCase())) {
return "LOC";
} else if(label.toLowerCase().contains("Org".toLowerCase())) {
return "ORG";
} else {
return "O";
}
} |
885185d1-8524-4d05-beda-14ebc85759b9 | public ImprovedSimpleLabelNERdata2TokenSequence ()
{
super (null, new LabelAlphabet());
} |
075f04d6-17bc-41db-b676-ee626b83a79e | public ImprovedSimpleLabelNERdata2TokenSequence (boolean extraFeatures)
{
super (null, new LabelAlphabet());
if (!extraFeatures) {
doDigitCollapses = doConjunctions = doSpelling = doPhrases = doTags = false;
doDowncasing = true;
}
} |
0252dced-26d1-41c2-9743-e21584414bf5 | public Instance pipe (Instance carrier)
{
String sentenceLines = carrier.getData().toString();
String[] tokens = sentenceLines.split ("\n");
TokenSequence data = new TokenSequence (tokens.length);
LabelSequence target = new LabelSequence ((LabelAlphabet)getTargetAlphabet(), tokens.length);
boolean [][] ending = new boolean[3][endings.length];
boolean [][] endingp1 = new boolean[3][endings.length];
boolean [][] endingp2 = new boolean[3][endings.length];
StringBuffer source = saveSource ? new StringBuffer() : null;
String prevWord = "<Start>";
String prevPOStag = "<Start>";
String prevPhrase = "<Start>";
String prevLabel = "O";
String word = "<Start>";
String POStag = "<Start>";
String phrase = "<Start>";
String label = "O";
String nextWord, nextPOStag, nextPhrase, nextLabel;
Pattern ipattern = Pattern.compile ("I-.*");
for (int i = 0; i < tokens.length; i++) {
if (tokens[i].length() != 0) {
String[] features = tokens[i].split ("\t");
if (features.length != 7){
//throw new IllegalStateException ("Line \""+tokens[i]+"\" doesn't have 7 elements");
continue;
}
//sentenceNum = features[0];
//wordNum = features[1];
nextWord = features[2];
nextPOStag = features[3];
nextPhrase = features[5];
nextLabel = labelSimplifier(features[6]);
//System.out.println(word + " - " + label);
} else {
//sentenceNum = "-<S>-";
//wordNum = "-<S>-";
nextWord = "<Start>";
nextPOStag = "<Start>";
nextPhrase = "<Start>";
nextLabel = "O";
}
// Transformations
if (doDigitCollapses) {
if (word.matches ("19\\d\\d"))
word = "<YEAR>";
else if (word.matches ("19\\d\\ds"))
word = "<YEARDECADE>";
else if (word.matches ("19\\d\\d-\\d+"))
word = "<YEARSPAN>";
else if (word.matches ("\\d+\\\\/\\d"))
word = "<FRACTION>";
else if (word.matches ("\\d[\\d,\\.]*"))
word = "<DIGITS>";
else if (word.matches ("19\\d\\d-\\d\\d-\\d--d"))
word = "<DATELINEDATE>";
else if (word.matches ("19\\d\\d-\\d\\d-\\d\\d"))
word = "<DATELINEDATE>";
else if (word.matches (".*-led"))
word = "<LED>";
else if (word.matches (".*-sponsored"))
word = "<LED>";
}
if (doDowncasing)
word = word.toLowerCase();
Token token = new Token (word);
// Word and tag unigram at current time
if (doSpelling) {
for (int j = 0; j < endings.length; j++) {
ending[2][j] = ending[1][j];
ending[1][j] = ending[0][j];
ending[0][j] = endingPatterns[j].matcher(word).matches();
if (ending[0][j]) token.setFeatureValue (endingNames[0][0][j], 1);
}
}
if (doTags) {
token.setFeatureValue ("T="+POStag, 1);
}
if (doPhrases) {
token.setFeatureValue ("P="+phrase, 1);
}
boolean addLabelPrefix = false;
if (addLabelPrefix) {
// Change so each segment always begins with a "B-",
// even if previous token did not have this label.
String oldLabel = label;
if (ipattern.matcher(label).matches ()
&& (prevLabel.length() < 3 // prevLabel is "O"
|| !prevLabel.substring(2).equals (label.substring(2)))) {
label = "B" + oldLabel.substring(1);
}
prevLabel = oldLabel;
}
boolean addPreviousLabel = true;
if(addPreviousLabel){
token.setFeatureValue ("PL="+prevLabel,1);
}
boolean addNextLabel = true;
if(addNextLabel){
token.setFeatureValue ("NL="+ nextLabel,1);
}
boolean addPrefixWord = true;
if(addPrefixWord){
token.setFeatureValue ("PF="+prevWord,1);
}
boolean addSuffixWord = true;
if(addSuffixWord){
token.setFeatureValue ("SF="+ nextWord,1);
}
// Append
data.add (token);
//target.add (bigramLabel);
target.add (label);
//System.out.print (label + ' ');
if (saveSource) {
source.append (word); source.append (" ");
//source.append (bigramLabel); source.append ("\n");
source.append (label); source.append ("\n");
}
prevWord = word;
prevLabel = label;
prevPOStag = POStag;
prevPhrase = phrase;
word = nextWord;
label = nextLabel;
POStag = nextPOStag;
phrase = nextPhrase;
}
//System.out.println ("NERED");
carrier.setData(data);
carrier.setTarget(target);
if (saveSource)
carrier.setSource(source);
return carrier;
} |
b8441233-4d00-48db-ad6e-9646c17568f6 | public static String labelSimplifier(String label){
if(label.toLowerCase().contains("Peo".toLowerCase())) {
return "PER";
} else if(label.toLowerCase().contains("Loc".toLowerCase())) {
return "LOC";
} else if(label.toLowerCase().contains("Org".toLowerCase())) {
return "ORG";
} else {
return "O";
}
} |
65c67975-cd96-4210-9174-1d818132e545 | public static void main (String[] args) throws IOException {
String address = "F:/cs571data/project2/data/train";
File[] files = new File(address).listFiles();
for (File file : files){
Scanner sc = new Scanner(file);
//loop thru lines
while (sc.hasNext()) {
String line = sc.nextLine();
String[] tokens = line.split ("\n");
//loop thru tokens
for (int i = 0; i < tokens.length; i++) {
if (tokens[i].length() != 0) {
String[] tokenizedLine = tokens[i].split ("\t");
if(tokenizedLine.length == 7){
String Label = tokenizedLine[6];
if(labelSet.contains(Label)){
continue;
}else{
labelSet.add(Label);
}
} else {
continue;
}
}
}//end loop thru tokens
}//end loop thru lines
}//end loop thru files
System.out.println(labelSet.toString());
} |
dc8b5000-5df6-453c-80b9-c38280901604 | public TrainDetailedCRF(String trainingFileFolder, String testingFileFolder) throws IOException {
ArrayList<Pipe> pipeList = new ArrayList<Pipe>();
// Construct pipes
pipeList.add(new Input2CharSequence("UTF-8"));
pipeList.add(new ImprovedDetailedLabelNERdata2TokenSequence(true)); // true to extract feature
pipeList.add(new TokenSequence2FeatureVectorSequence());
//////////////////////////////////////////////////
Pipe pipe = new SerialPipes(pipeList);
InstanceList trainingInstances = new InstanceList(pipe);
InstanceList testingInstances = new InstanceList(pipe);
File[] trainingFiles = new File(trainingFileFolder).listFiles();
for(File trainingfile : trainingFiles){
LineGroupIterator it = new LineGroupIterator(new BufferedReader(new InputStreamReader(
new FileInputStream(trainingfile))), Pattern.compile("^\\s*$"), true);
trainingInstances.addThruPipe(it);
}
System.out.println("Training loaded");
File[] testingFiles = new File(testingFileFolder).listFiles();
for(File testingfile : testingFiles){
testingInstances.addThruPipe(new LineGroupIterator(new BufferedReader(new InputStreamReader(
new FileInputStream(testingfile))), Pattern.compile("^\\s*$"), true));
}
System.out.println("Testing loaded");
System.out.println();
CRF crf = new CRF(pipe, null);
// Taking 20%, 40%, 60%, 80%, 100% of Training Data as input
InstanceList[] ilists = trainingInstances.split(new Randoms(), new double[] {1.0, 0.0, 0.0});
// Better result use All Label Connections
// Higher efficiency use less Label Connections
// Choose one :
// crf.addFullyConnectedStatesForLabels();
// or
crf.addStatesForLabelsConnectedAsIn(ilists[0]);
// or
// crf.addStatesForThreeQuarterLabelsConnectedAsIn(ilists[0]);
// or
// crf.addStatesForBiLabelsConnectedAsIn (ilists[0]);
// or
// crf.addStatesForHalfLabelsConnectedAsIn (ilists[0]);
// crf.addStartState(); // Use Start State
CRFTrainerByThreadedLabelLikelihood trainer =
new CRFTrainerByThreadedLabelLikelihood(crf, 6);
trainer.setGaussianPriorVariance (100.0);
// CRFTrainerByStochasticGradient trainer =
// new CRFTrainerByStochasticGradient(crf, 1.0);
// CRFTrainerByL1LabelLikelihood trainer =
// new CRFTrainerByL1LabelLikelihood(crf, 0.75);
// CRFTrainerByValueGradients trainer =
// new CRFTrainerByValueGradients(crf, null);
// DON'T UNDERSTAND, need to check the source
trainer.addEvaluator(new PerClassAccuracyEvaluator(testingInstances, "testing"));
trainer.train(ilists[0]);
trainer.shutdown();
} |
81c8ea8f-f172-43e4-b0ad-25256606bdc8 | public ImprovedDetailedLabelNERdata2TokenSequence ()
{
super (null, new LabelAlphabet());
} |
d4866958-fc31-4ef2-81a5-253bfbfb8d57 | public ImprovedDetailedLabelNERdata2TokenSequence (boolean extraFeatures)
{
super (null, new LabelAlphabet());
if (!extraFeatures) {
doDigitCollapses = doConjunctions = doSpelling = doPhrases = doTags = false;
doDowncasing = true;
}
} |
4033195d-66b3-46c8-a7a3-ae90e49ecb6d | public Instance pipe (Instance carrier)
{
String sentenceLines = carrier.getData().toString();
String[] tokens = sentenceLines.split ("\n");
TokenSequence data = new TokenSequence (tokens.length);
LabelSequence target = new LabelSequence ((LabelAlphabet)getTargetAlphabet(), tokens.length);
boolean [][] ending = new boolean[3][endings.length];
boolean [][] endingp1 = new boolean[3][endings.length];
boolean [][] endingp2 = new boolean[3][endings.length];
StringBuffer source = saveSource ? new StringBuffer() : null;
String prevWord = "<Start>";
String prevPOStag = "<Start>";
String prevPhrase = "<Start>";
String prevLabel = "O";
String word = "<Start>";
String POStag = "<Start>";
String phrase = "<Start>";
String label = "O";
String nextWord, nextPOStag, nextPhrase, nextLabel;
Pattern ipattern = Pattern.compile ("I-.*");
for (int i = 0; i < tokens.length; i++) {
if (tokens[i].length() != 0) {
String[] features = tokens[i].split ("\t");
if (features.length != 7){
//throw new IllegalStateException ("Line \""+tokens[i]+"\" doesn't have 7 elements");
continue;
}
//sentenceNum = features[0];
//wordNum = features[1];
nextWord = features[2];
nextPOStag = features[3];
nextPhrase = features[5];
nextLabel = labelPrefixRemover(features[6]);
//System.out.println(word + " - " + label);
} else {
//sentenceNum = "-<S>-";
//wordNum = "-<S>-";
nextWord = "<Start>";
nextPOStag = "<Start>";
nextPhrase = "<Start>";
nextLabel = "O";
}
// Transformations
if (doDigitCollapses) {
if (word.matches ("19\\d\\d"))
word = "<YEAR>";
else if (word.matches ("19\\d\\ds"))
word = "<YEARDECADE>";
else if (word.matches ("19\\d\\d-\\d+"))
word = "<YEARSPAN>";
else if (word.matches ("\\d+\\\\/\\d"))
word = "<FRACTION>";
else if (word.matches ("\\d[\\d,\\.]*"))
word = "<DIGITS>";
else if (word.matches ("19\\d\\d-\\d\\d-\\d--d"))
word = "<DATELINEDATE>";
else if (word.matches ("19\\d\\d-\\d\\d-\\d\\d"))
word = "<DATELINEDATE>";
else if (word.matches (".*-led"))
word = "<LED>";
else if (word.matches (".*-sponsored"))
word = "<LED>";
}
if (doDowncasing)
word = word.toLowerCase();
Token token = new Token (word);
// Word and tag unigram at current time
if (doSpelling) {
for (int j = 0; j < endings.length; j++) {
ending[2][j] = ending[1][j];
ending[1][j] = ending[0][j];
ending[0][j] = endingPatterns[j].matcher(word).matches();
if (ending[0][j]) token.setFeatureValue (endingNames[0][0][j], 1);
}
}
if (doTags) {
token.setFeatureValue ("T="+POStag, 1);
}
if (doPhrases) {
token.setFeatureValue ("P="+phrase, 1);
}
//************//
boolean addLabelPrefix = false;
if (addLabelPrefix) {
// Change so each segment always begins with a "B-",
// even if previous token did not have this label.
String oldLabel = label;
if (ipattern.matcher(label).matches ()
&& (prevLabel.length() < 3 // prevLabel is "O"
|| !prevLabel.substring(2).equals (label.substring(2)))) {
label = "B" + oldLabel.substring(1);
}
prevLabel = oldLabel;
}
boolean addPreviousLabel = true;
if(addPreviousLabel){
token.setFeatureValue ("PL="+prevLabel,1);
}
boolean addNextLabel = true;
if(addNextLabel){
token.setFeatureValue ("NL="+ nextLabel,1);
}
boolean addPrefixWord = true;
if(addPrefixWord){
token.setFeatureValue ("PF="+prevWord,1);
}
boolean addSuffixWord = true;
if(addSuffixWord){
token.setFeatureValue ("SF="+ nextWord,1);
}
// Append
data.add (token);
//target.add (bigramLabel);
target.add (label);
//System.out.print (label + ' ');
if (saveSource) {
source.append (word); source.append (" ");
//source.append (bigramLabel); source.append ("\n");
source.append (label); source.append ("\n");
}
prevWord = word;
prevLabel = label;
prevPOStag = POStag;
prevPhrase = phrase;
word = nextWord;
label = nextLabel;
POStag = nextPOStag;
phrase = nextPhrase;
}
//System.out.println ("NERED");
carrier.setData(data);
carrier.setTarget(target);
if (saveSource)
carrier.setSource(source);
return carrier;
} |
05a9ee38-8ace-48ab-a441-d2172b97d119 | public static String labelPrefixRemover(String label){
String newLabel = "O";
if(label.contains("B-")) {
newLabel = label.replace("B-", "");
} else if(label.contains("I-")) {
newLabel = label.replace("I-", "");
}
if(newLabel.contains("Peo")) {
return "PER";
} else if(newLabel.contains("Loc")) {
return "LOC";
} else if(newLabel.contains("Org")) {
return newLabel;
} else if(newLabel.equals("O")){
return newLabel;
} else {
return "MISC";
}
} |
e2156683-03c9-4b7d-98c6-38d38db0ed5a | public static void main (String[] args) throws IOException {
long startTime = System.currentTimeMillis();
if(args.length == 2){
trainingDirectory = args[0];
testingDirectory = args[1];
} else if (args.length == 0){
//trainingDirectory = "D:/cs571data/data/train";
//testingDirectory = "D:/cs571data/data/test";
trainingDirectory = "/aut/proj/ir/eugene/Data/CS571/project2/data/train";
testingDirectory = "/aut/proj/ir/eugene/Data/CS571/project2/data/test";
} else {
System.err.println("Argument Wrong, please provide valid "
+ "[TrainingDirectory] [TestingDirectory]");
}
try{
TrainDetailedCRF trainer = new TrainDetailedCRF(trainingDirectory, testingDirectory);
} catch (IOException e) {
System.err.println("File Not Found");
}
long endTime = System.currentTimeMillis();
long totalTime = endTime - startTime;
System.out.println();
System.out.println("Total time : " + totalTime + "mSec");
} |
3a2a30a6-275f-4a5b-9f5e-d1579f67a4b0 | public String getMsg(){
return "chirag rrrr";
} |
cfdebf68-0361-4014-8188-cb3d946fe6c0 | public void test(){
} |
5d0c5672-56fe-43c0-9691-2ef25ee150ea | public DecryptionCezar(String text, int k) {
String input = text;
StringBuilder dec = new StringBuilder();
for (int i = 0; i < input.length(); ++i) {
char c = input.charAt(i);
if (isEnglish(c)) {
int x = (findInEnglish(c) - k + nEng) % nEng;
if (Character.isUpperCase(c)) {
dec.append(engslish[x]);
} else {
dec.append(Character.toLowerCase(engslish[x]));
}
continue;
}
if (isRussian(c)) {
int x = (findInRussian(c) - k + nRus) % nRus;
if (Character.isUpperCase(c)) {
dec.append(russian[x]);
} else {
dec.append(Character.toLowerCase(russian[x]));
}
continue;
}
if (!isEnglish(c) && !isRussian(c)) {
dec.append(c);
}
}
output = dec.toString();
} |
ebc32396-2d66-4d7a-93ea-1bba2cdd6f15 | public DecryptionCezar(EncryptCezar enc) {
int k = enc.getK();
String input = enc.getEncText();
DecryptionCezar dec = new DecryptionCezar(input, k);
output = dec.getDecText();
} |
6e6c2774-8209-4c5b-85d0-6f864f631706 | public String getDecText() {
return output;
} |
c58ad490-a729-44e8-ac3f-596ad21d4fa4 | public EncryptCezar(String text, int k) {
this.k = k;
String input = text;
StringBuilder output = new StringBuilder();
for (int i = 0; i < input.length(); ++i) {
char c = input.charAt(i);
if (isEnglish(c)) {
int y = (findInEnglish(c) + k) % nEng;
if (Character.isUpperCase(c)) {
output.append(engslish[y]);
} else {
output.append(Character.toLowerCase(engslish[y]));
}
continue;
}
if (isRussian(c)) {
int y = (findInRussian(c) + k) % nRus;
if (Character.isUpperCase(c)) {
output.append(russian[y]);
} else {
output.append(Character.toLowerCase(russian[y]));
}
continue;
}
if (!isEnglish(c) && !isRussian(c)) {
output.append(c);
}
}
this.output = output.toString();
} |
6947aa3e-0cc4-4139-b434-b4dd2261c7cb | public String getEncText() {
return this.output;
} |
95fdd06e-1456-4e72-98a1-e3282f304f51 | public int getK() {
return this.k;
} |
59b9a531-8656-4e2a-a0a8-b6a484490e84 | public String getVersion() {
return version;
} |
b7001a8e-ad10-46a5-bdc4-d6f83706afd7 | public int getSize(){
return size;
} |
8241d7c2-5b12-4df9-b941-ad598a0b9523 | CONST(String str){
version = str;
} |
209d6f7a-3e00-470f-8091-cb9f472c3b59 | CONST(int i){
size = i;
} |
6ee577f8-ede2-43e7-a80b-9dd9d431558d | public static void main(String[] args){
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
while(true){
System.out.println("Please enter a command ('help' provides help):");
System.out.print(">> ");
String cmd;
try{
cmd = br.readLine();
switch(cmd.toLowerCase()){
case "exit":
exit();
break;
case "help":
printHelp();
break;
default:
processCommandFurther(cmd);
}
}catch(IOException e){
e.printStackTrace();
}
}
} |
cd6e20f1-bfd4-438c-9094-8fa8d1f1ec8c | private static void processCommandFurther(String cmd){
if(cmd.startsWith("mst -r")){ // random mode
String[] params = cmd.split("\\s+");
if(params.length < 4){
System.out.println("ERROR: Not enough params given. Syntax is 'mst -r n d'. Please try again.\n");
} else{
int numVertices = Integer.parseInt(params[2]);
double density = Double.parseDouble(params[3])/100;
if(density < 0.01){
System.out.println("Please specify a density in percentage, e.g. for a graph with density of 50%, please enter 50\n");
} else{
processRandomMode(numVertices, density);
}
}
} else if(cmd.startsWith("mst -s")){ // file input mode, simple heap scheme
Graph graph = createGraphFromFile(cmd);
List<Edge> generatedMST = MSTGenerator.generateMST(new SimpleSchemeMSTGenerator(), graph);
printTimeAndCost(MSTGenerator.getRuntime(), generatedMST);
printEdges(generatedMST);
} else if(cmd.startsWith("mst -f")){ // file input mode, f-heap scheme
Graph graph = createGraphFromFile(cmd);
List<Edge> generatedMST = MSTGenerator.generateMST(new FHeapSchemeMSTGenerator(), graph);
printTimeAndCost(MSTGenerator.getRuntime(), generatedMST);
printEdges(generatedMST);
} else if("runexperiment".equals(cmd)){
runRandomizedExperiment();
} else{
System.out.println("Unrecognized command; please try again.\n");
}
} |
250c8812-544c-402d-97b8-82228648ae05 | private static void processRandomMode(int numVertices, double density){
Graph graph = GraphGenerator.generateGraph(numVertices, density);
System.out.println("Graph size = "+numVertices+", density = "+density);
System.out.println();
System.out.println("Running simple scheme");
System.out.println("---------------------");
List<Edge> generatedMST = MSTGenerator.generateMST(new SimpleSchemeMSTGenerator(), graph);
printTimeAndCost(MSTGenerator.getRuntime(), generatedMST);
System.out.println("Running f-heap scheme");
System.out.println("---------------------");
generatedMST = MSTGenerator.generateMST(new FHeapSchemeMSTGenerator(), graph);
printTimeAndCost(MSTGenerator.getRuntime(), generatedMST);
} |
05fc5b8f-bfc5-4413-a9a8-1bfea4dda300 | private static void printTimeAndCost(long runtime, List<Edge> generatedMST){
System.out.format("Time taken:\t\t%d min, %d sec (%d millisec)\n",
TimeUnit.MILLISECONDS.toMinutes(runtime),
TimeUnit.MILLISECONDS.toSeconds(runtime) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(runtime)),
runtime
);
printTotalCostOfMST(generatedMST);
System.out.println();
} |
db27ee7d-83d3-4567-ad22-b4c73867889d | private static void printTotalCostOfMST(List<Edge> generatedMST){
int totalCost = 0;
for(Edge MSTEdge: generatedMST){
totalCost += MSTEdge.getCost();
}
System.out.println("Total cost of MST:\t"+totalCost);
} |
39583852-352b-44ef-a56e-a956bcaefceb | private static void printEdges(List<Edge> generatedMST){
System.out.println("Edges in MST:");
for(Edge MSTEdge: generatedMST){
System.out.println(MSTEdge.getStart()+"\t"+MSTEdge.getFinish()+"\t"+MSTEdge.getCost());
}
System.out.println();
} |
cd2507a5-d339-4d32-b973-b6b166849a55 | private static Graph createGraphFromFile(String cmd){
String[] params = cmd.split("\\s+");
String fileName = params[2];
BufferedReader br;
Graph graph = null;
try{
br = new BufferedReader(new FileReader(fileName));
String line = br.readLine();
String[] values = line.split("\\s+");
int numVertices = Integer.parseInt(values[0]);
int numEdges = Integer.parseInt(values[1]);
System.out.println("Graph size = "+numVertices+", number of edges = "+numEdges);
graph = new Graph(numVertices, 0); //density is ignored since we're going to manually add the edges
while ((line = br.readLine()) != null) {
values = line.split("\\s+");
int startNode = Integer.parseInt(values[0]);
int endNode = Integer.parseInt(values[1]);
int cost = Integer.parseInt(values[2]);
graph.getAdjList().get(startNode).add(new AdjListNode(endNode, new Edge(startNode, endNode, cost, false)));
graph.getAdjList().get(endNode).add(new AdjListNode(startNode, new Edge(endNode, startNode, cost, false)));
}
br.close();
} catch(FileNotFoundException e){
System.out.format("ERROR: File %s not found.\n", fileName);
} catch(IOException e){
System.out.format("ERROR: IO error reading from file %s.\n", fileName);
}
return graph;
} |
ad024736-4ebd-4bd9-9c04-e1b632b348a2 | public static void runRandomizedExperiment(){
final int NUMRUNS = 5;
final int[] numVerticesArray = {1000, 3000, 5000};
final int[] densityArray = {10, 20, 30, 40, 50, 60, 70, 80, 90, 100};
for(int numVertices: numVerticesArray){
for(int density: densityArray){
long simpleSchemeRuntime = 0;
long fHeapSchemeRuntime = 0;
for(int run = 0; run < NUMRUNS; run++){
Graph graph = GraphGenerator.generateGraph(numVertices, density/100.0);
MSTGenerator.generateMST(new SimpleSchemeMSTGenerator(), graph);
simpleSchemeRuntime += MSTGenerator.getRuntime();
MSTGenerator.generateMST(new FHeapSchemeMSTGenerator(), graph);
fHeapSchemeRuntime += MSTGenerator.getRuntime();
}
simpleSchemeRuntime = simpleSchemeRuntime / NUMRUNS;
fHeapSchemeRuntime = fHeapSchemeRuntime / NUMRUNS;
System.out.format("%d, %d, %d, %d\n",
numVertices,
density,
simpleSchemeRuntime,
fHeapSchemeRuntime);
}
}
} |
7ed4eb72-133f-44e3-bf1f-78576d194b07 | private static void exit(){
System.exit(0);
} |
7952ea6a-84e3-4a52-9d39-4de9a0e78f50 | private static void printHelp(){
System.out.println("Available commands:");
System.out.println("'help' \t: Prints this message");
System.out.println("'mst -r n d' \t: Runs Prim's algorithm using both simple and f-heap schemes on a graph of size n and density d specified in %");
System.out.println(" \t Prints time taken by both schemes");
System.out.println("'mst -s filename'\t: Runs Prim's algorithm using the simple scheme on a graph initialized from file 'filename'");
System.out.println("'mst -f filename'\t: Runs Prim's algorithm using the f-heap scheme on a graph initialized from file 'filename'");
System.out.println("'runexperiment' \t: Runs the randomized mode experiment outlined in the project description");
System.out.println("'exit' \t: Quits this program");
System.out.println();
} |
0529ae69-804b-48a8-b697-172a5a373436 | public List<Edge> generateMST(Graph graph); |
e61222a8-2f08-4e73-b6a1-0922200fe7b9 | public static Graph generateGraph(int numVertices, double density){
Graph graph = null;
while(notConnected(graph = createAndPopulateGraph(numVertices, density)));
return graph;
} |
7383002d-9949-456a-8cdf-6dc0e8ded007 | private static Graph createAndPopulateGraph(int numVertices, double density){
if(DEBUG)
return createTestGraph(numVertices);
return uniformSpanningTreeApproach(numVertices, density);
} |
eaeda0aa-85b2-4d8e-ad3a-206a111c6cc0 | private static boolean notConnected(Graph graph){
int startDFSAt = graph.selectARandomNode();
HashSet<Integer> visitedNodes = new HashSet<Integer>();
visitedNodes.add(startDFSAt);
runDFSFromNode(startDFSAt, visitedNodes, graph);
if(visitedNodes.size() == graph.getNumVertices())
return false;
return true;
} |
70a9665e-60aa-4527-bdad-5f64f41f11c7 | private static void runDFSFromNode(Integer startNode, HashSet<Integer> visitedNodes, Graph graph){
for(AdjListNode node: graph.getAdjList().get(startNode)){
if(!visitedNodes.contains(node.getTargetNode())){
visitedNodes.add(node.getTargetNode());
runDFSFromNode(node.getTargetNode(), visitedNodes, graph);
}
}
} |
c70c924c-282d-46e5-b118-7900e733a45a | private static Graph uniformSpanningTreeApproach(int numVertices, double density){
Graph graph = new Graph(numVertices, density);
HashSet<Integer> visitedNodes = new HashSet<Integer>();
int[] firstIncidentEdges = createIncidentEdgeArray(numVertices);
int startNode = (int) (Math.random() * numVertices);
int nextNode = startNode;
int numEdgesAdded = 0;
visitedNodes.add(startNode);
firstIncidentEdges[startNode] = startNode;
while(visitedNodes.size() < numVertices){
while((nextNode = (int) (Math.random() * numVertices)) == startNode); // no self-connections!
if(!graph.getAdjList().get(startNode).contains(new AdjListNode(nextNode, null))){
int cost = ((int)(Math.random() * MAX_EDGE_COST))+1;
graph.getAdjList().get(startNode).add(new AdjListNode(nextNode, new Edge(startNode, nextNode, cost, false))); //undirected graph; symmetrical connections
graph.getAdjList().get(nextNode).add(new AdjListNode(startNode, new Edge(nextNode, startNode, cost, false))); //undirected graph; symmetrical connections
visitedNodes.add(nextNode);
numEdgesAdded = numEdgesAdded + 2;
if(firstIncidentEdges[nextNode] == SENTINEL){
firstIncidentEdges[nextNode] = startNode;
}
startNode = nextNode;
}
}
if(numEdgesAdded < graph.getNumEdges()){ // we don't have enough edges, add more randomly, creating cycles
while(numEdgesAdded < graph.getNumEdges()){
startNode = (int) (Math.random() * numVertices);
while((nextNode = (int) (Math.random() * numVertices)) == startNode); // no self-connections!
if(!graph.getAdjList().get(startNode).contains(new AdjListNode(nextNode, null))){
int cost = ((int)(Math.random() * 1000))+1;
graph.getAdjList().get(startNode).add(new AdjListNode(nextNode, new Edge(startNode, nextNode, cost, false))); //undirected graph; symmetrical connections
graph.getAdjList().get(nextNode).add(new AdjListNode(startNode, new Edge(nextNode, startNode, cost, false))); //undirected graph; symmetrical connections
numEdgesAdded = numEdgesAdded + 2;
}
}
} else if (numEdgesAdded > graph.getNumEdges()){ // we have too many edges, prune some. take care not to maroon any existing vertex
while(numEdgesAdded > graph.getNumEdges()){
startNode = (int) (Math.random() * numVertices);
while((nextNode = (int) (Math.random() * numVertices)) == startNode); // no self-connections!
if(graph.getAdjList().get(startNode).contains(new AdjListNode(nextNode, null))){
if(firstIncidentEdges[nextNode] != startNode){ // remove the edge only if it's not the first incident edge
graph.getAdjList().get(startNode).remove(new AdjListNode(nextNode, null));
graph.getAdjList().get(nextNode).remove(new AdjListNode(startNode, null));
numEdgesAdded = numEdgesAdded - 2;
}
}
}
}
return graph;
} |
22bb524a-0249-47c2-90d0-794022d5f942 | private static int[] createIncidentEdgeArray(int numVertices){
int[] firstIncidentEdges = new int[numVertices]; // record the first incident edge on a newly discovered vertex. comes in handy if we need to prune edges
// because it helps us avoid marooning vertices
for(int i=0; i<numVertices; i++){
firstIncidentEdges[i] = SENTINEL; // sentinel value
}
return firstIncidentEdges;
} |
37c8ea01-0b5a-44ac-8343-7ead3f020720 | private static Graph createTestGraph(int numVertices){
Graph graph = new Graph(numVertices, 0); //density is ignored since we're going to manually add test data
/*graph.getAdjList().get(2).put(5, new Edge(2, 5, 36, false));
graph.getAdjList().get(5).put(2, new Edge(5, 2, 36, false));
graph.getAdjList().get(1).put(4, new Edge(1, 4, 54, false));
graph.getAdjList().get(4).put(1, new Edge(4, 1, 54, false));
graph.getAdjList().get(1).put(5, new Edge(1, 5, 30, false));
graph.getAdjList().get(5).put(1, new Edge(5, 1, 30, false));
graph.getAdjList().get(6).put(4, new Edge(6, 4, 85, false));
graph.getAdjList().get(4).put(6, new Edge(4, 6, 85, false));
graph.getAdjList().get(2).put(0, new Edge(2, 0, 91, false));
graph.getAdjList().get(0).put(2, new Edge(0, 2, 91, false));
graph.getAdjList().get(2).put(6, new Edge(2, 6, 21, false));
graph.getAdjList().get(6).put(2, new Edge(6, 2, 21, false));
graph.getAdjList().get(3).put(0, new Edge(3, 0, 46, false));
graph.getAdjList().get(0).put(3, new Edge(0, 3, 46, false));
graph.getAdjList().get(3).put(1, new Edge(3, 1, 52, false));
graph.getAdjList().get(1).put(3, new Edge(1, 3, 52, false));
graph.getAdjList().get(0).put(1, new Edge(0, 1, 80, false));
graph.getAdjList().get(1).put(0, new Edge(1, 0, 80, false));
graph.getAdjList().get(4).put(0, new Edge(4, 0, 34, false));
graph.getAdjList().get(0).put(4, new Edge(0, 4, 34, false));*/
/*graph.getAdjList().get(4).put(2, new Edge(4, 2, 40, false));
graph.getAdjList().get(2).put(4, new Edge(2, 4, 40, false));
graph.getAdjList().get(4).put(0, new Edge(4, 0, 77, false));
graph.getAdjList().get(0).put(4, new Edge(0, 4, 77, false));
graph.getAdjList().get(2).put(0, new Edge(2, 0, 30, false));
graph.getAdjList().get(0).put(2, new Edge(0, 2, 30, false));
graph.getAdjList().get(3).put(0, new Edge(3, 0, 54, false));
graph.getAdjList().get(0).put(3, new Edge(0, 3, 54, false));
graph.getAdjList().get(3).put(1, new Edge(3, 1, 50, false));
graph.getAdjList().get(1).put(3, new Edge(1, 3, 50, false));*/
/*
* 0 -> 1 788
* 0 -> 2 974
* 0 -> 3 271
* 0 -> 4 177
* 3 -> 2 126
*/
/*graph.getAdjList().get(0).put(1, new Edge(0, 1, 788, false));
graph.getAdjList().get(0).put(2, new Edge(0, 2, 974, false));
graph.getAdjList().get(0).put(3, new Edge(0, 3, 271, false));
graph.getAdjList().get(0).put(4, new Edge(0, 4, 177, false));
graph.getAdjList().get(3).put(2, new Edge(3, 2, 126, false));*/
/*
* 0 -> 1 669
* 1 -> 3 575
* 3 -> 2 1
* 2 -> 0 993
* 2 -> 4 979
*/
/*graph.getAdjList().get(0).put(1, new Edge(0, 1, 669, false));
graph.getAdjList().get(1).put(3, new Edge(1, 3, 575, false));
graph.getAdjList().get(3).put(2, new Edge(3, 2, 1, false));
graph.getAdjList().get(2).put(0, new Edge(2, 0, 993, false));
graph.getAdjList().get(2).put(4, new Edge(2, 4, 979, false));*/
/*
* 0--->1 : 510
* 0--->2 : 621
* 1--->2 : 369
* 1--->4 : 643
* 4--->2 : 107
* 4--->3 : 535
*/
/*graph.getAdjList().get(0).put(1, new Edge(0, 1, 510, false));
graph.getAdjList().get(0).put(2, new Edge(0, 2, 621, false));
graph.getAdjList().get(1).put(2, new Edge(1, 2, 369, false));
graph.getAdjList().get(1).put(4, new Edge(1, 4, 643, false));
graph.getAdjList().get(4).put(2, new Edge(4, 2, 107, false));
graph.getAdjList().get(4).put(3, new Edge(4, 3, 535, false));*/
/*
* 1--->4 : 325
* 3--->0 : 751
* 3--->2 : 804
* 4--->0 : 429
* 4--->3 : 484
*/
/*graph.getAdjList().get(1).put(4, new Edge(1, 4, 325, false));
graph.getAdjList().get(3).put(0, new Edge(3, 0, 751, false));
graph.getAdjList().get(3).put(2, new Edge(3, 2, 804, false));
graph.getAdjList().get(4).put(0, new Edge(4, 0, 429, false));
graph.getAdjList().get(4).put(3, new Edge(4, 3, 484, false));*/
/*
* 0--->1 : 686
* 0--->2 : 197
* 1--->2 : 941
* 1--->4 : 250
* 2--->0 : 512
* 2--->3 : 991
*/
/*graph.getAdjList().get(0).put(1, new Edge(0, 1, 686, false));
graph.getAdjList().get(0).put(2, new Edge(0, 2, 197, false));
graph.getAdjList().get(1).put(2, new Edge(1, 2, 941, false));
graph.getAdjList().get(1).put(4, new Edge(1, 4, 250, false));
graph.getAdjList().get(2).put(0, new Edge(2, 0, 512, false));
graph.getAdjList().get(2).put(3, new Edge(2, 3, 991, false));*/
/*
* 1--->3 : 580
* 2--->0 : 909
* 2--->1 : 515
* 2--->4 : 776
* 3--->2 : 411
*/
/*graph.getAdjList().get(1).put(3, new Edge(1, 3, 580, false));
graph.getAdjList().get(2).put(0, new Edge(2, 0, 909, false));
graph.getAdjList().get(2).put(1, new Edge(2, 1, 515, false));
graph.getAdjList().get(2).put(4, new Edge(2, 4, 776, false));
graph.getAdjList().get(3).put(2, new Edge(3, 2, 411, false));*/
/*graph.getAdjList().get(10).put(8, new Edge(10, 8, 11, false));
graph.getAdjList().get(8).put(10, new Edge(8, 10, 11, false));
graph.getAdjList().get(7).put(12, new Edge(7, 12, 38, false));
graph.getAdjList().get(12).put(7, new Edge(12, 7, 38, false));
graph.getAdjList().get(10).put(0, new Edge(10, 0, 79, false));
graph.getAdjList().get(0).put(10, new Edge(0, 10, 79, false));
graph.getAdjList().get(5).put(0, new Edge(5, 0, 45, false));
graph.getAdjList().get(0).put(5, new Edge(0, 5, 45, false));
graph.getAdjList().get(6).put(2, new Edge(6, 2, 79, false));
graph.getAdjList().get(2).put(6, new Edge(2, 6, 79, false));
graph.getAdjList().get(14).put(6, new Edge(14, 6, 61, false));
graph.getAdjList().get(6).put(14, new Edge(6, 14, 61, false));
graph.getAdjList().get(3).put(12, new Edge(3, 12, 60, false));
graph.getAdjList().get(12).put(3, new Edge(12, 3, 60, false));
graph.getAdjList().get(6).put(9, new Edge(6, 9, 97, false));
graph.getAdjList().get(9).put(6, new Edge(9, 6, 97, false));
graph.getAdjList().get(7).put(0, new Edge(7, 0, 52, false));
graph.getAdjList().get(0).put(7, new Edge(0, 7, 52, false));
graph.getAdjList().get(4).put(6, new Edge(4, 6, 90, false));
graph.getAdjList().get(6).put(4, new Edge(6, 4, 90, false));
graph.getAdjList().get(6).put(13, new Edge(6, 13, 91, false));
graph.getAdjList().get(13).put(6, new Edge(13, 6, 91, false));
graph.getAdjList().get(5).put(10, new Edge(5, 10, 28, false));
graph.getAdjList().get(10).put(5, new Edge(10, 5, 28, false));
graph.getAdjList().get(2).put(13, new Edge(2, 13, 58, false));
graph.getAdjList().get(13).put(2, new Edge(13, 2, 58, false));
graph.getAdjList().get(10).put(7, new Edge(10, 7, 32, false));
graph.getAdjList().get(7).put(10, new Edge(7, 10, 32, false));
graph.getAdjList().get(11).put(6, new Edge(11, 6, 57, false));
graph.getAdjList().get(6).put(11, new Edge(6, 11, 57, false));
graph.getAdjList().get(14).put(11, new Edge(14, 11, 44, false));
graph.getAdjList().get(11).put(14, new Edge(11, 14, 44, false));
graph.getAdjList().get(12).put(0, new Edge(12, 0, 97, false));
graph.getAdjList().get(0).put(12, new Edge(0, 12, 97, false));
graph.getAdjList().get(12).put(4, new Edge(12, 4, 21, false));
graph.getAdjList().get(4).put(12, new Edge(4, 12, 21, false));
graph.getAdjList().get(3).put(6, new Edge(3, 6, 79, false));
graph.getAdjList().get(6).put(3, new Edge(6, 3, 79, false));
graph.getAdjList().get(9).put(4, new Edge(9, 4, 69, false));
graph.getAdjList().get(4).put(9, new Edge(4, 9, 69, false));
graph.getAdjList().get(0).put(1, new Edge(0, 1, 17, false));
graph.getAdjList().get(1).put(0, new Edge(1, 0, 17, false));
graph.getAdjList().get(9).put(2, new Edge(9, 2, 85, false));
graph.getAdjList().get(2).put(9, new Edge(2, 9, 85, false));
graph.getAdjList().get(4).put(7, new Edge(4, 7, 76, false));
graph.getAdjList().get(7).put(4, new Edge(7, 4, 76, false));
graph.getAdjList().get(9).put(12, new Edge(9, 12, 39, false));
graph.getAdjList().get(12).put(9, new Edge(12, 9, 39, false));
graph.getAdjList().get(5).put(1, new Edge(5, 1, 40, false));
graph.getAdjList().get(1).put(5, new Edge(1, 5, 40, false));
graph.getAdjList().get(14).put(5, new Edge(14, 5, 21, false));
graph.getAdjList().get(5).put(14, new Edge(5, 14, 21, false));
graph.getAdjList().get(14).put(7, new Edge(14, 7, 10, false));
graph.getAdjList().get(7).put(14, new Edge(7, 14, 10, false));
graph.getAdjList().get(5).put(4, new Edge(5, 4, 13, false));
graph.getAdjList().get(4).put(5, new Edge(4, 5, 13, false));
graph.getAdjList().get(5).put(11, new Edge(5, 11, 59, false));
graph.getAdjList().get(11).put(5, new Edge(11, 5, 59, false));
graph.getAdjList().get(6).put(0, new Edge(6, 0, 73, false));
graph.getAdjList().get(0).put(6, new Edge(0, 6, 73, false));
graph.getAdjList().get(6).put(1, new Edge(6, 1, 52, false));
graph.getAdjList().get(1).put(6, new Edge(1, 6, 52, false));
graph.getAdjList().get(12).put(10, new Edge(12, 10, 15, false));
graph.getAdjList().get(10).put(12, new Edge(10, 12, 15, false));
graph.getAdjList().get(1).put(3, new Edge(1, 3, 36, false));
graph.getAdjList().get(3).put(1, new Edge(3, 1, 36, false));
graph.getAdjList().get(14).put(9, new Edge(14, 9, 75, false));
graph.getAdjList().get(9).put(14, new Edge(9, 14, 75, false));
graph.getAdjList().get(14).put(2, new Edge(14, 2, 73, false));
graph.getAdjList().get(2).put(14, new Edge(2, 14, 73, false));
graph.getAdjList().get(1).put(2, new Edge(1, 2, 11, false));
graph.getAdjList().get(2).put(1, new Edge(2, 1, 11, false));
graph.getAdjList().get(13).put(4, new Edge(13, 4, 28, false));
graph.getAdjList().get(4).put(13, new Edge(4, 13, 28, false));
graph.getAdjList().get(10).put(14, new Edge(10, 14, 97, false));
graph.getAdjList().get(14).put(10, new Edge(14, 10, 97, false));
graph.getAdjList().get(11).put(9, new Edge(11, 9, 48, false));
graph.getAdjList().get(9).put(11, new Edge(9, 11, 48, false));
graph.getAdjList().get(7).put(11, new Edge(7, 11, 85, false));
graph.getAdjList().get(11).put(7, new Edge(11, 7, 85, false));
graph.getAdjList().get(14).put(1, new Edge(14, 1, 69, false));
graph.getAdjList().get(1).put(14, new Edge(1, 14, 69, false));
graph.getAdjList().get(3).put(0, new Edge(3, 0, 61, false));
graph.getAdjList().get(0).put(3, new Edge(0, 3, 61, false));
graph.getAdjList().get(10).put(3, new Edge(10, 3, 66, false));
graph.getAdjList().get(3).put(10, new Edge(3, 10, 66, false));
graph.getAdjList().get(11).put(13, new Edge(11, 13, 76, false));
graph.getAdjList().get(13).put(11, new Edge(13, 11, 76, false));
graph.getAdjList().get(8).put(11, new Edge(8, 11, 95, false));
graph.getAdjList().get(11).put(8, new Edge(11, 8, 95, false));
graph.getAdjList().get(4).put(11, new Edge(4, 11, 6, false));
graph.getAdjList().get(11).put(4, new Edge(11, 4, 6, false));
graph.getAdjList().get(2).put(0, new Edge(2, 0, 65, false));
graph.getAdjList().get(0).put(2, new Edge(0, 2, 65, false));
graph.getAdjList().get(4).put(2, new Edge(4, 2, 15, false));
graph.getAdjList().get(2).put(4, new Edge(2, 4, 15, false));
graph.getAdjList().get(1).put(7, new Edge(1, 7, 99, false));
graph.getAdjList().get(7).put(1, new Edge(7, 1, 99, false));
graph.getAdjList().get(10).put(1, new Edge(10, 1, 91, false));
graph.getAdjList().get(1).put(10, new Edge(1, 10, 91, false));
graph.getAdjList().get(12).put(14, new Edge(12, 14, 60, false));
graph.getAdjList().get(14).put(12, new Edge(14, 12, 60, false));
graph.getAdjList().get(8).put(4, new Edge(8, 4, 87, false));
graph.getAdjList().get(4).put(8, new Edge(4, 8, 87, false));*/
return graph;
} |
0a67577d-e008-4120-b382-f825dc3d51dd | public static List<Edge> generateMST(MSTGeneratorInterface mstGenerator, Graph graph){
long start = System.currentTimeMillis();
List<Edge> generatedMST = mstGenerator.generateMST(graph);
long end = System.currentTimeMillis();
runtime = end - start;
return generatedMST;
} |
e284d45e-82c8-44b1-b3a6-df1603de56ec | public static long getRuntime(){
return runtime;
} |
5269c7be-285e-4e1b-964e-74f4ea029d54 | public static void main(String[] args){
int numVertices = 1000;
double density = 0.5;
//uncomment the while to check if the f-heap, simple scheme equality breaks down at any time
/*while(true){*/
Graph graph = GraphGenerator.generateGraph(numVertices, density);
printGraphMetrics(graph, density);
List<Edge> finalMST = new SimpleSchemeMSTGenerator().generateMST(graph);
int total1 = printResults(finalMST);
finalMST = new FHeapSchemeMSTGenerator().generateMST(graph);
int total2 = printResults(finalMST);
/*if(total1 != total2)
break;
}*/
} |
31ca66d1-7045-4a94-ac75-54e0c4dd3879 | private static void printGraphMetrics(Graph graph, double density){
System.out.println("Number of vertices = "+graph.getNumVertices());
System.out.println("Edge density = "+density);
System.out.println("-----------------------------");
} |
b5780c1f-fa23-457e-99ff-f632590b9ff2 | private static int printResults(List<Edge> finalMST){
int totalCost = 0;
for(Edge MSTEdge: finalMST){
totalCost += MSTEdge.getCost();
}
System.out.println(totalCost);
System.out.println("-----");
for(Edge MSTEdge: finalMST){
System.out.println(MSTEdge.getStart()+"\t"+MSTEdge.getFinish()+"\t"+MSTEdge.getCost());
}
System.out.println();
return totalCost;
} |
9bf633dc-04d0-488a-b3fb-0a93d3dd6f56 | @Override
public List<Edge> generateMST(Graph graph){
fHeap = new FHeap();
List<Edge> generatedMST = new ArrayList<Edge>();
int startNodeIndex = graph.selectARandomNode();
for(int i = 0; i < graph.getNumVertices(); i++){
fHeap.insert(Integer.MAX_VALUE);
}
fHeap.decreaseKey(fHeap.getNodeList().get(startNodeIndex), 0, startNodeIndex);
while(fHeap.getSize() != 0){
FHeapNode newestMSTNode = fHeap.deleteMin();
startNodeIndex = newestMSTNode.getIndex();
for(AdjListNode node: graph.getAdjList().get(startNodeIndex)){
int nodeIndex = node.getTargetNode();
int cost = node.getEdge().getCost();
fHeap.decreaseKey(fHeap.getNodeList().get(nodeIndex), cost, startNodeIndex);
}
generatedMST.add(new Edge(newestMSTNode.getPredecessor(), newestMSTNode.getIndex(),
newestMSTNode.getCost(), false));
}
generatedMST.remove(0);
return generatedMST;
} |
bd9b2a4a-f64b-478f-b82a-655c7ab722cc | @Override
public List<Edge> generateMST(Graph graph){
List<Integer> nodesInMST = new ArrayList<Integer>();
int startMSTAt = graph.selectARandomNode();
nodesInMST.add(startMSTAt);
Edge[] feelerEdges = new Edge[graph.getNumVertices()];
for(int i = 0; i < feelerEdges.length; i++){
feelerEdges[i] = new Edge(0, 0, Integer.MAX_VALUE, false);
}
feelerEdges[startMSTAt] = new Edge(startMSTAt, startMSTAt, 0, true);
List<Edge> finalMSTEdges = new ArrayList<Edge>();
buildMSTNodeByNode(graph, startMSTAt, nodesInMST, finalMSTEdges, feelerEdges);
return finalMSTEdges;
} |
ca2d9715-afa8-4bc3-ac0b-30a6f772f28c | private void buildMSTNodeByNode(Graph graph,
int startMSTAt,
List<Integer> nodesInMST,
List<Edge> finalMSTEdges,
Edge[] feelerEdges){
//add the outgoing edges from this node to all the outgoing edges we already have
for(AdjListNode node: graph.getAdjList().get(startMSTAt)){
Edge feelerEdge = node.getEdge();
if(!nodesInMST.contains(feelerEdge.getFinish())){
if(feelerEdge.getCost() < feelerEdges[feelerEdge.getFinish()].getCost()){
feelerEdges[feelerEdge.getFinish()] = feelerEdge;
}
}
}
if(nodesInMST.size() == graph.getNumVertices())
return;
//O(n) traversal through the feeler edges to pick the least one
int minCost = Integer.MAX_VALUE;
int minEdgeIndex = -1;
Edge minEdge = null;
for(int i = 0; i < feelerEdges.length; i++){
if(!feelerEdges[i].isAlreadyInMST() && feelerEdges[i].getCost() < minCost){
minCost = feelerEdges[i].getCost();
minEdge = feelerEdges[i];
minEdgeIndex = i;
}
}
finalMSTEdges.add(minEdge);
nodesInMST.add(minEdge.getFinish());
feelerEdges[minEdgeIndex].setAlreadyInMST(true);
buildMSTNodeByNode(graph, minEdge.getFinish(), nodesInMST, finalMSTEdges, feelerEdges);
} |
9068b204-baab-49e9-a511-12f75f32ee6a | public AdjListNode(int targetNode, Edge edge){
super();
this.targetNode = targetNode;
this.edge = edge;
} |
06fa09dd-5d12-4bc9-b04c-2c95bc046f34 | @Override
public int hashCode(){
final int prime = 31;
int result = 1;
result = prime * result + targetNode;
return result;
} |
4102a150-9698-4b48-9fe0-b0a23253a17a | @Override
public boolean equals(Object obj){
if(this == obj)
return true;
if(obj == null)
return false;
if(!(obj instanceof AdjListNode))
return false;
AdjListNode other = (AdjListNode)obj;
if(targetNode != other.targetNode)
return false;
return true;
} |
53c3e243-7245-4eaf-b3b4-57174afaaa18 | public int getTargetNode(){
return targetNode;
} |
3bf8c1ba-2683-4f4a-a9f1-e2ea3f7212f1 | public void setTargetNode(int targetNode){
this.targetNode = targetNode;
} |
8a73b514-bb4a-4075-aeea-7710e9e41db9 | public Edge getEdge(){
return edge;
} |
59d03317-5500-44e7-86ba-87d761ab6ff2 | public void setEdge(Edge edge){
this.edge = edge;
} |
43031dc4-8acc-468b-b70d-a51495f64f38 | public Edge(int start, int finish, int cost, boolean eligible){
super();
this.start = start;
this.finish = finish;
this.cost = cost;
this.alreadyInMST = eligible;
} |
97c62cc0-8c91-4703-84f9-7a2404821604 | public int getStart(){
return start;
} |
fae403ee-8dfd-4bd0-aedf-b5bca15226ce | public void setStart(int start){
this.start = start;
} |
1a19b8b2-4a6d-42ca-a94a-a29c29507cf9 | public int getFinish(){
return finish;
} |
1b1399f8-cb81-4bad-9334-7fc518c0dd60 | public void setFinish(int finish){
this.finish = finish;
} |
0209fe60-8b74-40a9-a5e9-aa5de8e97f14 | public int getCost(){
return cost;
} |
cf923402-ec53-4c19-9f14-e02f9312ce2c | public void setCost(int cost){
this.cost = cost;
} |
f4161c83-ce90-4f1a-973c-a9eac760dffa | public boolean isAlreadyInMST(){
return alreadyInMST;
} |
56219136-3b8d-4e5c-974a-1f42c266a5e0 | public void setAlreadyInMST(boolean alreadyInMST){
this.alreadyInMST = alreadyInMST;
} |
f7317649-9ad6-47ca-a653-ff9465f55180 | public Graph(int numVertices, double density){
this.numVertices = numVertices;
this.numEdges = (int) (density * numVertices * (numVertices - 1) / 2);
adjList = new LinkedList<List<AdjListNode>>();
for(int i=0;i<numVertices;i++){
adjList.add(i, new LinkedList<AdjListNode>());
}
} |
e870d67a-c891-4575-a8b6-f9b213218825 | public int selectARandomNode(){
return (int) (Math.random() * numVertices);
} |
519e060c-85f6-493a-853c-e9ab28d48330 | public int getNumVertices(){
return numVertices;
} |
7a21116a-31fc-4602-8c62-946b0893b50e | public List<List<AdjListNode>> getAdjList(){
return adjList;
} |
f3f606a4-b061-4f98-bf27-e13de1e6c551 | public int getNumEdges(){
return numEdges;
} |
fa083ea1-8fff-4297-b584-24a8dadafb72 | public void setAdjList(List<List<AdjListNode>> adjList){
this.adjList = adjList;
} |
a2730c23-662a-41fc-ba5c-940133167358 | public FHeap(){
size = 0;
nodeList = new ArrayList<FHeapNode>();
nodeDegrees = new HashMap<Integer, FHeapNode>();
} |
e1492b64-0ec7-40ca-b997-03f953db438e | public void insert(int key){
FHeapNode newNode = new FHeapNode(size, key, 0, 0, null, null, null, null, false);
nodeList.add(newNode);
size++;
if(min == null){
newNode.setLeftSibling(newNode);
newNode.setRightSibling(newNode);
min = newNode;
}
else{
insertIntoRootList(nodeList.get(size - 1));
}
} |
7e342881-89d1-447c-ba51-0f551952db58 | private void insertIntoRootList(FHeapNode nodeToInsert){
spliceNodeToRight(min, nodeToInsert);
nodeToInsert.setParent(null);
nodeToInsert.setMarked(false);
if(nodeToInsert.getCost() < min.getCost())
min = nodeToInsert;
} |
cfd8e22a-bda8-4e80-8932-cb19baee4721 | private void spliceNodeToRight(FHeapNode existingNode, FHeapNode newNode){
newNode.setRightSibling(existingNode.getRightSibling());
newNode.setLeftSibling(existingNode);
existingNode.getRightSibling().setLeftSibling(newNode);
existingNode.setRightSibling(newNode);
} |
f12db506-060a-4721-b9ab-5cd4b773e454 | public FHeapNode deleteMin(){
if(size == 0)
throw new RuntimeException("Error: No elements in heap");
FHeapNode nodeToDelete = nodeList.get(min.getIndex());
// insert the children of the node we're about to delete into the root chain
insertChildrenOfNodeIntoRootList(nodeToDelete);
// connect up the two neighbors of the node we're about to delete
joinNeighbors(nodeToDelete);
nodeToDelete.setAlreadyInMST(true); // set the corresponding nodeList object to null to indicate it's already in the MST (this will be used to decide
// whether to ignore this node in decreaseKey
size--;
updateMin(nodeToDelete.getRightSibling());
nonRecursiveBinomialize(min);
return nodeToDelete;
} |
dd873633-49ce-4bb6-8001-029f3c5fb87d | private void insertChildrenOfNodeIntoRootList(FHeapNode node){
if(node.getChild() != null){
FHeapNode startNode = node.getChild();
FHeapNode currentNode = startNode.getRightSibling();
insertIntoRootList(startNode);
while(currentNode != startNode){
FHeapNode tempNode = currentNode.getRightSibling();
insertIntoRootList(currentNode);
currentNode = tempNode;
}
}
} |
a393a2ce-e03d-4d3b-95e3-e92e7316bca9 | private void updateMin(FHeapNode startNode){
min = startNode;
FHeapNode currentNode = startNode.getRightSibling();
while(currentNode != startNode){
if(!currentNode.isAlreadyInMST() && currentNode.getCost() < min.getCost()){
min = currentNode;
}
currentNode = currentNode.getRightSibling();
}
} |
b173037c-9caa-45a9-be78-ed075a96f20c | private void nonRecursiveBinomialize(FHeapNode startNode){
boolean DONE = false;
FHeapNode currentNode = startNode;
nodeDegrees.clear();
while(!DONE){
while(true){
int degree = currentNode.getDegree();
if(nodeDegrees.containsKey(degree)){
FHeapNode existingNodeOfSameDegree = nodeDegrees.get(degree);
FHeapNode winningNode = union(currentNode, existingNodeOfSameDegree);
currentNode = winningNode;
startNode = winningNode;
if(winningNode.getCost() <= min.getCost())
min = winningNode;
nodeDegrees.clear();
break;
}
else{
nodeDegrees.put(degree, currentNode);
currentNode = currentNode.getRightSibling();
if(currentNode == startNode){
DONE = true;
break;
}
}
}
//if(currentNode.getCost() <= min.getCost())
// min = currentNode;
}
} |
f363ea90-9ca2-4c01-b60e-4f53ddf6f5a2 | private void binomialize(FHeapNode startNode){
nodeDegrees.clear();
binomialize(startNode, startNode);
} |
49abb080-8ca8-4940-a619-3af694439db1 | private void binomialize(FHeapNode startNode, FHeapNode currentNode){
nodeDegrees.put(currentNode.getDegree(), currentNode);
while(currentNode.getRightSibling() != startNode){
FHeapNode node = currentNode.getRightSibling();
int degree = node.getDegree();
if(nodeDegrees.containsKey(degree)){
FHeapNode existingNodeOfSameDegree = nodeDegrees.get(degree);
FHeapNode winningNode = union(node, existingNodeOfSameDegree);
if(winningNode.getCost() <= min.getCost())
min = winningNode;
binomialize(winningNode); // start afresh
return;
}
else{
binomialize(startNode, node); // retain degrees hashmap
return;
}
}
} |
d973746c-3124-4488-80d2-abb0c0675f5d | private FHeapNode union(FHeapNode node1, FHeapNode node2){
if(node1.getCost() <= node2.getCost()){
node2.setParent(node1);
// connect up the neighbors of the node that we're about to make a child. this way the root chain stays connected
// without passing through the node that we just demoted
joinNeighbors(node2);
// connect up the child nodes
if(node1.getDegree() == 0){ // node1 has no preexisting children. this will be its first child. x <-> x
node1.setChild(node2);
node2.setLeftSibling(node2);
node2.setRightSibling(node2);
}
else
spliceNodeToRight(node1.getChild(), node2);
node1.setDegree(node1.getDegree() + 1); // increment degree
return node1;
}
else
return union(node2, node1); // node2 was < node1; try again
} |
ef4e14f6-1158-4f9a-b566-5eb457d4e444 | private void joinNeighbors(FHeapNode node){
node.getLeftSibling().setRightSibling(node.getRightSibling());
node.getRightSibling().setLeftSibling(node.getLeftSibling());
} |
2fb09aa9-576b-4008-b796-60c222c2ca81 | public void decreaseKey(FHeapNode node, int newKey, int predecessor){
if(node.isAlreadyInMST())
return;
if(newKey >= node.getCost())
return;
node.setCost(newKey);
node.setPredecessor(predecessor);
cut(node);
} |
d6876c25-a4c8-4b99-a528-0c2cd0e1900b | private void cut(FHeapNode node){
FHeapNode parent = node.getParent(); // save this beforehand because the reference to the parent will be nulled out in the insertIntoRootList method
if(null == parent){ // stop if we're at the root chain or if we ascended to it
if(node.getCost() < min.getCost())
min = node;
return;
}
else if(node.getCost() < parent.getCost()){
parent.setDegree(parent.getDegree() - 1); // decrement degree
if(node.getRightSibling() == node)
parent.setChild(null);
else{
if(parent.getChild() == node){
parent.setChild(node.getRightSibling());
}
joinNeighbors(node);
}
insertIntoRootList(node);
if(!parent.isMarked())
parent.setMarked(true);
else
cut(parent);
}
} |
6e7c4552-6bc1-4761-87b2-e7d43315f078 | public FHeapNode getMin(){
return min;
} |
829008db-b645-41ff-89f4-5b04e1f810b5 | public int getSize(){
return size;
} |
9e17a92d-e6cc-4b3f-b36e-11150c1619a1 | public List<FHeapNode> getNodeList(){
return nodeList;
} |
8541a900-c2cc-4aff-82eb-a4507ada92e1 | public FHeapNode(int index, int cost, int degree, int predecessor, FHeapNode leftSibling, FHeapNode rightSibling, FHeapNode parent,
FHeapNode child, boolean alreadyInMST){
super();
this.index = index;
this.cost = cost;
this.degree = degree;
this.predecessor = predecessor;
this.leftSibling = leftSibling;
this.rightSibling = rightSibling;
this.parent = parent;
this.child = child;
this.alreadyInMST = alreadyInMST;
} |
60024793-155d-4beb-9efe-b97ed8cdfb4f | public int getCost(){
return cost;
} |
f989796d-c08f-4e86-a3bf-2942f71f7dc9 | public void setCost(int cost){
this.cost = cost;
} |
d198b9e9-296e-462f-ba7d-167564fd9c65 | public FHeapNode getLeftSibling(){
return leftSibling;
} |
8d363503-4dad-4e8c-ac4c-2ed6f555a9a2 | public void setLeftSibling(FHeapNode leftSibling){
this.leftSibling = leftSibling;
} |
760c19d8-ae8b-47b7-a296-c74778c6e2aa | public FHeapNode getRightSibling(){
return rightSibling;
} |
e61ad9fa-b6f7-459d-b2f4-e1299cb51eb9 | public void setRightSibling(FHeapNode rightSibling){
this.rightSibling = rightSibling;
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.