repo
stringlengths
1
191
file
stringlengths
23
351
code
stringlengths
0
5.32M
file_length
int64
0
5.32M
avg_line_length
float64
0
2.9k
max_line_length
int64
0
288k
extension_type
stringclasses
1 value
TSOpen
TSOpen-master/src/main/java/lu/uni/tsopen/symbolicExecution/symbolicValues/UnknownValue.java
package lu.uni.tsopen.symbolicExecution.symbolicValues; /*- * #%L * TSOpen - Open-source implementation of TriggerScope * * Paper describing the approach : https://seclab.ccs.neu.edu/static/publications/sp2016triggerscope.pdf * * %% * Copyright (C) 2019 Jordan Samhi * University of Luxembourg - Interdisciplinary Centre for * Security Reliability and Trust (SnT) - All rights reserved * * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import lu.uni.tsopen.symbolicExecution.SymbolicExecution; import lu.uni.tsopen.utils.Constants; public class UnknownValue extends AbstractSymbolicValue { private String additionalValues; public UnknownValue(SymbolicExecution se) { super(se); this.additionalValues = ""; } @Override public String getValue() { if(this.additionalValues.isEmpty()) { return Constants.UNKNOWN_VALUE; }else { return String.format("%s_%s", Constants.UNKNOWN_VALUE, this.additionalValues); } } public void addValue(String s) { this.additionalValues += s; } @Override public boolean isSymbolic() { return true; } @Override public boolean isConstant() { return false; } @Override public boolean isMethodRepresentation() { return false; } @Override public boolean isObject() { return false; } }
1,930
24.077922
104
java
TSOpen
TSOpen-master/src/main/java/lu/uni/tsopen/symbolicExecution/symbolicValues/FieldValue.java
package lu.uni.tsopen.symbolicExecution.symbolicValues; /*- * #%L * TSOpen - Open-source implementation of TriggerScope * * Paper describing the approach : https://seclab.ccs.neu.edu/static/publications/sp2016triggerscope.pdf * * %% * Copyright (C) 2019 Jordan Samhi * University of Luxembourg - Interdisciplinary Centre for * Security Reliability and Trust (SnT) - All rights reserved * * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import lu.uni.tsopen.symbolicExecution.SymbolicExecution; import soot.Value; public class FieldValue extends AbstractSymbolicValue { private Value base; private String field; public FieldValue(Value base, String field, SymbolicExecution se) { super(se); this.base = base; this.field = field; } @Override public String getValue() { return String.format("%s.%s", this.base == null ? "" : this.base, this.field); } @Override public boolean isSymbolic() { return true; } @Override public boolean isConstant() { return false; } @Override public boolean isMethodRepresentation() { return false; } @Override public boolean isObject() { return false; } }
1,796
24.671429
104
java
TSOpen
TSOpen-master/src/main/java/lu/uni/tsopen/symbolicExecution/symbolicValues/AbstractSymbolicValue.java
package lu.uni.tsopen.symbolicExecution.symbolicValues; /*- * #%L * TSOpen - Open-source implementation of TriggerScope * * Paper describing the approach : https://seclab.ccs.neu.edu/static/publications/sp2016triggerscope.pdf * * %% * Copyright (C) 2019 Jordan Samhi * University of Luxembourg - Interdisciplinary Centre for * Security Reliability and Trust (SnT) - All rights reserved * * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import lu.uni.tsopen.symbolicExecution.ContextualValues; import lu.uni.tsopen.symbolicExecution.SymbolicExecution; import soot.Value; import soot.jimple.Constant; import soot.tagkit.StringConstantValueTag; public abstract class AbstractSymbolicValue implements SymbolicValue { protected List<StringConstantValueTag> tags; protected SymbolicExecution se; protected Map<Value, List<SymbolicValue>> values; public AbstractSymbolicValue(SymbolicExecution se) { this.tags = new ArrayList<StringConstantValueTag>(); this.se = se; this.values = new HashMap<Value, List<SymbolicValue>>(); } protected String computeValue(Value v) { List<SymbolicValue> values = null; String s = ""; values = this.values.get(v); if(values != null) { s += values.get(0); return s; }else if(v instanceof Constant){ return ((Constant)v).toString(); } return v.getType().toString(); } protected List<SymbolicValue> getSymbolicValues(Value v) { Map<Value, ContextualValues> context = this.se.getContext(); if(context.containsKey(v)) { return context.get(v).getLastCoherentValues(null); } return null; } @Override public List<StringConstantValueTag> getTags() { return this.tags; } @Override public String getStringTags() { String tags = ""; for(StringConstantValueTag scvt : this.tags) { tags += String.format("%s ", scvt.getStringValue()); } return tags; } @Override public boolean hasTag() { return !this.tags.isEmpty(); } @Override public String toString() { String value = ""; List<String> usedStrings = new ArrayList<String>(); String tagValue = null; if(!this.tags.isEmpty()) { for(StringConstantValueTag tag : this.tags) { tagValue = tag.getStringValue(); if(!usedStrings.contains(tagValue)) { usedStrings.add(tagValue); value += tag.getStringValue(); if(tag != this.tags.get(this.tags.size() - 1)) { value += " | "; } } } return value; } return this.getValue(); } @Override public void addTag(StringConstantValueTag tag) { this.tags.add(tag); } @Override public boolean containsTag(String t) { for(StringConstantValueTag tag : this.tags) { if(tag.getStringValue().equals(t)) { return true; } } return false; } @Override public Value getBase() { return null; } }
3,521
25.088889
104
java
TSOpen
TSOpen-master/src/main/java/lu/uni/tsopen/symbolicExecution/symbolicValues/SymbolicValue.java
package lu.uni.tsopen.symbolicExecution.symbolicValues; /*- * #%L * TSOpen - Open-source implementation of TriggerScope * * Paper describing the approach : https://seclab.ccs.neu.edu/static/publications/sp2016triggerscope.pdf * * %% * Copyright (C) 2019 Jordan Samhi * University of Luxembourg - Interdisciplinary Centre for * Security Reliability and Trust (SnT) - All rights reserved * * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.List; import soot.Value; import soot.tagkit.StringConstantValueTag; public interface SymbolicValue { public String getValue(); public boolean isSymbolic(); public boolean isConstant(); public boolean isMethodRepresentation(); public boolean isObject(); public boolean hasTag(); public void addTag(StringConstantValueTag scvt); public List<StringConstantValueTag> getTags(); public String getStringTags(); public boolean containsTag(String t); public Value getBase(); }
1,604
32.4375
104
java
TSOpen
TSOpen-master/src/main/java/lu/uni/tsopen/symbolicExecution/methodRecognizers/sms/SmsMethodsRecognition.java
package lu.uni.tsopen.symbolicExecution.methodRecognizers.sms; /*- * #%L * TSOpen - Open-source implementation of TriggerScope * * Paper describing the approach : https://seclab.ccs.neu.edu/static/publications/sp2016triggerscope.pdf * * %% * Copyright (C) 2019 Jordan Samhi * University of Luxembourg - Interdisciplinary Centre for * Security Reliability and Trust (SnT) - All rights reserved * * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import lu.uni.tsopen.symbolicExecution.symbolicValues.SymbolicValue; import soot.SootMethod; public interface SmsMethodsRecognition { public boolean recognizeSmsMethod(SootMethod method, SymbolicValue sv); public boolean processSmsMethod(SootMethod method, SymbolicValue sv); }
1,394
35.710526
104
java
TSOpen
TSOpen-master/src/main/java/lu/uni/tsopen/symbolicExecution/methodRecognizers/sms/SmsMethodsRecognitionHandler.java
package lu.uni.tsopen.symbolicExecution.methodRecognizers.sms; /*- * #%L * TSOpen - Open-source implementation of TriggerScope * * Paper describing the approach : https://seclab.ccs.neu.edu/static/publications/sp2016triggerscope.pdf * * %% * Copyright (C) 2019 Jordan Samhi * University of Luxembourg - Interdisciplinary Centre for * Security Reliability and Trust (SnT) - All rights reserved * * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import lu.uni.tsopen.symbolicExecution.SymbolicExecution; import lu.uni.tsopen.symbolicExecution.symbolicValues.SymbolicValue; import soot.SootMethod; public abstract class SmsMethodsRecognitionHandler implements SmsMethodsRecognition { private SmsMethodsRecognitionHandler next; protected SymbolicExecution se; public SmsMethodsRecognitionHandler(SmsMethodsRecognitionHandler next, SymbolicExecution se) { this.next = next; this.se = se; } @Override public boolean recognizeSmsMethod(SootMethod method, SymbolicValue sv) { boolean recognized = this.processSmsMethod(method, sv); if(recognized) { return recognized; } if(this.next != null) { return this.next.recognizeSmsMethod(method, sv); } else { return false; } } }
1,873
30.233333
104
java
TSOpen
TSOpen-master/src/main/java/lu/uni/tsopen/symbolicExecution/methodRecognizers/sms/CreateFromPduRecognition.java
package lu.uni.tsopen.symbolicExecution.methodRecognizers.sms; /*- * #%L * TSOpen - Open-source implementation of TriggerScope * * Paper describing the approach : https://seclab.ccs.neu.edu/static/publications/sp2016triggerscope.pdf * * %% * Copyright (C) 2019 Jordan Samhi * University of Luxembourg - Interdisciplinary Centre for * Security Reliability and Trust (SnT) - All rights reserved * * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import lu.uni.tsopen.symbolicExecution.SymbolicExecution; import lu.uni.tsopen.symbolicExecution.symbolicValues.SymbolicValue; import lu.uni.tsopen.utils.Constants; import soot.SootClass; import soot.SootMethod; import soot.tagkit.StringConstantValueTag; public class CreateFromPduRecognition extends SmsMethodsRecognitionHandler { public CreateFromPduRecognition(SmsMethodsRecognitionHandler next, SymbolicExecution se) { super(next, se); } @Override public boolean processSmsMethod(SootMethod method, SymbolicValue sv) { SootClass declaringClass = method.getDeclaringClass(); String methodName = method.getName(); if(methodName.equals(Constants.CREATE_FROM_PDU) && declaringClass.getName().equals(Constants.ANDROID_TELEPHONY_SMSMESSAGE)) { sv.addTag(new StringConstantValueTag(Constants.SMS_TAG)); return true; } return false; } }
1,973
34.25
127
java
TSOpen
TSOpen-master/src/main/java/lu/uni/tsopen/symbolicExecution/methodRecognizers/bool/StartsWithRecognition.java
package lu.uni.tsopen.symbolicExecution.methodRecognizers.bool; /*- * #%L * TSOpen - Open-source implementation of TriggerScope * * Paper describing the approach : https://seclab.ccs.neu.edu/static/publications/sp2016triggerscope.pdf * * %% * Copyright (C) 2019 Jordan Samhi * University of Luxembourg - Interdisciplinary Centre for * Security Reliability and Trust (SnT) - All rights reserved * * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.List; import lu.uni.tsopen.symbolicExecution.SymbolicExecution; import lu.uni.tsopen.symbolicExecution.symbolicValues.SymbolicValue; import lu.uni.tsopen.utils.Constants; import lu.uni.tsopen.utils.Utils; import soot.SootMethod; import soot.Value; import soot.jimple.Constant; import soot.tagkit.StringConstantValueTag; public class StartsWithRecognition extends BooleanMethodsRecognitionHandler { public StartsWithRecognition(BooleanMethodsRecognitionHandler next, SymbolicExecution se) { super(next, se); } @Override public boolean processBooleanMethod(SootMethod method, Value base, SymbolicValue sv, List<Value> args) { Value firstArg = null; String methodName = method.getName(); if(methodName.equals(Constants.STARTS_WITH)) { firstArg = args.get(0); if(Utils.containsTag(base, Constants.SMS_BODY_TAG, this.se) || Utils.containsTag(base, Constants.SMS_SENDER_TAG, this.se)) { if(firstArg instanceof Constant || Utils.containsTags(firstArg, this.se)) { sv.addTag(new StringConstantValueTag(Constants.SUSPICIOUS)); return true; } } } return false; } }
2,239
34
127
java
TSOpen
TSOpen-master/src/main/java/lu/uni/tsopen/symbolicExecution/methodRecognizers/bool/EqualsRecognition.java
package lu.uni.tsopen.symbolicExecution.methodRecognizers.bool; /*- * #%L * TSOpen - Open-source implementation of TriggerScope * * Paper describing the approach : https://seclab.ccs.neu.edu/static/publications/sp2016triggerscope.pdf * * %% * Copyright (C) 2019 Jordan Samhi * University of Luxembourg - Interdisciplinary Centre for * Security Reliability and Trust (SnT) - All rights reserved * * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.List; import lu.uni.tsopen.symbolicExecution.SymbolicExecution; import lu.uni.tsopen.symbolicExecution.symbolicValues.SymbolicValue; import lu.uni.tsopen.utils.Constants; import lu.uni.tsopen.utils.Utils; import soot.SootMethod; import soot.Value; import soot.jimple.Constant; import soot.tagkit.StringConstantValueTag; public class EqualsRecognition extends BooleanMethodsRecognitionHandler { public EqualsRecognition(BooleanMethodsRecognitionHandler next, SymbolicExecution se) { super(next, se); } @Override public boolean processBooleanMethod(SootMethod method, Value base, SymbolicValue sv, List<Value> args) { Value firstArg = null; String methodName = method.getName(); if(methodName.equals(Constants.EQUALS)) { firstArg = args.get(0); if(Utils.containsTag(base, Constants.NOW_TAG, this.se)) { if(firstArg.getType().toString().equals(Constants.JAVA_UTIL_DATE)) { sv.addTag(new StringConstantValueTag(Constants.SUSPICIOUS)); return true; } } if(Utils.containsTag(base, Constants.SMS_BODY_TAG, this.se) || Utils.containsTag(base, Constants.SMS_SENDER_TAG, this.se)) { if(firstArg instanceof Constant || Utils.containsTags(firstArg, this.se)) { sv.addTag(new StringConstantValueTag(Constants.SUSPICIOUS)); return true; } } } return false; } }
2,457
33.138889
127
java
TSOpen
TSOpen-master/src/main/java/lu/uni/tsopen/symbolicExecution/methodRecognizers/bool/BooleanMethodsRecognitionHandler.java
package lu.uni.tsopen.symbolicExecution.methodRecognizers.bool; /*- * #%L * TSOpen - Open-source implementation of TriggerScope * * Paper describing the approach : https://seclab.ccs.neu.edu/static/publications/sp2016triggerscope.pdf * * %% * Copyright (C) 2019 Jordan Samhi * University of Luxembourg - Interdisciplinary Centre for * Security Reliability and Trust (SnT) - All rights reserved * * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.List; import lu.uni.tsopen.symbolicExecution.SymbolicExecution; import lu.uni.tsopen.symbolicExecution.symbolicValues.SymbolicValue; import soot.SootMethod; import soot.Value; public abstract class BooleanMethodsRecognitionHandler implements BooleanMethodsRecognition { private BooleanMethodsRecognitionHandler next; protected SymbolicExecution se; public BooleanMethodsRecognitionHandler(BooleanMethodsRecognitionHandler next, SymbolicExecution se) { this.next = next; this.se = se; } @Override public boolean recognizeBooleanMethod(SootMethod method, Value base, SymbolicValue sv, List<Value> args) { boolean recognized = this.processBooleanMethod(method, base, sv, args); if(recognized) { return recognized; } if(this.next != null) { return this.next.recognizeBooleanMethod(method, base, sv, args); } else { return false; } } }
2,002
30.793651
107
java
TSOpen
TSOpen-master/src/main/java/lu/uni/tsopen/symbolicExecution/methodRecognizers/bool/BeforeRecognition.java
package lu.uni.tsopen.symbolicExecution.methodRecognizers.bool; /*- * #%L * TSOpen - Open-source implementation of TriggerScope * * Paper describing the approach : https://seclab.ccs.neu.edu/static/publications/sp2016triggerscope.pdf * * %% * Copyright (C) 2019 Jordan Samhi * University of Luxembourg - Interdisciplinary Centre for * Security Reliability and Trust (SnT) - All rights reserved * * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.List; import lu.uni.tsopen.symbolicExecution.SymbolicExecution; import lu.uni.tsopen.symbolicExecution.symbolicValues.SymbolicValue; import lu.uni.tsopen.utils.Constants; import lu.uni.tsopen.utils.Utils; import soot.SootMethod; import soot.Value; import soot.tagkit.StringConstantValueTag; public class BeforeRecognition extends BooleanMethodsRecognitionHandler { public BeforeRecognition(BooleanMethodsRecognitionHandler next, SymbolicExecution se) { super(next, se); } @Override public boolean processBooleanMethod(SootMethod method, Value base, SymbolicValue sv, List<Value> args) { Value firstArg = null; String methodName = method.getName(); if(methodName.equals(Constants.BEFORE)) { firstArg = args.get(0); if(Utils.containsTag(base, Constants.NOW_TAG, this.se)) { if(firstArg.getType().toString().equals(Constants.JAVA_UTIL_DATE)) { sv.addTag(new StringConstantValueTag(Constants.SUSPICIOUS)); return true; } } } return false; } }
2,119
32.125
105
java
TSOpen
TSOpen-master/src/main/java/lu/uni/tsopen/symbolicExecution/methodRecognizers/bool/AfterRecognition.java
package lu.uni.tsopen.symbolicExecution.methodRecognizers.bool; /*- * #%L * TSOpen - Open-source implementation of TriggerScope * * Paper describing the approach : https://seclab.ccs.neu.edu/static/publications/sp2016triggerscope.pdf * * %% * Copyright (C) 2019 Jordan Samhi * University of Luxembourg - Interdisciplinary Centre for * Security Reliability and Trust (SnT) - All rights reserved * * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.List; import lu.uni.tsopen.symbolicExecution.SymbolicExecution; import lu.uni.tsopen.symbolicExecution.symbolicValues.SymbolicValue; import lu.uni.tsopen.utils.Constants; import lu.uni.tsopen.utils.Utils; import soot.SootMethod; import soot.Value; import soot.tagkit.StringConstantValueTag; public class AfterRecognition extends BooleanMethodsRecognitionHandler { public AfterRecognition(BooleanMethodsRecognitionHandler next, SymbolicExecution se) { super(next, se); } @Override public boolean processBooleanMethod(SootMethod method, Value base, SymbolicValue sv, List<Value> args) { Value firstArg = null; String methodName = method.getName(); if(methodName.equals(Constants.AFTER)) { firstArg = args.get(0); if(Utils.containsTag(base, Constants.NOW_TAG, this.se)) { if(firstArg.getType().toString().equals(Constants.JAVA_UTIL_DATE) || firstArg.getType().toString().equals(Constants.JAVA_UTIL_CALENDAR) || firstArg.getType().toString().equals(Constants.JAVA_UTIL_GREGORIAN_CALENDAR) || firstArg.getType().toString().equals(Constants.JAVA_TEXT_SIMPLE_DATE_FORMAT) || firstArg.getType().toString().equals(Constants.JAVA_TIME_LOCAL_DATE_TIME) || firstArg.getType().toString().equals(Constants.JAVA_TIME_LOCAL_DATE)) { sv.addTag(new StringConstantValueTag(Constants.SUSPICIOUS)); return true; } } } return false; } }
2,525
35.608696
105
java
TSOpen
TSOpen-master/src/main/java/lu/uni/tsopen/symbolicExecution/methodRecognizers/bool/BooleanMethodsRecognition.java
package lu.uni.tsopen.symbolicExecution.methodRecognizers.bool; /*- * #%L * TSOpen - Open-source implementation of TriggerScope * * Paper describing the approach : https://seclab.ccs.neu.edu/static/publications/sp2016triggerscope.pdf * * %% * Copyright (C) 2019 Jordan Samhi * University of Luxembourg - Interdisciplinary Centre for * Security Reliability and Trust (SnT) - All rights reserved * * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.List; import lu.uni.tsopen.symbolicExecution.symbolicValues.SymbolicValue; import soot.SootMethod; import soot.Value; public interface BooleanMethodsRecognition { public boolean recognizeBooleanMethod(SootMethod method, Value base, SymbolicValue sv, List<Value> args); public boolean processBooleanMethod(SootMethod method, Value base, SymbolicValue sv, List<Value> args); }
1,510
35.853659
106
java
TSOpen
TSOpen-master/src/main/java/lu/uni/tsopen/symbolicExecution/methodRecognizers/bool/MatchesRecognition.java
package lu.uni.tsopen.symbolicExecution.methodRecognizers.bool; /*- * #%L * TSOpen - Open-source implementation of TriggerScope * * Paper describing the approach : https://seclab.ccs.neu.edu/static/publications/sp2016triggerscope.pdf * * %% * Copyright (C) 2019 Jordan Samhi * University of Luxembourg - Interdisciplinary Centre for * Security Reliability and Trust (SnT) - All rights reserved * * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.List; import lu.uni.tsopen.symbolicExecution.SymbolicExecution; import lu.uni.tsopen.symbolicExecution.symbolicValues.SymbolicValue; import lu.uni.tsopen.utils.Constants; import lu.uni.tsopen.utils.Utils; import soot.SootMethod; import soot.Value; import soot.jimple.Constant; import soot.tagkit.StringConstantValueTag; public class MatchesRecognition extends BooleanMethodsRecognitionHandler { public MatchesRecognition(BooleanMethodsRecognitionHandler next, SymbolicExecution se) { super(next, se); } @Override public boolean processBooleanMethod(SootMethod method, Value base, SymbolicValue sv, List<Value> args) { Value firstArg = null; String methodName = method.getName(); if(methodName.equals(Constants.MATCHES)) { if(args.size() > 0) { firstArg = args.get(0); if(Utils.containsTag(base, Constants.SMS_BODY_TAG, this.se) || Utils.containsTag(base, Constants.SMS_SENDER_TAG, this.se) || Utils.containsTag(base, Constants.NOW_TAG, this.se)) { if(firstArg instanceof Constant) { sv.addTag(new StringConstantValueTag(Constants.SUSPICIOUS)); return true; } } } } return false; } }
2,288
32.173913
105
java
TSOpen
TSOpen-master/src/main/java/lu/uni/tsopen/symbolicExecution/methodRecognizers/bool/ContainsRecognition.java
package lu.uni.tsopen.symbolicExecution.methodRecognizers.bool; /*- * #%L * TSOpen - Open-source implementation of TriggerScope * * Paper describing the approach : https://seclab.ccs.neu.edu/static/publications/sp2016triggerscope.pdf * * %% * Copyright (C) 2019 Jordan Samhi * University of Luxembourg - Interdisciplinary Centre for * Security Reliability and Trust (SnT) - All rights reserved * * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.List; import lu.uni.tsopen.symbolicExecution.SymbolicExecution; import lu.uni.tsopen.symbolicExecution.symbolicValues.SymbolicValue; import lu.uni.tsopen.utils.Constants; import lu.uni.tsopen.utils.Utils; import soot.SootMethod; import soot.Value; import soot.jimple.Constant; import soot.tagkit.StringConstantValueTag; public class ContainsRecognition extends BooleanMethodsRecognitionHandler { public ContainsRecognition(BooleanMethodsRecognitionHandler next, SymbolicExecution se) { super(next, se); } @Override public boolean processBooleanMethod(SootMethod method, Value base, SymbolicValue sv, List<Value> args) { Value firstArg = null; String methodName = method.getName(); if(methodName.equals(Constants.CONTAINS)) { firstArg = args.get(0); if(Utils.containsTag(base, Constants.SMS_BODY_TAG, this.se) || Utils.containsTag(base, Constants.SMS_SENDER_TAG, this.se)) { if(firstArg instanceof Constant) { sv.addTag(new StringConstantValueTag(Constants.SUSPICIOUS)); return true; } } } return false; } }
2,187
32.661538
127
java
TSOpen
TSOpen-master/src/main/java/lu/uni/tsopen/symbolicExecution/methodRecognizers/bool/EndsWithRecognition.java
package lu.uni.tsopen.symbolicExecution.methodRecognizers.bool; /*- * #%L * TSOpen - Open-source implementation of TriggerScope * * Paper describing the approach : https://seclab.ccs.neu.edu/static/publications/sp2016triggerscope.pdf * * %% * Copyright (C) 2019 Jordan Samhi * University of Luxembourg - Interdisciplinary Centre for * Security Reliability and Trust (SnT) - All rights reserved * * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.List; import lu.uni.tsopen.symbolicExecution.SymbolicExecution; import lu.uni.tsopen.symbolicExecution.symbolicValues.SymbolicValue; import lu.uni.tsopen.utils.Constants; import lu.uni.tsopen.utils.Utils; import soot.SootMethod; import soot.Value; import soot.jimple.Constant; import soot.tagkit.StringConstantValueTag; public class EndsWithRecognition extends BooleanMethodsRecognitionHandler { public EndsWithRecognition(BooleanMethodsRecognitionHandler next, SymbolicExecution se) { super(next, se); } @Override public boolean processBooleanMethod(SootMethod method, Value base, SymbolicValue sv, List<Value> args) { Value firstArg = null; String methodName = method.getName(); if(methodName.equals(Constants.ENDS_WITH)) { firstArg = args.get(0); if(Utils.containsTag(base, Constants.SMS_BODY_TAG, this.se) || Utils.containsTag(base, Constants.SMS_SENDER_TAG, this.se)) { if(firstArg instanceof Constant || Utils.containsTags(firstArg, this.se)) { sv.addTag(new StringConstantValueTag(Constants.SUSPICIOUS)); return true; } } } return false; } }
2,235
32.878788
127
java
TSOpen
TSOpen-master/src/main/java/lu/uni/tsopen/symbolicExecution/methodRecognizers/numeric/GetLatitudeRecognition.java
package lu.uni.tsopen.symbolicExecution.methodRecognizers.numeric; /*- * #%L * TSOpen - Open-source implementation of TriggerScope * * Paper describing the approach : https://seclab.ccs.neu.edu/static/publications/sp2016triggerscope.pdf * * %% * Copyright (C) 2019 Jordan Samhi * University of Luxembourg - Interdisciplinary Centre for * Security Reliability and Trust (SnT) - All rights reserved * * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import lu.uni.tsopen.symbolicExecution.SymbolicExecution; import lu.uni.tsopen.symbolicExecution.symbolicValues.SymbolicValue; import lu.uni.tsopen.utils.Constants; import soot.SootMethod; import soot.Value; public class GetLatitudeRecognition extends NumericMethodsRecognitionHandler { public GetLatitudeRecognition(NumericMethodsRecognitionHandler next, SymbolicExecution se) { super(next, se); } @Override public boolean processNumericMethod(SootMethod method, Value base, SymbolicValue sv) { return this.genericProcessNumericMethod(method, base, sv, Constants.ANDROID_LOCATION_LOCATION, Constants.GET_LATITUDE, Constants.HERE_TAG, Constants.LATITUDE_TAG); } }
1,794
35.632653
165
java
TSOpen
TSOpen-master/src/main/java/lu/uni/tsopen/symbolicExecution/methodRecognizers/numeric/GetSecondsRecognition.java
package lu.uni.tsopen.symbolicExecution.methodRecognizers.numeric; /*- * #%L * TSOpen - Open-source implementation of TriggerScope * * Paper describing the approach : https://seclab.ccs.neu.edu/static/publications/sp2016triggerscope.pdf * * %% * Copyright (C) 2019 Jordan Samhi * University of Luxembourg - Interdisciplinary Centre for * Security Reliability and Trust (SnT) - All rights reserved * * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import lu.uni.tsopen.symbolicExecution.SymbolicExecution; import lu.uni.tsopen.symbolicExecution.symbolicValues.SymbolicValue; import lu.uni.tsopen.utils.Constants; import soot.SootMethod; import soot.Value; public class GetSecondsRecognition extends NumericMethodsRecognitionHandler { public GetSecondsRecognition(NumericMethodsRecognitionHandler next, SymbolicExecution se) { super(next, se); } @Override public boolean processNumericMethod(SootMethod method, Value base, SymbolicValue sv) { return this.genericProcessNumericMethod(method, base, sv, Constants.JAVA_UTIL_DATE, Constants.GET_SECONDS, Constants.NOW_TAG, Constants.SECONDS_TAG); } }
1,777
36.041667
151
java
TSOpen
TSOpen-master/src/main/java/lu/uni/tsopen/symbolicExecution/methodRecognizers/numeric/GetMinutesRecognition.java
package lu.uni.tsopen.symbolicExecution.methodRecognizers.numeric; /*- * #%L * TSOpen - Open-source implementation of TriggerScope * * Paper describing the approach : https://seclab.ccs.neu.edu/static/publications/sp2016triggerscope.pdf * * %% * Copyright (C) 2019 Jordan Samhi * University of Luxembourg - Interdisciplinary Centre for * Security Reliability and Trust (SnT) - All rights reserved * * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import lu.uni.tsopen.symbolicExecution.SymbolicExecution; import lu.uni.tsopen.symbolicExecution.symbolicValues.SymbolicValue; import lu.uni.tsopen.utils.Constants; import soot.SootMethod; import soot.Value; public class GetMinutesRecognition extends NumericMethodsRecognitionHandler { public GetMinutesRecognition(NumericMethodsRecognitionHandler next, SymbolicExecution se) { super(next, se); } @Override public boolean processNumericMethod(SootMethod method, Value base, SymbolicValue sv) { return this.genericProcessNumericMethod(method, base, sv, Constants.JAVA_UTIL_DATE, Constants.GET_MINUTES, Constants.NOW_TAG, Constants.MINUTES_TAG); } }
1,778
35.306122
151
java
TSOpen
TSOpen-master/src/main/java/lu/uni/tsopen/symbolicExecution/methodRecognizers/numeric/GetRecognition.java
package lu.uni.tsopen.symbolicExecution.methodRecognizers.numeric; /*- * #%L * TSOpen - Open-source implementation of TriggerScope * * Paper describing the approach : https://seclab.ccs.neu.edu/static/publications/sp2016triggerscope.pdf * * %% * Copyright (C) 2019 Jordan Samhi * University of Luxembourg - Interdisciplinary Centre for * Security Reliability and Trust (SnT) - All rights reserved * * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import lu.uni.tsopen.symbolicExecution.SymbolicExecution; import lu.uni.tsopen.symbolicExecution.symbolicValues.SymbolicValue; import lu.uni.tsopen.utils.Constants; import soot.SootMethod; import soot.Value; import soot.tagkit.StringConstantValueTag; public class GetRecognition extends NumericMethodsRecognitionHandler { public GetRecognition(NumericMethodsRecognitionHandler next, SymbolicExecution se) { super(next, se); } @Override public boolean processNumericMethod(SootMethod method, Value base, SymbolicValue sv) { String className = method.getDeclaringClass().getName(); String methodName = method.getName(); if((methodName.equals(Constants.GET) && (className.equals(Constants.JAVA_UTIL_CALENDAR) || className.equals(Constants.JAVA_UTIL_GREGORIAN_CALENDAR)))) { sv.addTag(new StringConstantValueTag(Constants.NOW_TAG)); return true; } return false; } }
2,006
34.839286
154
java
TSOpen
TSOpen-master/src/main/java/lu/uni/tsopen/symbolicExecution/methodRecognizers/numeric/GetMonthRecognition.java
package lu.uni.tsopen.symbolicExecution.methodRecognizers.numeric; /*- * #%L * TSOpen - Open-source implementation of TriggerScope * * Paper describing the approach : https://seclab.ccs.neu.edu/static/publications/sp2016triggerscope.pdf * * %% * Copyright (C) 2019 Jordan Samhi * University of Luxembourg - Interdisciplinary Centre for * Security Reliability and Trust (SnT) - All rights reserved * * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import lu.uni.tsopen.symbolicExecution.SymbolicExecution; import lu.uni.tsopen.symbolicExecution.symbolicValues.SymbolicValue; import lu.uni.tsopen.utils.Constants; import soot.SootMethod; import soot.Value; public class GetMonthRecognition extends NumericMethodsRecognitionHandler { public GetMonthRecognition(NumericMethodsRecognitionHandler next, SymbolicExecution se) { super(next, se); } @Override public boolean processNumericMethod(SootMethod method, Value base, SymbolicValue sv) { return this.genericProcessNumericMethod(method, base, sv, Constants.JAVA_UTIL_DATE, Constants.GET_MONTH, Constants.NOW_TAG, Constants.MONTH_TAG); } }
1,770
35.142857
147
java
TSOpen
TSOpen-master/src/main/java/lu/uni/tsopen/symbolicExecution/methodRecognizers/numeric/NumericMethodsRecognitionHandler.java
package lu.uni.tsopen.symbolicExecution.methodRecognizers.numeric; /*- * #%L * TSOpen - Open-source implementation of TriggerScope * * Paper describing the approach : https://seclab.ccs.neu.edu/static/publications/sp2016triggerscope.pdf * * %% * Copyright (C) 2019 Jordan Samhi * University of Luxembourg - Interdisciplinary Centre for * Security Reliability and Trust (SnT) - All rights reserved * * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import lu.uni.tsopen.symbolicExecution.SymbolicExecution; import lu.uni.tsopen.symbolicExecution.symbolicValues.SymbolicValue; import lu.uni.tsopen.utils.Utils; import soot.SootMethod; import soot.Value; import soot.tagkit.StringConstantValueTag; public abstract class NumericMethodsRecognitionHandler implements NumericMethodsRecognition { private NumericMethodsRecognitionHandler next; protected SymbolicExecution se; public NumericMethodsRecognitionHandler(NumericMethodsRecognitionHandler next, SymbolicExecution se) { this.next = next; this.se = se; } @Override public boolean recognizeNumericMethod(SootMethod method, Value base, SymbolicValue sv) { boolean recognized = this.processNumericMethod(method, base, sv); if(recognized) { return recognized; } if(this.next != null) { return this.next.recognizeNumericMethod(method, base, sv); } else { return false; } } @Override public boolean genericProcessNumericMethod(SootMethod method, Value base, SymbolicValue sv, String className, String methodName, String containedTag, String addedTag) { if(method.getDeclaringClass().getName().equals(className) && method.getName().equals(methodName)) { if(this.isTagHandled(containedTag, addedTag, base, sv)) { return true; } } return false; } @Override public boolean isTagHandled(String containedTag, String addedTag, Value base, SymbolicValue sv) { if(Utils.containsTag(base, containedTag, this.se)) { sv.addTag(new StringConstantValueTag(addedTag)); return true; } return false; } }
2,678
31.277108
104
java
TSOpen
TSOpen-master/src/main/java/lu/uni/tsopen/symbolicExecution/methodRecognizers/numeric/GetHoursRecognition.java
package lu.uni.tsopen.symbolicExecution.methodRecognizers.numeric; /*- * #%L * TSOpen - Open-source implementation of TriggerScope * * Paper describing the approach : https://seclab.ccs.neu.edu/static/publications/sp2016triggerscope.pdf * * %% * Copyright (C) 2019 Jordan Samhi * University of Luxembourg - Interdisciplinary Centre for * Security Reliability and Trust (SnT) - All rights reserved * * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import lu.uni.tsopen.symbolicExecution.SymbolicExecution; import lu.uni.tsopen.symbolicExecution.symbolicValues.SymbolicValue; import lu.uni.tsopen.utils.Constants; import soot.SootMethod; import soot.Value; public class GetHoursRecognition extends NumericMethodsRecognitionHandler { public GetHoursRecognition(NumericMethodsRecognitionHandler next, SymbolicExecution se) { super(next, se); } @Override public boolean processNumericMethod(SootMethod method, Value base, SymbolicValue sv) { return this.genericProcessNumericMethod(method, base, sv, Constants.JAVA_UTIL_DATE, Constants.GET_HOURS, Constants.NOW_TAG, Constants.HOUR_TAG); } }
1,769
35.122449
146
java
TSOpen
TSOpen-master/src/main/java/lu/uni/tsopen/symbolicExecution/methodRecognizers/numeric/GetLongitudeRecognition.java
package lu.uni.tsopen.symbolicExecution.methodRecognizers.numeric; /*- * #%L * TSOpen - Open-source implementation of TriggerScope * * Paper describing the approach : https://seclab.ccs.neu.edu/static/publications/sp2016triggerscope.pdf * * %% * Copyright (C) 2019 Jordan Samhi * University of Luxembourg - Interdisciplinary Centre for * Security Reliability and Trust (SnT) - All rights reserved * * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import lu.uni.tsopen.symbolicExecution.SymbolicExecution; import lu.uni.tsopen.symbolicExecution.symbolicValues.SymbolicValue; import lu.uni.tsopen.utils.Constants; import soot.SootMethod; import soot.Value; public class GetLongitudeRecognition extends NumericMethodsRecognitionHandler { public GetLongitudeRecognition(NumericMethodsRecognitionHandler next, SymbolicExecution se) { super(next, se); } @Override public boolean processNumericMethod(SootMethod method, Value base, SymbolicValue sv) { return this.genericProcessNumericMethod(method, base, sv, Constants.ANDROID_LOCATION_LOCATION, Constants.GET_LONGITUDE, Constants.HERE_TAG, Constants.LONGITUDE_TAG); } }
1,798
35.714286
167
java
TSOpen
TSOpen-master/src/main/java/lu/uni/tsopen/symbolicExecution/methodRecognizers/numeric/NumericMethodsRecognition.java
package lu.uni.tsopen.symbolicExecution.methodRecognizers.numeric; /*- * #%L * TSOpen - Open-source implementation of TriggerScope * * Paper describing the approach : https://seclab.ccs.neu.edu/static/publications/sp2016triggerscope.pdf * * %% * Copyright (C) 2019 Jordan Samhi * University of Luxembourg - Interdisciplinary Centre for * Security Reliability and Trust (SnT) - All rights reserved * * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import lu.uni.tsopen.symbolicExecution.symbolicValues.SymbolicValue; import soot.SootMethod; import soot.Value; public interface NumericMethodsRecognition { public boolean recognizeNumericMethod(SootMethod method, Value base, SymbolicValue sv); public boolean processNumericMethod(SootMethod method, Value base, SymbolicValue sv); public boolean genericProcessNumericMethod(SootMethod method, Value base, SymbolicValue sv, String className, String methodName, String containedTag, String addedTag); public boolean isTagHandled(String containedTag, String addedTag, Value base, SymbolicValue sv); }
1,722
41.02439
104
java
TSOpen
TSOpen-master/src/main/java/lu/uni/tsopen/symbolicExecution/methodRecognizers/numeric/CurrentTimeMillisRecognition.java
package lu.uni.tsopen.symbolicExecution.methodRecognizers.numeric; /*- * #%L * TSOpen - Open-source implementation of TriggerScope * * Paper describing the approach : https://seclab.ccs.neu.edu/static/publications/sp2016triggerscope.pdf * * %% * Copyright (C) 2019 Jordan Samhi * University of Luxembourg - Interdisciplinary Centre for * Security Reliability and Trust (SnT) - All rights reserved * * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import lu.uni.tsopen.symbolicExecution.SymbolicExecution; import lu.uni.tsopen.symbolicExecution.symbolicValues.SymbolicValue; import lu.uni.tsopen.utils.Constants; import soot.SootMethod; import soot.Value; import soot.tagkit.StringConstantValueTag; public class CurrentTimeMillisRecognition extends NumericMethodsRecognitionHandler { public CurrentTimeMillisRecognition(NumericMethodsRecognitionHandler next, SymbolicExecution se) { super(next, se); } @Override public boolean processNumericMethod(SootMethod method, Value base, SymbolicValue sv) { return this.genericProcessNumericMethod(method, base, sv, Constants.JAVA_LANG_SYSTEM, Constants.CURRENT_TIME_MILLIS, null, Constants.NOW_TAG); } @Override public boolean isTagHandled(String containedTag, String addedTag, Value base, SymbolicValue sv) { sv.addTag(new StringConstantValueTag(addedTag)); return true; } }
2,008
34.875
144
java
TSOpen
TSOpen-master/src/main/java/lu/uni/tsopen/symbolicExecution/methodRecognizers/numeric/GetYearRecognition.java
package lu.uni.tsopen.symbolicExecution.methodRecognizers.numeric; /*- * #%L * TSOpen - Open-source implementation of TriggerScope * * Paper describing the approach : https://seclab.ccs.neu.edu/static/publications/sp2016triggerscope.pdf * * %% * Copyright (C) 2019 Jordan Samhi * University of Luxembourg - Interdisciplinary Centre for * Security Reliability and Trust (SnT) - All rights reserved * * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import lu.uni.tsopen.symbolicExecution.SymbolicExecution; import lu.uni.tsopen.symbolicExecution.symbolicValues.SymbolicValue; import lu.uni.tsopen.utils.Constants; import soot.SootMethod; import soot.Value; public class GetYearRecognition extends NumericMethodsRecognitionHandler { public GetYearRecognition(NumericMethodsRecognitionHandler next, SymbolicExecution se) { super(next, se); } @Override public boolean processNumericMethod(SootMethod method, Value base, SymbolicValue sv) { return this.genericProcessNumericMethod(method, base, sv, Constants.JAVA_UTIL_DATE, Constants.GET_YEAR, Constants.NOW_TAG, Constants.YEAR_TAG); } }
1,766
35.061224
145
java
TSOpen
TSOpen-master/src/main/java/lu/uni/tsopen/symbolicExecution/methodRecognizers/location/GetLastLocationRecognition.java
package lu.uni.tsopen.symbolicExecution.methodRecognizers.location; /*- * #%L * TSOpen - Open-source implementation of TriggerScope * * Paper describing the approach : https://seclab.ccs.neu.edu/static/publications/sp2016triggerscope.pdf * * %% * Copyright (C) 2019 Jordan Samhi * University of Luxembourg - Interdisciplinary Centre for * Security Reliability and Trust (SnT) - All rights reserved * * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import lu.uni.tsopen.symbolicExecution.SymbolicExecution; import lu.uni.tsopen.symbolicExecution.symbolicValues.SymbolicValue; import lu.uni.tsopen.utils.Constants; import soot.SootMethod; import soot.Type; import soot.Value; import soot.tagkit.StringConstantValueTag; public class GetLastLocationRecognition extends LocationMethodsRecognitionHandler { public GetLastLocationRecognition(LocationMethodsRecognitionHandler next, SymbolicExecution se) { super(next, se); } @Override public boolean processLocationMethod(SootMethod method, SymbolicValue sv) { String methodName = method.getName(); Value base = sv.getBase(); Type type = base == null ? method.getDeclaringClass().getType() : base.getType(); if((base != null && type.toString().equals(Constants.COM_GOOGLE_ANDROID_GMS_LOCATION_LOCATION_RESULT) && methodName.equals(Constants.GET_LAST_LOCATION))) { sv.addTag(new StringConstantValueTag(Constants.HERE_TAG)); return true; } return false; } }
2,097
35.807018
157
java
TSOpen
TSOpen-master/src/main/java/lu/uni/tsopen/symbolicExecution/methodRecognizers/location/DistanceBetweenRecognition.java
package lu.uni.tsopen.symbolicExecution.methodRecognizers.location; /*- * #%L * TSOpen - Open-source implementation of TriggerScope * * Paper describing the approach : https://seclab.ccs.neu.edu/static/publications/sp2016triggerscope.pdf * * %% * Copyright (C) 2019 Jordan Samhi * University of Luxembourg - Interdisciplinary Centre for * Security Reliability and Trust (SnT) - All rights reserved * * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.List; import lu.uni.tsopen.symbolicExecution.ContextualValues; import lu.uni.tsopen.symbolicExecution.SymbolicExecution; import lu.uni.tsopen.symbolicExecution.symbolicValues.MethodRepresentationValue; import lu.uni.tsopen.symbolicExecution.symbolicValues.SymbolicValue; import lu.uni.tsopen.utils.Constants; import lu.uni.tsopen.utils.Utils; import soot.SootMethod; import soot.Value; import soot.tagkit.StringConstantValueTag; public class DistanceBetweenRecognition extends LocationMethodsRecognitionHandler { public DistanceBetweenRecognition(LocationMethodsRecognitionHandler next, SymbolicExecution se) { super(next, se); } @Override public boolean processLocationMethod(SootMethod method, SymbolicValue sv) { MethodRepresentationValue mrv = null; Value lastArg = null; List<Value> args = null; ContextualValues contextualValues = null; List<SymbolicValue> values = null; if(method.getName().equals(Constants.DISTANCE_BETWEEN)) { if(sv instanceof MethodRepresentationValue) { mrv = (MethodRepresentationValue) sv; args = mrv.getArgs(); for(Value arg : args) { if(Utils.containsTag(arg, Constants.LATITUDE_TAG, this.se) || Utils.containsTag(arg, Constants.LONGITUDE_TAG, this.se)) { lastArg = args.get(args.size() - 1); contextualValues = this.se.getContextualValues(lastArg); if(contextualValues != null) { values = contextualValues.getLastCoherentValues(null); if(values != null) { for(SymbolicValue symval : values) { symval.addTag(new StringConstantValueTag(Constants.SUSPICIOUS)); } } } } } } return true; } return false; } }
2,812
32.891566
104
java
TSOpen
TSOpen-master/src/main/java/lu/uni/tsopen/symbolicExecution/methodRecognizers/location/GetLastKnowLocationRecognition.java
package lu.uni.tsopen.symbolicExecution.methodRecognizers.location; /*- * #%L * TSOpen - Open-source implementation of TriggerScope * * Paper describing the approach : https://seclab.ccs.neu.edu/static/publications/sp2016triggerscope.pdf * * %% * Copyright (C) 2019 Jordan Samhi * University of Luxembourg - Interdisciplinary Centre for * Security Reliability and Trust (SnT) - All rights reserved * * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import lu.uni.tsopen.symbolicExecution.SymbolicExecution; import lu.uni.tsopen.symbolicExecution.symbolicValues.SymbolicValue; import lu.uni.tsopen.utils.Constants; import soot.SootMethod; import soot.tagkit.StringConstantValueTag; public class GetLastKnowLocationRecognition extends LocationMethodsRecognitionHandler { public GetLastKnowLocationRecognition(LocationMethodsRecognitionHandler next, SymbolicExecution se) { super(next, se); } @Override public boolean processLocationMethod(SootMethod method, SymbolicValue sv) { String className = method.getDeclaringClass().getName(); String methodName = method.getName(); if((className.equals(Constants.ANDROID_LOCATION_LOCATION_MANAGER) && methodName.equals(Constants.GET_LAST_KNOW_LOCATION))) { sv.addTag(new StringConstantValueTag(Constants.HERE_TAG)); return true; } return false; } }
1,983
35.740741
126
java
TSOpen
TSOpen-master/src/main/java/lu/uni/tsopen/symbolicExecution/methodRecognizers/location/LocationMethodsRecognitionHandler.java
package lu.uni.tsopen.symbolicExecution.methodRecognizers.location; /*- * #%L * TSOpen - Open-source implementation of TriggerScope * * Paper describing the approach : https://seclab.ccs.neu.edu/static/publications/sp2016triggerscope.pdf * * %% * Copyright (C) 2019 Jordan Samhi * University of Luxembourg - Interdisciplinary Centre for * Security Reliability and Trust (SnT) - All rights reserved * * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import lu.uni.tsopen.symbolicExecution.SymbolicExecution; import lu.uni.tsopen.symbolicExecution.symbolicValues.SymbolicValue; import soot.SootMethod; public abstract class LocationMethodsRecognitionHandler implements LocationMethodsRecognition { private LocationMethodsRecognitionHandler next; protected SymbolicExecution se; public LocationMethodsRecognitionHandler(LocationMethodsRecognitionHandler next, SymbolicExecution se) { this.next = next; this.se = se; } @Override public boolean recognizeLocationMethod(SootMethod method, SymbolicValue sv) { boolean recognized = this.processLocationMethod(method, sv); if(recognized) { return recognized; } if(this.next != null) { return this.next.recognizeLocationMethod(method, sv); } else { return false; } } }
1,917
30.966667
105
java
TSOpen
TSOpen-master/src/main/java/lu/uni/tsopen/symbolicExecution/methodRecognizers/location/LocationMethodsRecognition.java
package lu.uni.tsopen.symbolicExecution.methodRecognizers.location; /*- * #%L * TSOpen - Open-source implementation of TriggerScope * * Paper describing the approach : https://seclab.ccs.neu.edu/static/publications/sp2016triggerscope.pdf * * %% * Copyright (C) 2019 Jordan Samhi * University of Luxembourg - Interdisciplinary Centre for * Security Reliability and Trust (SnT) - All rights reserved * * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import lu.uni.tsopen.symbolicExecution.symbolicValues.SymbolicValue; import soot.SootMethod; public interface LocationMethodsRecognition { public boolean recognizeLocationMethod(SootMethod method, SymbolicValue sv); public boolean processLocationMethod(SootMethod method, SymbolicValue sv); }
1,414
36.236842
104
java
TSOpen
TSOpen-master/src/main/java/lu/uni/tsopen/symbolicExecution/methodRecognizers/dateTime/GetInstanceRecognition.java
package lu.uni.tsopen.symbolicExecution.methodRecognizers.dateTime; /*- * #%L * TSOpen - Open-source implementation of TriggerScope * * Paper describing the approach : https://seclab.ccs.neu.edu/static/publications/sp2016triggerscope.pdf * * %% * Copyright (C) 2019 Jordan Samhi * University of Luxembourg - Interdisciplinary Centre for * Security Reliability and Trust (SnT) - All rights reserved * * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import lu.uni.tsopen.symbolicExecution.SymbolicExecution; import lu.uni.tsopen.symbolicExecution.symbolicValues.SymbolicValue; import lu.uni.tsopen.utils.Constants; import soot.SootMethod; import soot.tagkit.StringConstantValueTag; public class GetInstanceRecognition extends DateTimeMethodsRecognitionHandler { public GetInstanceRecognition(DateTimeMethodsRecognitionHandler next, SymbolicExecution se) { super(next, se); } @Override public boolean processDateTimeMethod(SootMethod method, SymbolicValue sv) { String className = method.getDeclaringClass().getName(); String methodName = method.getName(); if((methodName.equals(Constants.GET_INSTANCE) && (className.equals(Constants.JAVA_UTIL_CALENDAR) || className.equals(Constants.JAVA_UTIL_GREGORIAN_CALENDAR)))) { sv.addTag(new StringConstantValueTag(Constants.NOW_TAG)); return true; } return false; } }
2,004
35.454545
163
java
TSOpen
TSOpen-master/src/main/java/lu/uni/tsopen/symbolicExecution/methodRecognizers/dateTime/DateTimeMethodsRecognitionHandler.java
package lu.uni.tsopen.symbolicExecution.methodRecognizers.dateTime; /*- * #%L * TSOpen - Open-source implementation of TriggerScope * * Paper describing the approach : https://seclab.ccs.neu.edu/static/publications/sp2016triggerscope.pdf * * %% * Copyright (C) 2019 Jordan Samhi * University of Luxembourg - Interdisciplinary Centre for * Security Reliability and Trust (SnT) - All rights reserved * * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import lu.uni.tsopen.symbolicExecution.SymbolicExecution; import lu.uni.tsopen.symbolicExecution.symbolicValues.SymbolicValue; import soot.SootMethod; public abstract class DateTimeMethodsRecognitionHandler implements DateTimeMethodsRecognition { private DateTimeMethodsRecognitionHandler next; protected SymbolicExecution se; public DateTimeMethodsRecognitionHandler(DateTimeMethodsRecognitionHandler next, SymbolicExecution se) { this.next = next; this.se = se; } @Override public boolean recognizeDateTimeMethod(SootMethod method, SymbolicValue sv) { boolean recognized = this.processDateTimeMethod(method, sv); if(recognized) { return recognized; } if(this.next != null) { return this.next.recognizeDateTimeMethod(method, sv); } else { return false; } } }
1,917
30.966667
105
java
TSOpen
TSOpen-master/src/main/java/lu/uni/tsopen/symbolicExecution/methodRecognizers/dateTime/DateTimeMethodsRecognition.java
package lu.uni.tsopen.symbolicExecution.methodRecognizers.dateTime; /*- * #%L * TSOpen - Open-source implementation of TriggerScope * * Paper describing the approach : https://seclab.ccs.neu.edu/static/publications/sp2016triggerscope.pdf * * %% * Copyright (C) 2019 Jordan Samhi * University of Luxembourg - Interdisciplinary Centre for * Security Reliability and Trust (SnT) - All rights reserved * * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import lu.uni.tsopen.symbolicExecution.symbolicValues.SymbolicValue; import soot.SootMethod; public interface DateTimeMethodsRecognition { public boolean recognizeDateTimeMethod(SootMethod method, SymbolicValue sv); public boolean processDateTimeMethod(SootMethod method, SymbolicValue sv); }
1,414
36.236842
104
java
TSOpen
TSOpen-master/src/main/java/lu/uni/tsopen/symbolicExecution/methodRecognizers/dateTime/NowRecognition.java
package lu.uni.tsopen.symbolicExecution.methodRecognizers.dateTime; /*- * #%L * TSOpen - Open-source implementation of TriggerScope * * Paper describing the approach : https://seclab.ccs.neu.edu/static/publications/sp2016triggerscope.pdf * * %% * Copyright (C) 2019 Jordan Samhi * University of Luxembourg - Interdisciplinary Centre for * Security Reliability and Trust (SnT) - All rights reserved * * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import lu.uni.tsopen.symbolicExecution.SymbolicExecution; import lu.uni.tsopen.symbolicExecution.symbolicValues.SymbolicValue; import lu.uni.tsopen.utils.Constants; import soot.SootMethod; import soot.tagkit.StringConstantValueTag; public class NowRecognition extends DateTimeMethodsRecognitionHandler { public NowRecognition(DateTimeMethodsRecognitionHandler next, SymbolicExecution se) { super(next, se); } @Override public boolean processDateTimeMethod(SootMethod method, SymbolicValue sv) { String className = method.getDeclaringClass().getName(); String methodName = method.getName(); if(methodName.equals(Constants.NOW) && (className.equals(Constants.JAVA_TIME_LOCAL_DATE_TIME) || className.equals(Constants.JAVA_TIME_LOCAL_DATE))) { sv.addTag(new StringConstantValueTag(Constants.NOW_TAG)); return true; } return false; } }
1,975
35.592593
151
java
TSOpen
TSOpen-master/src/main/java/lu/uni/tsopen/symbolicExecution/methodRecognizers/dateTime/SetToNowRecognition.java
package lu.uni.tsopen.symbolicExecution.methodRecognizers.dateTime; /*- * #%L * TSOpen - Open-source implementation of TriggerScope * * Paper describing the approach : https://seclab.ccs.neu.edu/static/publications/sp2016triggerscope.pdf * * %% * Copyright (C) 2019 Jordan Samhi * University of Luxembourg - Interdisciplinary Centre for * Security Reliability and Trust (SnT) - All rights reserved * * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import lu.uni.tsopen.symbolicExecution.SymbolicExecution; import lu.uni.tsopen.symbolicExecution.symbolicValues.SymbolicValue; import lu.uni.tsopen.utils.Constants; import soot.SootMethod; import soot.tagkit.StringConstantValueTag; public class SetToNowRecognition extends DateTimeMethodsRecognitionHandler { public SetToNowRecognition(DateTimeMethodsRecognitionHandler next, SymbolicExecution se) { super(next, se); } @Override public boolean processDateTimeMethod(SootMethod method, SymbolicValue sv) { String className = method.getDeclaringClass().getName(); String methodName = method.getName(); if(methodName.equals(Constants.SET_TO_NOW) && (className.equals(Constants.ANDROID_TEXT_FORMAT_TIME))) { sv.addTag(new StringConstantValueTag(Constants.NOW_TAG)); return true; } return false; } }
1,940
34.290909
105
java
TSOpen
TSOpen-master/src/main/java/lu/uni/tsopen/symbolicExecution/methodRecognizers/strings/FormatRecognition.java
package lu.uni.tsopen.symbolicExecution.methodRecognizers.strings; /*- * #%L * TSOpen - Open-source implementation of TriggerScope * * Paper describing the approach : https://seclab.ccs.neu.edu/static/publications/sp2016triggerscope.pdf * * %% * Copyright (C) 2019 Jordan Samhi * University of Luxembourg - Interdisciplinary Centre for * Security Reliability and Trust (SnT) - All rights reserved * * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.ArrayList; import java.util.List; import lu.uni.tsopen.symbolicExecution.SymbolicExecution; import lu.uni.tsopen.symbolicExecution.symbolicValues.SymbolicValue; import lu.uni.tsopen.utils.Constants; import lu.uni.tsopen.utils.Utils; import soot.SootMethod; import soot.Value; public class FormatRecognition extends StringMethodsRecognitionHandler { public FormatRecognition(StringMethodsRecognitionHandler next, SymbolicExecution se) { super(next, se); } @Override public List<SymbolicValue> processStringMethod(SootMethod method, Value base, List<Value> args) { List<SymbolicValue> results = new ArrayList<SymbolicValue>(); if(method.getName().equals(Constants.FORMAT) && base != null && base.getType().toString().equals(Constants.JAVA_TEXT_SIMPLE_DATE_FORMAT)) { this.addSimpleResult(base, results); for(Value arg : args) { for(SymbolicValue sv : results) { Utils.propagateTags(arg, sv, this.se); } } return results; } return null; } }
2,117
32.619048
141
java
TSOpen
TSOpen-master/src/main/java/lu/uni/tsopen/symbolicExecution/methodRecognizers/strings/SubStringRecognition.java
package lu.uni.tsopen.symbolicExecution.methodRecognizers.strings; /*- * #%L * TSOpen - Open-source implementation of TriggerScope * * Paper describing the approach : https://seclab.ccs.neu.edu/static/publications/sp2016triggerscope.pdf * * %% * Copyright (C) 2019 Jordan Samhi * University of Luxembourg - Interdisciplinary Centre for * Security Reliability and Trust (SnT) - All rights reserved * * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.ArrayList; import java.util.List; import lu.uni.tsopen.symbolicExecution.SymbolicExecution; import lu.uni.tsopen.symbolicExecution.symbolicValues.ConstantValue; import lu.uni.tsopen.symbolicExecution.symbolicValues.MethodRepresentationValue; import lu.uni.tsopen.symbolicExecution.symbolicValues.SymbolicValue; import lu.uni.tsopen.utils.Constants; import soot.SootMethod; import soot.Value; import soot.jimple.IntConstant; import soot.jimple.StringConstant; public class SubStringRecognition extends StringMethodsRecognitionHandler { public SubStringRecognition(StringMethodsRecognitionHandler next, SymbolicExecution se) { super(next, se); } @Override public List<SymbolicValue> processStringMethod(SootMethod method, Value base, List<Value> args) { List<SymbolicValue> results = new ArrayList<SymbolicValue>(); StringConstant baseStr = null; Value arg1 = null, arg2 = null; int v1 = 0, v2 = 0; SymbolicValue object = null; if(method.getName().equals(Constants.SUBSTRING)) { if(base instanceof StringConstant) { baseStr = (StringConstant) base; if(baseStr.value.contains(Constants.UNKNOWN_STRING)){ object = new MethodRepresentationValue(base, args, method, this.se); }else { arg1 = args.get(0); if(arg1 instanceof IntConstant) { v1 = ((IntConstant)arg1).value; if(args.size() == 1) { object = new ConstantValue(StringConstant.v(baseStr.value.substring(v1)), this.se); }else { arg2 = args.get(1); if(arg2 instanceof IntConstant) { v2 = ((IntConstant)arg2).value; object = new ConstantValue(StringConstant.v(baseStr.value.substring(v1, v2)), this.se); } } } } }else { object = new MethodRepresentationValue(base, args, method, this.se); } if(object != null) { this.addResult(results, object); } return results; } return null; } }
3,031
32.318681
104
java
TSOpen
TSOpen-master/src/main/java/lu/uni/tsopen/symbolicExecution/methodRecognizers/strings/StringMethodsRecognition.java
package lu.uni.tsopen.symbolicExecution.methodRecognizers.strings; /*- * #%L * TSOpen - Open-source implementation of TriggerScope * * Paper describing the approach : https://seclab.ccs.neu.edu/static/publications/sp2016triggerscope.pdf * * %% * Copyright (C) 2019 Jordan Samhi * University of Luxembourg - Interdisciplinary Centre for * Security Reliability and Trust (SnT) - All rights reserved * * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.List; import lu.uni.tsopen.symbolicExecution.symbolicValues.SymbolicValue; import soot.SootMethod; import soot.Value; public interface StringMethodsRecognition { public List<SymbolicValue> recognizeStringMethod(SootMethod method, Value base, List<Value> args); public List<SymbolicValue> processStringMethod(SootMethod method, Value base, List<Value> args); }
1,498
35.560976
104
java
TSOpen
TSOpen-master/src/main/java/lu/uni/tsopen/symbolicExecution/methodRecognizers/strings/ToUpperCaseRecognition.java
package lu.uni.tsopen.symbolicExecution.methodRecognizers.strings; /*- * #%L * TSOpen - Open-source implementation of TriggerScope * * Paper describing the approach : https://seclab.ccs.neu.edu/static/publications/sp2016triggerscope.pdf * * %% * Copyright (C) 2019 Jordan Samhi * University of Luxembourg - Interdisciplinary Centre for * Security Reliability and Trust (SnT) - All rights reserved * * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.ArrayList; import java.util.List; import lu.uni.tsopen.symbolicExecution.SymbolicExecution; import lu.uni.tsopen.symbolicExecution.symbolicValues.SymbolicValue; import lu.uni.tsopen.utils.Constants; import lu.uni.tsopen.utils.Utils; import soot.SootMethod; import soot.Value; public class ToUpperCaseRecognition extends StringMethodsRecognitionHandler { public ToUpperCaseRecognition(StringMethodsRecognitionHandler next, SymbolicExecution se) { super(next, se); } @Override public List<SymbolicValue> processStringMethod(SootMethod method, Value base, List<Value> args) { List<SymbolicValue> results = new ArrayList<SymbolicValue>(); if(method.getName().equals(Constants.TO_UPPER_CASE)) { this.addSimpleResult(base, results); for(SymbolicValue sv : results) { Utils.propagateTags(base, sv, this.se); } return results; } return null; } }
2,008
31.934426
104
java
TSOpen
TSOpen-master/src/main/java/lu/uni/tsopen/symbolicExecution/methodRecognizers/strings/GetMessageBodyRecognition.java
package lu.uni.tsopen.symbolicExecution.methodRecognizers.strings; /*- * #%L * TSOpen - Open-source implementation of TriggerScope * * Paper describing the approach : https://seclab.ccs.neu.edu/static/publications/sp2016triggerscope.pdf * * %% * Copyright (C) 2019 Jordan Samhi * University of Luxembourg - Interdisciplinary Centre for * Security Reliability and Trust (SnT) - All rights reserved * * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.ArrayList; import java.util.List; import lu.uni.tsopen.symbolicExecution.SymbolicExecution; import lu.uni.tsopen.symbolicExecution.symbolicValues.MethodRepresentationValue; import lu.uni.tsopen.symbolicExecution.symbolicValues.SymbolicValue; import lu.uni.tsopen.utils.Constants; import soot.SootMethod; import soot.Value; import soot.tagkit.StringConstantValueTag; public class GetMessageBodyRecognition extends StringMethodsRecognitionHandler { public GetMessageBodyRecognition(StringMethodsRecognitionHandler next, SymbolicExecution se) { super(next, se); } @Override public List<SymbolicValue> processStringMethod(SootMethod method, Value base, List<Value> args) { List<SymbolicValue> results = new ArrayList<SymbolicValue>(); MethodRepresentationValue mrv = new MethodRepresentationValue(base, args, method, this.se); if(method.getName().equals(Constants.GET_MESSAGE_BODY) || method.getName().equals(Constants.GET_DISPLAY_MESSAGE_BODY)) { mrv.addTag(new StringConstantValueTag(Constants.SMS_BODY_TAG)); this.addResult(results, mrv); } return results; } }
2,221
36.661017
122
java
TSOpen
TSOpen-master/src/main/java/lu/uni/tsopen/symbolicExecution/methodRecognizers/strings/ValueOfRecognition.java
package lu.uni.tsopen.symbolicExecution.methodRecognizers.strings; /*- * #%L * TSOpen - Open-source implementation of TriggerScope * * Paper describing the approach : https://seclab.ccs.neu.edu/static/publications/sp2016triggerscope.pdf * * %% * Copyright (C) 2019 Jordan Samhi * University of Luxembourg - Interdisciplinary Centre for * Security Reliability and Trust (SnT) - All rights reserved * * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.ArrayList; import java.util.List; import lu.uni.tsopen.symbolicExecution.SymbolicExecution; import lu.uni.tsopen.symbolicExecution.symbolicValues.ConstantValue; import lu.uni.tsopen.symbolicExecution.symbolicValues.SymbolicValue; import lu.uni.tsopen.utils.Constants; import lu.uni.tsopen.utils.Utils; import soot.SootMethod; import soot.Value; import soot.jimple.Constant; public class ValueOfRecognition extends StringMethodsRecognitionHandler { public ValueOfRecognition(StringMethodsRecognitionHandler next, SymbolicExecution se) { super(next, se); } @Override public List<SymbolicValue> processStringMethod(SootMethod method, Value base, List<Value> args) { List<SymbolicValue> results = new ArrayList<SymbolicValue>(); Value effectiveArg = null; if(method.getName().equals(Constants.VALUEOF)) { effectiveArg = args.get(0); if(effectiveArg instanceof Constant) { results.add(new ConstantValue((Constant)effectiveArg, this.se)); }else { this.addSimpleResult(effectiveArg, results); for(SymbolicValue sv : results) { Utils.propagateTags(effectiveArg, sv, this.se); } } return results; } return null; } }
2,298
32.808824
104
java
TSOpen
TSOpen-master/src/main/java/lu/uni/tsopen/symbolicExecution/methodRecognizers/strings/GetOriginatingAddressRecognition.java
package lu.uni.tsopen.symbolicExecution.methodRecognizers.strings; /*- * #%L * TSOpen - Open-source implementation of TriggerScope * * Paper describing the approach : https://seclab.ccs.neu.edu/static/publications/sp2016triggerscope.pdf * * %% * Copyright (C) 2019 Jordan Samhi * University of Luxembourg - Interdisciplinary Centre for * Security Reliability and Trust (SnT) - All rights reserved * * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.ArrayList; import java.util.List; import lu.uni.tsopen.symbolicExecution.SymbolicExecution; import lu.uni.tsopen.symbolicExecution.symbolicValues.MethodRepresentationValue; import lu.uni.tsopen.symbolicExecution.symbolicValues.SymbolicValue; import lu.uni.tsopen.utils.Constants; import soot.SootMethod; import soot.Value; import soot.tagkit.StringConstantValueTag; public class GetOriginatingAddressRecognition extends StringMethodsRecognitionHandler { public GetOriginatingAddressRecognition(StringMethodsRecognitionHandler next, SymbolicExecution se) { super(next, se); } @Override public List<SymbolicValue> processStringMethod(SootMethod method, Value base, List<Value> args) { List<SymbolicValue> results = new ArrayList<SymbolicValue>(); MethodRepresentationValue mrv = new MethodRepresentationValue(base, args, method, this.se); if(method.getName().equals(Constants.GET_ORIGINATING_ADDRESS) || method.getName().equals(Constants.GET_DISPLAY_ORIGINATING_ADDRESS)) { mrv.addTag(new StringConstantValueTag(Constants.SMS_SENDER_TAG)); this.addResult(results, mrv); } return results; } }
2,252
36.55
136
java
TSOpen
TSOpen-master/src/main/java/lu/uni/tsopen/symbolicExecution/methodRecognizers/strings/AppendRecognition.java
package lu.uni.tsopen.symbolicExecution.methodRecognizers.strings; /*- * #%L * TSOpen - Open-source implementation of TriggerScope * * Paper describing the approach : https://seclab.ccs.neu.edu/static/publications/sp2016triggerscope.pdf * * %% * Copyright (C) 2019 Jordan Samhi * University of Luxembourg - Interdisciplinary Centre for * Security Reliability and Trust (SnT) - All rights reserved * * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.ArrayList; import java.util.List; import lu.uni.tsopen.symbolicExecution.ContextualValues; import lu.uni.tsopen.symbolicExecution.SymbolicExecution; import lu.uni.tsopen.symbolicExecution.symbolicValues.ConstantValue; import lu.uni.tsopen.symbolicExecution.symbolicValues.MethodRepresentationValue; import lu.uni.tsopen.symbolicExecution.symbolicValues.SymbolicValue; import lu.uni.tsopen.symbolicExecution.symbolicValues.UnknownValue; import lu.uni.tsopen.utils.Constants; import lu.uni.tsopen.utils.Utils; import soot.SootMethod; import soot.Value; import soot.jimple.Constant; import soot.jimple.StringConstant; public class AppendRecognition extends StringMethodsRecognitionHandler { public AppendRecognition(StringMethodsRecognitionHandler next, SymbolicExecution se) { super(next, se); } @Override public List<SymbolicValue> processStringMethod(SootMethod method, Value base, List<Value> args) { List<SymbolicValue> values = null; List<SymbolicValue> results = new ArrayList<SymbolicValue>(); ContextualValues contextualValuesOfBase = null; if(method.getName().equals(Constants.APPEND)) { contextualValuesOfBase = this.se.getContext().get(base); if(contextualValuesOfBase == null) { results.addAll(this.computeValue(new UnknownValue(this.se), args, base, method)); }else { values = contextualValuesOfBase.getLastCoherentValues(null); if(values != null) { for(SymbolicValue sv : values) { results.addAll(this.computeValue(sv, args, base, method)); } } } for(SymbolicValue sv : results) { Utils.propagateTags(base, sv, this.se); } return results; } return null; } private List<SymbolicValue> computeValue(SymbolicValue symVal, List<Value> args, Value base, SootMethod method) { List<SymbolicValue> results = new ArrayList<SymbolicValue>(); Value effectiveArg = args.get(0); ContextualValues contextualValuesOfBase = null; List<SymbolicValue> values = null; SymbolicValue object = null; if(effectiveArg instanceof Constant) { if(symVal.isConstant()) { object = new ConstantValue(StringConstant.v(String.format("%s%s", symVal, effectiveArg)), this.se); }else { object = new MethodRepresentationValue(base, args, method, this.se); } this.addResult(results, object); }else { contextualValuesOfBase = this.se.getContext().get(effectiveArg); if(contextualValuesOfBase == null) { if(symVal.isConstant()) { object = new ConstantValue(StringConstant.v(String.format("%s%s", symVal, Constants.UNKNOWN_STRING)), this.se); }else { object = new MethodRepresentationValue(base, args, method, this.se); } this.addResult(results, object); }else { values = contextualValuesOfBase.getLastCoherentValues(null); if(values != null) { for(SymbolicValue sv : values) { if(symVal.isConstant() && sv.isConstant()) { object = new ConstantValue(StringConstant.v(String.format("%s%s", symVal, sv)), this.se); }else { object = new MethodRepresentationValue(base, args, method, this.se); } this.addResult(results, object); } } } } for(SymbolicValue sv : results) { for(Value arg : args) { Utils.propagateTags(arg, sv, this.se); } } return results; } }
4,393
35.016393
116
java
TSOpen
TSOpen-master/src/main/java/lu/uni/tsopen/symbolicExecution/methodRecognizers/strings/ToStringRecognition.java
package lu.uni.tsopen.symbolicExecution.methodRecognizers.strings; /*- * #%L * TSOpen - Open-source implementation of TriggerScope * * Paper describing the approach : https://seclab.ccs.neu.edu/static/publications/sp2016triggerscope.pdf * * %% * Copyright (C) 2019 Jordan Samhi * University of Luxembourg - Interdisciplinary Centre for * Security Reliability and Trust (SnT) - All rights reserved * * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.ArrayList; import java.util.List; import lu.uni.tsopen.symbolicExecution.SymbolicExecution; import lu.uni.tsopen.symbolicExecution.symbolicValues.SymbolicValue; import lu.uni.tsopen.utils.Constants; import lu.uni.tsopen.utils.Utils; import soot.SootMethod; import soot.Value; public class ToStringRecognition extends StringMethodsRecognitionHandler { public ToStringRecognition(StringMethodsRecognitionHandler next, SymbolicExecution se) { super(next, se); } @Override public List<SymbolicValue> processStringMethod(SootMethod method, Value base, List<Value> args) { List<SymbolicValue> results = new ArrayList<SymbolicValue>(); if(method.getName().equals(Constants.TOSTRING)) { this.addSimpleResult(base, results); for(SymbolicValue sv : results) { Utils.propagateTags(base, sv, this.se); } return results; } return null; } }
1,997
31.754098
104
java
TSOpen
TSOpen-master/src/main/java/lu/uni/tsopen/symbolicExecution/methodRecognizers/strings/StringMethodsRecognitionHandler.java
package lu.uni.tsopen.symbolicExecution.methodRecognizers.strings; /*- * #%L * TSOpen - Open-source implementation of TriggerScope * * Paper describing the approach : https://seclab.ccs.neu.edu/static/publications/sp2016triggerscope.pdf * * %% * Copyright (C) 2019 Jordan Samhi * University of Luxembourg - Interdisciplinary Centre for * Security Reliability and Trust (SnT) - All rights reserved * * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import lu.uni.tsopen.symbolicExecution.ContextualValues; import lu.uni.tsopen.symbolicExecution.SymbolicExecution; import lu.uni.tsopen.symbolicExecution.symbolicValues.SymbolicValue; import lu.uni.tsopen.symbolicExecution.symbolicValues.UnknownValue; import soot.SootMethod; import soot.Value; public abstract class StringMethodsRecognitionHandler implements StringMethodsRecognition { protected Logger logger = LoggerFactory.getLogger(this.getClass()); private StringMethodsRecognitionHandler next; protected SymbolicExecution se; public StringMethodsRecognitionHandler(StringMethodsRecognitionHandler next, SymbolicExecution se) { this.next = next; this.se = se; } @Override public List<SymbolicValue> recognizeStringMethod(SootMethod method, Value base, List<Value> args) { List<SymbolicValue> result = this.processStringMethod(method, base, args); if(result != null && !result.isEmpty()) { return result; } if(this.next != null) { return this.next.recognizeStringMethod(method, base, args); } else { return null; } } protected void addSimpleResult(Value v, List<SymbolicValue> results) { ContextualValues contextualValues = this.se.getContext().get(v); List<SymbolicValue> values = null; if(contextualValues == null) { results.add(new UnknownValue(this.se)); }else { values = contextualValues.getLastCoherentValues(null); if(values != null) { for(SymbolicValue sv : values) { this.addResult(results, sv); } } } } protected void addResult(List<SymbolicValue> results, SymbolicValue object) { for(SymbolicValue sv : results) { if(sv.toString().equals(object.toString())) { return; } } results.add(object); } }
2,909
30.290323
104
java
TSOpen
TSOpen-master/src/main/java/lu/uni/tsopen/symbolicExecution/methodRecognizers/strings/ToLowerCaseRecognition.java
package lu.uni.tsopen.symbolicExecution.methodRecognizers.strings; /*- * #%L * TSOpen - Open-source implementation of TriggerScope * * Paper describing the approach : https://seclab.ccs.neu.edu/static/publications/sp2016triggerscope.pdf * * %% * Copyright (C) 2019 Jordan Samhi * University of Luxembourg - Interdisciplinary Centre for * Security Reliability and Trust (SnT) - All rights reserved * * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.ArrayList; import java.util.List; import lu.uni.tsopen.symbolicExecution.SymbolicExecution; import lu.uni.tsopen.symbolicExecution.symbolicValues.SymbolicValue; import lu.uni.tsopen.utils.Constants; import lu.uni.tsopen.utils.Utils; import soot.SootMethod; import soot.Value; public class ToLowerCaseRecognition extends StringMethodsRecognitionHandler { public ToLowerCaseRecognition(StringMethodsRecognitionHandler next, SymbolicExecution se) { super(next, se); } @Override public List<SymbolicValue> processStringMethod(SootMethod method, Value base, List<Value> args) { List<SymbolicValue> results = new ArrayList<SymbolicValue>(); if(method.getName().equals(Constants.TO_LOWER_CASE)) { this.addSimpleResult(base, results); for(SymbolicValue sv : results) { Utils.propagateTags(base, sv, this.se); } return results; } return null; } }
2,008
31.934426
104
java
null
tmVar3-main/src/tmVarlib/MentionRecognition.java
// // tmVar - Java version // Feature Extraction // package tmVarlib; import java.io.*; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.tartarus.snowball.SnowballStemmer; import org.tartarus.snowball.ext.englishStemmer; import edu.stanford.nlp.tagger.maxent.MaxentTagger; public class MentionRecognition { public void FeatureExtraction(String Filename,String FilenameData,String FilenameLoca,String TrainTest) { /* * Feature Extraction */ try { //input BufferedReader inputfile = new BufferedReader(new InputStreamReader(new FileInputStream(Filename), "UTF-8")); //output BufferedWriter FileLocation = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(FilenameLoca), "UTF-8")); // .location BufferedWriter FileData = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(FilenameData), "UTF-8")); // .data //parameters String Pmid=""; ArrayList<String> ParagraphType=new ArrayList<String>(); // Type: Title|Abstract ArrayList<String> ParagraphContent = new ArrayList<String>(); // Text ArrayList<String> annotations = new ArrayList<String>(); // Annotation HashMap<Integer, String> RegEx_HGVs_hash = new HashMap<Integer, String>(); // RegEx_HGVs_hash HashMap<Integer, String> character_hash = new HashMap<Integer, String>(); String line; while ((line = inputfile.readLine()) != null) { Pattern pat = Pattern.compile("^([^\\|\\t]+)\\|([^\\|\\t]+)\\|(.*)$"); Matcher mat = pat.matcher(line); if(mat.find()) //Title|Abstract { Pmid = mat.group(1); ParagraphType.add(mat.group(2)); ParagraphContent.add(mat.group(3)); } else if (line.contains("\t")) //Annotation { String anno[]=line.split("\t"); if(anno.length>=6) { String mentiontype=anno[4]; if(mentiontype.equals("Gene")) { tmVar.GeneMention=true; } if(TrainTest.equals("Train")) { int start= Integer.parseInt(anno[1]); int last= Integer.parseInt(anno[2]); String mention=anno[3]; String component=anno[5]; Matcher m1 = tmVar.Pattern_Component_1.matcher(component); Matcher m2 = tmVar.Pattern_Component_2.matcher(component); Matcher m3 = tmVar.Pattern_Component_3.matcher(component); Matcher m4 = tmVar.Pattern_Component_4.matcher(component); Matcher m5 = tmVar.Pattern_Component_5.matcher(component); Matcher m6 = tmVar.Pattern_Component_6.matcher(component); for(int s=start;s<last;s++) { character_hash.put(s,"I"); } if(m1.find()) { String type[]=m1.group(1).split(","); String W[]=m1.group(2).split(","); String P[]=m1.group(3).split(","); String M[]=m1.group(4).split(","); String F[]=m1.group(5).split(","); String S[]=m1.group(6).split(","); String mention_tmp=mention; for(int i=0;i<type.length;i++) { type[i]=type[i].replaceAll("([^A-Za-z0-9@])", "\\\\$1"); String patt="^(.*?)("+type[i]+")(.*?)$"; Pattern ptmp = Pattern.compile(patt); Matcher mtmp = ptmp.matcher(mention_tmp); if(mtmp.find()) { for(int j=mtmp.group(1).length();j<(mtmp.group(1).length()+mtmp.group(2).length());j++) { character_hash.put(j+start,"A"); } String mtmp2_tmp=""; for(int j=0;j<mtmp.group(2).length();j++){mtmp2_tmp=mtmp2_tmp+"@";} mention_tmp=mtmp.group(1)+mtmp2_tmp+mtmp.group(3); } else { System.out.println("Error! Cannot find component: m1\ttype\t"+Pmid+"\t"+mention); } } for(int i=0;i<W.length;i++) { W[i]=W[i].replaceAll("([^A-Za-z0-9@])", "\\\\$1"); String patt="^(.*?)("+W[i]+")(.*?)$"; Pattern ptmp = Pattern.compile(patt); Matcher mtmp = ptmp.matcher(mention_tmp); if(mtmp.find()) { for(int j=mtmp.group(1).length();j<(mtmp.group(1).length()+mtmp.group(2).length());j++) { character_hash.put(j+start,"W"); } String mtmp2_tmp=""; for(int j=0;j<mtmp.group(2).length();j++){mtmp2_tmp=mtmp2_tmp+"@";} mention_tmp=mtmp.group(1)+mtmp2_tmp+mtmp.group(3); } else { System.out.println("Error! Cannot find component: m1\tW\t"+Pmid+"\t"+mention); } } for(int i=0;i<P.length;i++) { P[i]=P[i].replaceAll("([^A-Za-z0-9@])", "\\\\$1"); String patt="^(.*?)("+P[i]+")(.*?)$"; Pattern ptmp = Pattern.compile(patt); Matcher mtmp = ptmp.matcher(mention_tmp); if(mtmp.find()) { for(int j=mtmp.group(1).length();j<(mtmp.group(1).length()+mtmp.group(2).length());j++) { character_hash.put(j+start,"P"); } String mtmp2_tmp=""; for(int j=0;j<mtmp.group(2).length();j++){mtmp2_tmp=mtmp2_tmp+"@";} mention_tmp=mtmp.group(1)+mtmp2_tmp+mtmp.group(3); } else { System.out.println("Error! Cannot find component: m1\tP\t"+Pmid+"\t"+mention); } } for(int i=0;i<M.length;i++) { M[i]=M[i].replaceAll("([^A-Za-z0-9@])", "\\\\$1"); String patt="^(.*?)("+M[i]+")(.*?)$"; Pattern ptmp = Pattern.compile(patt); Matcher mtmp = ptmp.matcher(mention_tmp); if(mtmp.find()) { for(int j=mtmp.group(1).length();j<(mtmp.group(1).length()+mtmp.group(2).length());j++) { character_hash.put(j+start,"M"); } String mtmp2_tmp=""; for(int j=0;j<mtmp.group(2).length();j++){mtmp2_tmp=mtmp2_tmp+"@";} mention_tmp=mtmp.group(1)+mtmp2_tmp+mtmp.group(3); } else { System.out.println("Error! Cannot find component: m1\tM\t"+Pmid+"\t"+mention); } } for(int i=0;i<F.length;i++) { F[i]=F[i].replaceAll("([^A-Za-z0-9@])", "\\\\$1"); String patt="^(.*?)("+F[i]+")(.*?)$"; Pattern ptmp = Pattern.compile(patt); Matcher mtmp = ptmp.matcher(mention_tmp); if(mtmp.find()) { for(int j=mtmp.group(1).length();j<(mtmp.group(1).length()+mtmp.group(2).length());j++) { character_hash.put(j+start,"F"); } String mtmp2_tmp=""; for(int j=0;j<mtmp.group(2).length();j++){mtmp2_tmp=mtmp2_tmp+"@";} mention_tmp=mtmp.group(1)+mtmp2_tmp+mtmp.group(3); } else { System.out.println("Error! Cannot find component: m1\tF\t"+Pmid+"\t"+mention); } } for(int i=0;i<S.length;i++) { S[i]=S[i].replaceAll("([^A-Za-z0-9@])", "\\\\$1"); String patt="^(.*?)("+S[i]+")(.*?)$"; Pattern ptmp = Pattern.compile(patt); Matcher mtmp = ptmp.matcher(mention_tmp); if(mtmp.find()) { for(int j=mtmp.group(1).length();j<(mtmp.group(1).length()+mtmp.group(2).length());j++) { character_hash.put(j+start,"S"); } String mtmp2_tmp=""; for(int j=0;j<mtmp.group(2).length();j++){mtmp2_tmp=mtmp2_tmp+"@";} mention_tmp=mtmp.group(1)+mtmp2_tmp+mtmp.group(3); } else { System.out.println("Error! Cannot find component: m1\tS\t"+Pmid+"\t"+mention); } } } else if(m2.find()) { String type[]=m2.group(1).split(","); String W[]=m2.group(2).split(","); String P[]=m2.group(3).split(","); String M[]=m2.group(4).split(","); String F[]=m2.group(5).split(","); String mention_tmp=mention; for(int i=0;i<type.length;i++) { type[i]=type[i].replaceAll("([^A-Za-z0-9@])", "\\\\$1"); String patt="^(.*?)("+type[i]+")(.*?)$"; Pattern ptmp = Pattern.compile(patt); Matcher mtmp = ptmp.matcher(mention_tmp); if(mtmp.find()) { for(int j=mtmp.group(1).length();j<(mtmp.group(1).length()+mtmp.group(2).length());j++) { character_hash.put(j+start,"A"); } String mtmp2_tmp=""; for(int j=0;j<mtmp.group(2).length();j++){mtmp2_tmp=mtmp2_tmp+"@";} mention_tmp=mtmp.group(1)+mtmp2_tmp+mtmp.group(3); } else { System.out.println("Error! Cannot find component: m2\tType\t"+Pmid+"\t"+mention); } } for(int i=0;i<W.length;i++) { W[i]=W[i].replaceAll("([^A-Za-z0-9@])", "\\\\$1"); String patt="^(.*?)("+W[i]+")(.*?)$"; Pattern ptmp = Pattern.compile(patt); Matcher mtmp = ptmp.matcher(mention_tmp); if(mtmp.find()) { for(int j=mtmp.group(1).length();j<(mtmp.group(1).length()+mtmp.group(2).length());j++) { character_hash.put(j+start,"W"); } String mtmp2_tmp=""; for(int j=0;j<mtmp.group(2).length();j++){mtmp2_tmp=mtmp2_tmp+"@";} mention_tmp=mtmp.group(1)+mtmp2_tmp+mtmp.group(3); } else { System.out.println("Error! Cannot find component: m2\tW\t"+Pmid+"\t"+mention); } } for(int i=0;i<P.length;i++) { P[i]=P[i].replaceAll("([^A-Za-z0-9@])", "\\\\$1"); String patt="^(.*?)("+P[i]+")(.*?)$"; Pattern ptmp = Pattern.compile(patt); Matcher mtmp = ptmp.matcher(mention_tmp); if(mtmp.find()) { for(int j=mtmp.group(1).length();j<(mtmp.group(1).length()+mtmp.group(2).length());j++) { character_hash.put(j+start,"P"); } String mtmp2_tmp=""; for(int j=0;j<mtmp.group(2).length();j++){mtmp2_tmp=mtmp2_tmp+"@";} mention_tmp=mtmp.group(1)+mtmp2_tmp+mtmp.group(3); } else { System.out.println("Error! Cannot find component: m2\tP\t"+Pmid+"\t"+mention); } } for(int i=0;i<M.length;i++) { M[i]=M[i].replaceAll("([^A-Za-z0-9@])", "\\\\$1"); String patt="^(.*?)("+M[i]+")(.*?)$"; Pattern ptmp = Pattern.compile(patt); Matcher mtmp = ptmp.matcher(mention_tmp); if(mtmp.find()) { for(int j=mtmp.group(1).length();j<(mtmp.group(1).length()+mtmp.group(2).length());j++) { character_hash.put(j+start,"M"); } String mtmp2_tmp=""; for(int j=0;j<mtmp.group(2).length();j++){mtmp2_tmp=mtmp2_tmp+"@";} mention_tmp=mtmp.group(1)+mtmp2_tmp+mtmp.group(3); } else { System.out.println("Error! Cannot find component: m2\tM\t"+Pmid+"\t"+mention); } } for(int i=0;i<F.length;i++) { F[i]=F[i].replaceAll("([^A-Za-z0-9@])", "\\\\$1"); String patt="^(.*?)("+F[i]+")(.*?)$"; Pattern ptmp = Pattern.compile(patt); Matcher mtmp = ptmp.matcher(mention_tmp); if(mtmp.find()) { for(int j=mtmp.group(1).length();j<(mtmp.group(1).length()+mtmp.group(2).length());j++) { character_hash.put(j+start,"F"); } String mtmp2_tmp=""; for(int j=0;j<mtmp.group(2).length();j++){mtmp2_tmp=mtmp2_tmp+"@";} mention_tmp=mtmp.group(1)+mtmp2_tmp+mtmp.group(3); } else { System.out.println("Error! Cannot find component: m2\tF\t"+Pmid+"\t"+mention); } } } else if(m3.find()) { String type[]=m3.group(1).split(","); String T[]=m3.group(2).split(","); String P[]=m3.group(4).split(","); String M[]=m3.group(5).split(","); String mention_tmp=mention; for(int i=0;i<type.length;i++) { type[i]=type[i].replaceAll("([^A-Za-z0-9@])", "\\\\$1"); String patt="^(.*?)("+type[i]+")(.*?)$"; Pattern ptmp = Pattern.compile(patt); Matcher mtmp = ptmp.matcher(mention_tmp); if(mtmp.find()) { for(int j=mtmp.group(1).length();j<(mtmp.group(1).length()+mtmp.group(2).length());j++) { character_hash.put(j+start,"A"); } String mtmp2_tmp=""; for(int j=0;j<mtmp.group(2).length();j++){mtmp2_tmp=mtmp2_tmp+"@";} mention_tmp=mtmp.group(1)+mtmp2_tmp+mtmp.group(3); } else { System.out.println("Error! Cannot find component: m3\tType\t"+Pmid+"\t"+mention); } } for(int i=0;i<P.length;i++) { P[i]=P[i].replaceAll("([^A-Za-z0-9@])", "\\\\$1"); String patt="^(.*?)("+P[i]+")(.*?)$"; Pattern ptmp = Pattern.compile(patt); Matcher mtmp = ptmp.matcher(mention_tmp); if(mtmp.find()) { for(int j=mtmp.group(1).length();j<(mtmp.group(1).length()+mtmp.group(2).length());j++) { character_hash.put(j+start,"P"); } String mtmp2_tmp=""; for(int j=0;j<mtmp.group(2).length();j++){mtmp2_tmp=mtmp2_tmp+"@";} mention_tmp=mtmp.group(1)+mtmp2_tmp+mtmp.group(3); } else { System.out.println("Error! Cannot find component: m3\tP\t"+Pmid+"\t"+mention); } } for(int i=0;i<T.length;i++) { T[i]=T[i].replaceAll("([^A-Za-z0-9@])", "\\\\$1"); String patt="^(.*?)("+T[i]+")(.*?)$"; Pattern ptmp = Pattern.compile(patt); Matcher mtmp = ptmp.matcher(mention_tmp); if(mtmp.find()) { for(int j=mtmp.group(1).length();j<(mtmp.group(1).length()+mtmp.group(2).length());j++) { character_hash.put(j+start,"T"); } String mtmp2_tmp=""; for(int j=0;j<mtmp.group(2).length();j++){mtmp2_tmp=mtmp2_tmp+"@";} mention_tmp=mtmp.group(1)+mtmp2_tmp+mtmp.group(3); } else { System.out.println("Error! Cannot find component: m3\tT\t"+Pmid+"\t"+mention); } } for(int i=0;i<M.length;i++) { M[i]=M[i].replaceAll("([^A-Za-z0-9@])", "\\\\$1"); String patt="^(.*?)("+M[i]+")(.*?)$"; Pattern ptmp = Pattern.compile(patt); Matcher mtmp = ptmp.matcher(mention_tmp); if(mtmp.find()) { for(int j=mtmp.group(1).length();j<(mtmp.group(1).length()+mtmp.group(2).length());j++) { character_hash.put(j+start,"M"); } String mtmp2_tmp=""; for(int j=0;j<mtmp.group(2).length();j++){mtmp2_tmp=mtmp2_tmp+"@";} mention_tmp=mtmp.group(1)+mtmp2_tmp+mtmp.group(3); } else { System.out.println("Error! Cannot find component: m3\tM\t"+Pmid+"\t"+mention); } } } else if(m4.find()) { String type[]=m4.group(1).split(","); String W[]=m4.group(2).split(","); String P[]=m4.group(3).split(","); String M[]=m4.group(4).split(","); String mention_tmp=mention; for(int i=0;i<type.length;i++) { type[i]=type[i].replaceAll("([^A-Za-z0-9@])", "\\\\$1"); String patt="^(.*?)("+type[i]+")(.*?)$"; Pattern ptmp = Pattern.compile(patt); Matcher mtmp = ptmp.matcher(mention_tmp); if(mtmp.find()) { for(int j=mtmp.group(1).length();j<(mtmp.group(1).length()+mtmp.group(2).length());j++) { character_hash.put(j+start,"A"); } String mtmp2_tmp=""; for(int j=0;j<mtmp.group(2).length();j++){mtmp2_tmp=mtmp2_tmp+"@";} mention_tmp=mtmp.group(1)+mtmp2_tmp+mtmp.group(3); } else { System.out.println("Error! Cannot find component: m4\tType\t"+Pmid+"\t"+mention); } } for(int i=0;i<W.length;i++) { W[i]=W[i].replaceAll("([^A-Za-z0-9@])", "\\\\$1"); String patt="^(.*?)("+W[i]+")(.*?)$"; Pattern ptmp = Pattern.compile(patt); Matcher mtmp = ptmp.matcher(mention_tmp); if(mtmp.find()) { for(int j=mtmp.group(1).length();j<(mtmp.group(1).length()+mtmp.group(2).length());j++) { character_hash.put(j+start,"W"); } String mtmp2_tmp=""; for(int j=0;j<mtmp.group(2).length();j++){mtmp2_tmp=mtmp2_tmp+"@";} mention_tmp=mtmp.group(1)+mtmp2_tmp+mtmp.group(3); } else { System.out.println("Error! Cannot find component: m4\tW\t"+Pmid+"\t"+mention); } } for(int i=0;i<P.length;i++) { P[i]=P[i].replaceAll("([^A-Za-z0-9@])", "\\\\$1"); String patt="^(.*?)("+P[i]+")(.*?)$"; Pattern ptmp = Pattern.compile(patt); Matcher mtmp = ptmp.matcher(mention_tmp); if(mtmp.find()) { for(int j=mtmp.group(1).length();j<(mtmp.group(1).length()+mtmp.group(2).length());j++) { character_hash.put(j+start,"P"); } String mtmp2_tmp=""; for(int j=0;j<mtmp.group(2).length();j++){mtmp2_tmp=mtmp2_tmp+"@";} mention_tmp=mtmp.group(1)+mtmp2_tmp+mtmp.group(3); } else { System.out.println("Error! Cannot find component: m4\tP\t"+Pmid+"\t"+mention); } } for(int i=0;i<M.length;i++) { M[i]=M[i].replaceAll("([^A-Za-z0-9@])", "\\\\$1"); String patt="^(.*?)("+M[i]+")(.*?)$"; Pattern ptmp = Pattern.compile(patt); Matcher mtmp = ptmp.matcher(mention_tmp); if(mtmp.find()) { for(int j=mtmp.group(1).length();j<(mtmp.group(1).length()+mtmp.group(2).length());j++) { character_hash.put(j+start,"M"); } String mtmp2_tmp=""; for(int j=0;j<mtmp.group(2).length();j++){mtmp2_tmp=mtmp2_tmp+"@";} mention_tmp=mtmp.group(1)+mtmp2_tmp+mtmp.group(3); } else { System.out.println("Error! Cannot find component: m4\tM\t"+Pmid+"\t"+mention); } } } else if(m5.find()) { String type[]=m5.group(1).split(","); String T[]=m5.group(2).split(","); String P[]=m5.group(3).split(","); String M[]=m5.group(4).split(","); String D[]=m5.group(5).split(","); String mention_tmp=mention; for(int i=0;i<type.length;i++) { type[i]=type[i].replaceAll("([^A-Za-z0-9@])", "\\\\$1"); String patt="^(.*?)("+type[i]+")(.*?)$"; Pattern ptmp = Pattern.compile(patt); Matcher mtmp = ptmp.matcher(mention_tmp); if(mtmp.find()) { for(int j=mtmp.group(1).length();j<(mtmp.group(1).length()+mtmp.group(2).length());j++) { character_hash.put(j+start,"A"); } String mtmp2_tmp=""; for(int j=0;j<mtmp.group(2).length();j++){mtmp2_tmp=mtmp2_tmp+"@";} mention_tmp=mtmp.group(1)+mtmp2_tmp+mtmp.group(3); } else { System.out.println("Error! Cannot find component: m5\tType\t"+Pmid+"\t"+mention); } } for(int i=0;i<T.length;i++) { T[i]=T[i].replaceAll("([^A-Za-z0-9@])", "\\\\$1"); String patt="^(.*?)("+T[i]+")(.*?)$"; Pattern ptmp = Pattern.compile(patt); Matcher mtmp = ptmp.matcher(mention_tmp); if(mtmp.find()) { for(int j=mtmp.group(1).length();j<(mtmp.group(1).length()+mtmp.group(2).length());j++) { character_hash.put(j+start,"T"); } String mtmp2_tmp=""; for(int j=0;j<mtmp.group(2).length();j++){mtmp2_tmp=mtmp2_tmp+"@";} mention_tmp=mtmp.group(1)+mtmp2_tmp+mtmp.group(3); } else { System.out.println("Error! Cannot find component: m5\tT\t"+Pmid+"\t"+mention); } } for(int i=0;i<P.length;i++) { P[i]=P[i].replaceAll("([^A-Za-z0-9@])", "\\\\$1"); String patt="^(.*?)("+P[i]+")(.*?)$"; Pattern ptmp = Pattern.compile(patt); Matcher mtmp = ptmp.matcher(mention_tmp); if(mtmp.find()) { for(int j=mtmp.group(1).length();j<(mtmp.group(1).length()+mtmp.group(2).length());j++) { character_hash.put(j+start,"P"); } String mtmp2_tmp=""; for(int j=0;j<mtmp.group(2).length();j++){mtmp2_tmp=mtmp2_tmp+"@";} mention_tmp=mtmp.group(1)+mtmp2_tmp+mtmp.group(3); } else { System.out.println("Error! Cannot find component: m5\tP\t"+Pmid+"\t"+mention); } } for(int i=0;i<M.length;i++) { M[i]=M[i].replaceAll("([^A-Za-z0-9@])", "\\\\$1"); String patt="^(.*?)("+M[i]+")(.*?)$"; Pattern ptmp = Pattern.compile(patt); Matcher mtmp = ptmp.matcher(mention_tmp); if(mtmp.find()) { for(int j=mtmp.group(1).length();j<(mtmp.group(1).length()+mtmp.group(2).length());j++) { character_hash.put(j+start,"M"); } String mtmp2_tmp=""; for(int j=0;j<mtmp.group(2).length();j++){mtmp2_tmp=mtmp2_tmp+"@";} mention_tmp=mtmp.group(1)+mtmp2_tmp+mtmp.group(3); } else { System.out.println("Error! Cannot find component: m5\tM\t"+Pmid+"\t"+mention); } } for(int i=0;i<D.length;i++) { D[i]=D[i].replaceAll("([^A-Za-z0-9@])", "\\\\$1"); String patt="^(.*?)("+D[i]+")(.*?)$"; Pattern ptmp = Pattern.compile(patt); Matcher mtmp = ptmp.matcher(mention_tmp); if(mtmp.find()) { for(int j=mtmp.group(1).length();j<(mtmp.group(1).length()+mtmp.group(2).length());j++) { character_hash.put(j+start,"D"); } String mtmp2_tmp=""; for(int j=0;j<mtmp.group(2).length();j++){mtmp2_tmp=mtmp2_tmp+"@";} mention_tmp=mtmp.group(1)+mtmp2_tmp+mtmp.group(3); } else { System.out.println("Error! Cannot find component: m5\tD\t"+Pmid+"\t"+mention); } } } else if(m6.find()) { String RS[]=m6.group(1).split(","); String mention_tmp=mention; for(int i=0;i<RS.length;i++) { RS[i]=RS[i].replaceAll("([\\[\\]])", "\\\\$1"); String patt="^(.*?)("+RS[i]+")(.*?)$"; Pattern ptmp = Pattern.compile(patt); Matcher mtmp = ptmp.matcher(mention_tmp); if(mtmp.find()) { for(int j=mtmp.group(1).length();j<(mtmp.group(1).length()+mtmp.group(2).length());j++) { character_hash.put(j+start,"R"); } String mtmp2_tmp=""; for(int j=0;j<mtmp.group(2).length();j++){mtmp2_tmp=mtmp2_tmp+"@";} mention_tmp=mtmp.group(1)+mtmp2_tmp+mtmp.group(3); } else { System.out.println("Error! Cannot find component: m6\tType\t"+Pmid+"\t"+mention); } } } else { System.out.println("Error! Annotation component cannot match RegEx. " + mention); } annotations.add(anno[1]+"\t"+anno[2]+"\t"+anno[3]+"\t"+anno[4]+"\t"+anno[5]); } } //else //{ // System.out.println("Error! annotation column is less than 6: "+line); //} } else if(line.length()==0) //Processing { String Document=""; for(int i=0;i<ParagraphContent.size();i++) { Document=Document+ParagraphContent.get(i)+" "; } String Document_rev=Document; /* * RegEx result of ProteinMutation - Post is group(5) */ for(int i=0;i<tmVar.RegEx_ProteinMutation_STR.size();i++) { Pattern PATTERN_RegEx_HGVs = Pattern.compile(tmVar.RegEx_ProteinMutation_STR.get(i)); Matcher m = PATTERN_RegEx_HGVs.matcher(Document_rev); while (m.find()) { String pre = m.group(1); String mention = m.group(2); String post = m.group(5); { Pattern ptmp = Pattern.compile("^(.+)([ ;.,:]+)$"); Matcher mtmp = ptmp.matcher(mention); if(mtmp.find()) { mention=mtmp.group(1); post=mtmp.group(2)+post; } if((!mention.contains("(")) && mention.substring(mention.length()-1,mention.length()).equals(")")){ mention=mention.substring(0,mention.length()-1);post=")"+post;} if((!mention.contains("[")) && mention.substring(mention.length()-1,mention.length()).equals("]")){ mention=mention.substring(0,mention.length()-1);post="]"+post;} if((!mention.contains("{")) && mention.substring(mention.length()-1,mention.length()).equals("}")){ mention=mention.substring(0,mention.length()-1);post="}"+post;} int start=pre.length(); int last=pre.length()+mention.length(); for(int j=start;j<last;j++) { RegEx_HGVs_hash.put(j,"ProteinMutation"); } String mention_rev=""; for(int j=0;j<mention.length();j++){mention_rev=mention_rev+"@";} Document_rev=pre+mention_rev+post; } PATTERN_RegEx_HGVs = Pattern.compile(tmVar.RegEx_ProteinMutation_STR.get(i)); m = PATTERN_RegEx_HGVs.matcher(Document_rev); } } /* * RegEx result of DNAMutation - Post is group(4) */ for(int i=0;i<tmVar.RegEx_DNAMutation_STR.size();i++) { Pattern PATTERN_RegEx_HGVs = Pattern.compile(tmVar.RegEx_DNAMutation_STR.get(i)); Matcher m = PATTERN_RegEx_HGVs.matcher(Document_rev); while (m.find()) { String pre = m.group(1); String mention = m.group(2); String post = m.group(4); //Pattern pCheck = Pattern.compile("^[cgr][^0-9a-zA-Z]*.[^0-9a-zA-Z]*[0-9]+[^0-9a-zA-Z]*$"); //Matcher mCheck = pCheck.matcher(mention); //if(!mCheck.find()) { Pattern ptmp = Pattern.compile("^(.+)([ ;.,:]+)$"); Matcher mtmp = ptmp.matcher(mention); if(mtmp.find()) { mention=mtmp.group(1); post=mtmp.group(2)+post; } if((!mention.contains("(")) && mention.substring(mention.length()-1,mention.length()).equals(")")){ mention=mention.substring(0,mention.length()-1);post=")"+post;} if((!mention.contains("[")) && mention.substring(mention.length()-1,mention.length()).equals("]")){ mention=mention.substring(0,mention.length()-1);post="]"+post;} if((!mention.contains("{")) && mention.substring(mention.length()-1,mention.length()).equals("}")){ mention=mention.substring(0,mention.length()-1);post="}"+post;} int start=pre.length(); int last=pre.length()+mention.length(); for(int j=start;j<last;j++) { RegEx_HGVs_hash.put(j,"DNAMutation"); } String mention_rev=""; for(int j=0;j<mention.length();j++){mention_rev=mention_rev+"@";} Document_rev=pre+mention_rev+post; } PATTERN_RegEx_HGVs = Pattern.compile(tmVar.RegEx_DNAMutation_STR.get(i)); m = PATTERN_RegEx_HGVs.matcher(Document_rev); } } /* * RegEx result of SNP */ for(int i=0;i<tmVar.RegEx_SNP_STR.size();i++) { Pattern PATTERN_RegEx_HGVs = Pattern.compile(tmVar.RegEx_SNP_STR.get(i)); Matcher m = PATTERN_RegEx_HGVs.matcher(Document_rev); while (m.find()) { String pre = m.group(1); String mention = m.group(2); String post = m.group(4); { Pattern ptmp = Pattern.compile("^(.+)([ ;.,:]+)$"); Matcher mtmp = ptmp.matcher(mention); if(mtmp.find()) { mention=mtmp.group(1); post=mtmp.group(2)+post; } if((!mention.contains("(")) && mention.substring(mention.length()-1,mention.length()).equals(")")){ mention=mention.substring(0,mention.length()-1);post=")"+post;} if((!mention.contains("[")) && mention.substring(mention.length()-1,mention.length()).equals("]")){ mention=mention.substring(0,mention.length()-1);post="]"+post;} if((!mention.contains("{")) && mention.substring(mention.length()-1,mention.length()).equals("}")){ mention=mention.substring(0,mention.length()-1);post="}"+post;} int start=pre.length(); int last=pre.length()+mention.length(); for(int j=start;j<last;j++) { RegEx_HGVs_hash.put(j,"SNP"); } String mention_rev=""; for(int j=0;j<mention.length();j++){mention_rev=mention_rev+"@";} Document_rev=pre+mention_rev+post; } PATTERN_RegEx_HGVs = Pattern.compile(tmVar.RegEx_SNP_STR.get(i)); m = PATTERN_RegEx_HGVs.matcher(Document_rev); } } /* * Tokenization for .location */ Document_rev=Document; Document_rev = Document_rev.replaceAll("([A-Z][A-Z])([A-Z][0-9][0-9]+[A-Z][\\W\\-\\_])", "$1 $2"); //PTENK289E Document_rev = Document_rev.replaceAll("([0-9])([A-Za-z])", "$1 $2"); Document_rev = Document_rev.replaceAll("([A-Za-z])([0-9])", "$1 $2"); Document_rev = Document_rev.replaceAll("([A-Z])([a-z])", "$1 $2"); Document_rev = Document_rev.replaceAll("([a-z])([A-Z])", "$1 $2"); Document_rev = Document_rev.replaceAll("(.+)fs", "$1 fs"); Document_rev = Document_rev.replaceAll("[\t ]+", " "); String regex="\\s+|(?=\\p{Punct})|(?<=\\p{Punct})"; String TokensInDoc[]=Document_rev.split(regex); String DocumentTmp=Document; int Offset=0; Document_rev = Document_rev.replaceAll("ω","w"); Document_rev = Document_rev.replaceAll("μ","u"); Document_rev = Document_rev.replaceAll("κ","k"); Document_rev = Document_rev.replaceAll("α","a"); Document_rev = Document_rev.replaceAll("γ","r"); Document_rev = Document_rev.replaceAll("β","b"); Document_rev = Document_rev.replaceAll("×","x"); Document_rev = Document_rev.replaceAll("¹","1"); Document_rev = Document_rev.replaceAll("²","2"); Document_rev = Document_rev.replaceAll("°","o"); Document_rev = Document_rev.replaceAll("ö","o"); Document_rev = Document_rev.replaceAll("é","e"); Document_rev = Document_rev.replaceAll("à","a"); Document_rev = Document_rev.replaceAll("Á","A"); Document_rev = Document_rev.replaceAll("ε","e"); Document_rev = Document_rev.replaceAll("θ","O"); Document_rev = Document_rev.replaceAll("•","."); Document_rev = Document_rev.replaceAll("µ","u"); Document_rev = Document_rev.replaceAll("λ","r"); Document_rev = Document_rev.replaceAll("⁺","+"); Document_rev = Document_rev.replaceAll("ν","v"); Document_rev = Document_rev.replaceAll("ï","i"); Document_rev = Document_rev.replaceAll("ã","a"); Document_rev = Document_rev.replaceAll("≡","="); Document_rev = Document_rev.replaceAll("ó","o"); Document_rev = Document_rev.replaceAll("³","3"); Document_rev = Document_rev.replaceAll("〖","["); Document_rev = Document_rev.replaceAll("〗","]"); Document_rev = Document_rev.replaceAll("Å","A"); Document_rev = Document_rev.replaceAll("ρ","p"); Document_rev = Document_rev.replaceAll("ü","u"); Document_rev = Document_rev.replaceAll("ɛ","e"); Document_rev = Document_rev.replaceAll("č","c"); Document_rev = Document_rev.replaceAll("š","s"); Document_rev = Document_rev.replaceAll("ß","b"); Document_rev = Document_rev.replaceAll("═","="); Document_rev = Document_rev.replaceAll("£","L"); Document_rev = Document_rev.replaceAll("Ł","L"); Document_rev = Document_rev.replaceAll("ƒ","f"); Document_rev = Document_rev.replaceAll("ä","a"); Document_rev = Document_rev.replaceAll("–","-"); Document_rev = Document_rev.replaceAll("⁻","-"); Document_rev = Document_rev.replaceAll("〈","<"); Document_rev = Document_rev.replaceAll("〉",">"); Document_rev = Document_rev.replaceAll("χ","X"); Document_rev = Document_rev.replaceAll("Đ","D"); Document_rev = Document_rev.replaceAll("‰","%"); Document_rev = Document_rev.replaceAll("·","."); Document_rev = Document_rev.replaceAll("→",">"); Document_rev = Document_rev.replaceAll("←","<"); Document_rev = Document_rev.replaceAll("ζ","z"); Document_rev = Document_rev.replaceAll("π","p"); Document_rev = Document_rev.replaceAll("τ","t"); Document_rev = Document_rev.replaceAll("ξ","X"); Document_rev = Document_rev.replaceAll("η","h"); Document_rev = Document_rev.replaceAll("ø","0"); Document_rev = Document_rev.replaceAll("Δ","D"); Document_rev = Document_rev.replaceAll("∆","D"); Document_rev = Document_rev.replaceAll("∑","S"); Document_rev = Document_rev.replaceAll("Ω","O"); Document_rev = Document_rev.replaceAll("δ","d"); Document_rev = Document_rev.replaceAll("σ","s"); Document_rev = Document_rev.replaceAll("Φ","F"); //Document_rev = Document_rev.replaceAll("[^0-9A-Za-z\\!\\@\\#\\$\\%\\^\\&\\*\\(\\)\\_\\+\\-\\=\\{\\}\\|\\[\\]\\\\\\:;'\\<\\>\\?\\,\\.\\/\\' ]+"," "); //tmVar.tagger = new MaxentTagger("lib/taggers/english-left3words-distsim.tagger"); String tagged=tmVar.tagger.tagString(Document_rev).replace("-LRB-", "(").replace("-RRB-", ")").replace("-LSB-", "[").replace("-RSB-", "]"); String tag_split[]=tagged.split(" "); HashMap<String,String> POS=new HashMap<String,String>(); for(int p=0;p<tag_split.length;p++) { String tmp[]=tag_split[p].split("_"); String tmp2[]=tmp[0].replaceAll("\\s+(?=\\p{Punct})", "").split(regex); for(int q=0;q<tmp2.length;q++) { if(tmp2[q].matches("[^0-9a-zA-Z]")) { POS.put(tmp2[q], tmp2[q]); } else if(tmp2[q].matches("[0-9a-zA-Z]+")) { POS.put(tmp2[q], tmp[1]); } else { POS.put(tmp2[q], tmp2[q]); } } } for(int i=0;i<TokensInDoc.length;i++) { if(DocumentTmp.length()>0) { while(DocumentTmp.substring(0,1).matches("[\\t ]")) { DocumentTmp=DocumentTmp.substring(1); Offset++; } if(DocumentTmp.substring(0,TokensInDoc[i].length()).equals(TokensInDoc[i])) { if(TokensInDoc[i].length()>0) { DocumentTmp=DocumentTmp.substring(TokensInDoc[i].length()); /* * Feature Extration */ //PST String pos=POS.get(TokensInDoc[i]); if(pos == null || pos.equals("")) { pos = "_NULL_"; } //stemming tmVar.stemmer.setCurrent(TokensInDoc[i].toLowerCase()); tmVar.stemmer.stem(); String stem=tmVar.stemmer.getCurrent(); //Number of Numbers [0-9] String Num_num=""; String tmp=TokensInDoc[i]; tmp=tmp.replaceAll("[^0-9]",""); if(tmp.length()>3){Num_num="N:4+";}else{Num_num="N:"+ tmp.length();} //Number of Uppercase [A-Z] String Num_Uc=""; tmp=TokensInDoc[i]; tmp=tmp.replaceAll("[^A-Z]",""); if(tmp.length()>3){Num_Uc="U:4+";}else{Num_Uc="U:"+ tmp.length();} //Number of Lowercase [a-z] String Num_lc=""; tmp=TokensInDoc[i]; tmp=tmp.replaceAll("[^a-z]",""); if(tmp.length()>3){Num_lc="L:4+";}else{Num_lc="L:"+ tmp.length();} //Number of ALL char String Num_All=""; if(TokensInDoc[i].length()>3){Num_All="A:4+";}else{Num_All="A:"+ TokensInDoc[i].length();} //specific character (;:,.->+_) String SpecificC=""; tmp=TokensInDoc[i]; if(TokensInDoc[i].equals(";") || TokensInDoc[i].equals(":") || TokensInDoc[i].equals(",") || TokensInDoc[i].equals(".") || TokensInDoc[i].equals("-") || TokensInDoc[i].equals(">") || TokensInDoc[i].equals("+") || TokensInDoc[i].equals("_")) { SpecificC="-SpecificC1-"; } else if(TokensInDoc[i].equals("(") || TokensInDoc[i].equals(")")) { SpecificC="-SpecificC2-"; } else if(TokensInDoc[i].equals("{") || TokensInDoc[i].equals("}")) { SpecificC="-SpecificC3-"; } else if(TokensInDoc[i].equals("[") || TokensInDoc[i].equals("]")) { SpecificC="-SpecificC4-"; } else if(TokensInDoc[i].equals("\\") || TokensInDoc[i].equals("/")) { SpecificC="-SpecificC5-"; } else { SpecificC="__nil__"; } //chromosomal keytokens String ChroKey=""; tmp=TokensInDoc[i]; String pattern_ChroKey="^(q|p|qter|pter|XY|t)$"; Pattern pattern_ChroKey_compile = Pattern.compile(pattern_ChroKey); Matcher pattern_ChroKey_compile_Matcher = pattern_ChroKey_compile.matcher(tmp); if(pattern_ChroKey_compile_Matcher.find()) { ChroKey="-ChroKey-"; } else { ChroKey="__nil__"; } //Mutation type String MutatType=""; tmp=TokensInDoc[i]; tmp=tmp.toLowerCase(); String pattern_MutatType="^(del|ins|dup|tri|qua|con|delins|indel)$"; String pattern_FrameShiftType="(fs|fsX|fsx)"; Pattern pattern_MutatType_compile = Pattern.compile(pattern_MutatType); Pattern pattern_FrameShiftType_compile = Pattern.compile(pattern_FrameShiftType); Matcher pattern_MutatType_compile_Matcher = pattern_MutatType_compile.matcher(tmp); Matcher pattern_FrameShiftType_compile_Matcher = pattern_FrameShiftType_compile.matcher(tmp); if(pattern_MutatType_compile_Matcher.find()) { MutatType="-MutatType-"; } else if(pattern_FrameShiftType_compile_Matcher.find()) { MutatType="-FrameShiftType-"; } else { MutatType="__nil__"; } //Mutation word String MutatWord=""; tmp=TokensInDoc[i]; tmp=tmp.toLowerCase(); String pattern_MutatWord="^(deletion|delta|elta|insertion|repeat|inversion|deletions|insertions|repeats|inversions)$"; Pattern pattern_MutatWord_compile = Pattern.compile(pattern_MutatWord); Matcher pattern_MutatWord_compile_Matcher = pattern_MutatWord_compile.matcher(tmp); if(pattern_MutatWord_compile_Matcher.find()) { MutatWord="-MutatWord-"; } else { MutatWord="__nil__"; } //Mutation article & basepair String MutatArticle=""; tmp=TokensInDoc[i]; tmp=tmp.toLowerCase(); String pattern_base="^(single|a|one|two|three|four|five|six|seven|eight|nine|ten|[0-9]+)$"; String pattern_Byte="^(kb|mb)$"; String pattern_bp="(base|bases|pair|amino|acid|acids|codon|postion|postions|bp|nucleotide|nucleotides)"; Pattern pattern_base_compile = Pattern.compile(pattern_base); Pattern pattern_Byte_compile = Pattern.compile(pattern_Byte); Pattern pattern_bp_compile = Pattern.compile(pattern_bp); Matcher pattern_base_compile_Matcher = pattern_base_compile.matcher(tmp); Matcher pattern_Byte_compile_Matcher = pattern_Byte_compile.matcher(tmp); Matcher pattern_bp_compile_Matcher = pattern_bp_compile.matcher(tmp); if(pattern_base_compile_Matcher.find()) { MutatArticle="-Base-"; } else if(pattern_Byte_compile_Matcher.find()) { MutatArticle="-Byte-"; } else if(pattern_bp_compile_Matcher.find()) { MutatArticle="-bp-"; } else { MutatArticle="__nil__"; } //Type1 String Type1=""; tmp=TokensInDoc[i]; tmp=tmp.toLowerCase(); String pattern_Type1="^[cgrm]$"; String pattern_Type1_2="^(ivs|ex|orf)$"; Pattern pattern_Type1_compile = Pattern.compile(pattern_Type1); Pattern pattern_Type1_2_compile = Pattern.compile(pattern_Type1_2); Matcher pattern_Type1_compile_Matcher = pattern_Type1_compile.matcher(tmp); Matcher pattern_Type1_2_compile_Matcher = pattern_Type1_2_compile.matcher(tmp); if(pattern_Type1_compile_Matcher.find()) { Type1="-Type1-"; } else if(pattern_Type1_2_compile_Matcher.find()) { Type1="-Type1_2-"; } else { Type1="__nil__"; } //Type2 String Type2=""; tmp=TokensInDoc[i]; if(tmp.equals("p")) { Type2="-Type2-"; } else { Type2="__nil__"; } //DNA symbols String DNASym=""; tmp=TokensInDoc[i]; String pattern_DNASym="^[ATCGUatcgu]$"; Pattern pattern_DNASym_compile = Pattern.compile(pattern_DNASym); Matcher pattern_DNASym_compile_Matcher = pattern_DNASym_compile.matcher(tmp); if(pattern_DNASym_compile_Matcher.find()) { DNASym="-DNASym-"; } else { DNASym="__nil__"; } //Protein symbols String ProteinSym=""; String lastToken=""; tmp=TokensInDoc[i]; if(i>0){lastToken=TokensInDoc[i-1];} String pattern_ProteinSymFull="(glutamine|glutamic|leucine|valine|isoleucine|lysine|alanine|glycine|aspartate|methionine|threonine|histidine|aspartic|asparticacid|arginine|asparagine|tryptophan|proline|phenylalanine|cysteine|serine|glutamate|tyrosine|stop|frameshift)"; String pattern_ProteinSymTri="^(cys|ile|ser|gln|met|asn|pro|lys|asp|thr|phe|ala|gly|his|leu|arg|trp|val|glu|tyr|fs|fsx)$"; String pattern_ProteinSymTriSub="^(ys|le|er|ln|et|sn|ro|ys|sp|hr|he|la|ly|is|eu|rg|rp|al|lu|yr)$"; String pattern_ProteinSymChar="^[CISQMNPKDTFAGHLRWVEYX]$"; String pattern_lastToken="^[CISQMNPKDTFAGHLRWVEYX]$"; Pattern pattern_ProteinSymFull_compile = Pattern.compile(pattern_ProteinSymFull); Matcher pattern_ProteinSymFull_compile_Matcher = pattern_ProteinSymFull_compile.matcher(tmp); Pattern pattern_ProteinSymTri_compile = Pattern.compile(pattern_ProteinSymTri); Matcher pattern_ProteinSymTri_compile_Matcher = pattern_ProteinSymTri_compile.matcher(tmp); Pattern pattern_ProteinSymTriSub_compile = Pattern.compile(pattern_ProteinSymTriSub); Matcher pattern_ProteinSymTriSub_compile_Matcher = pattern_ProteinSymTriSub_compile.matcher(tmp); Pattern pattern_ProteinSymChar_compile = Pattern.compile(pattern_ProteinSymChar); Matcher pattern_ProteinSymChar_compile_Matcher = pattern_ProteinSymChar_compile.matcher(tmp); Pattern pattern_lastToken_compile = Pattern.compile(pattern_lastToken); Matcher pattern_lastToken_compile_Matcher = pattern_lastToken_compile.matcher(lastToken); if(pattern_ProteinSymFull_compile_Matcher.find()) { ProteinSym="-ProteinSymFull-"; } else if(pattern_ProteinSymTri_compile_Matcher.find()) { ProteinSym="-ProteinSymTri-"; } else if(pattern_ProteinSymTriSub_compile_Matcher.find() && pattern_lastToken_compile_Matcher.find() && !Document.substring(Offset-1,Offset).equals(" ")) { ProteinSym="-ProteinSymTriSub-"; } else if(pattern_ProteinSymChar_compile_Matcher.find()) { ProteinSym="-ProteinSymChar-"; } else { ProteinSym="__nil__"; } //RS String RScode=""; tmp=TokensInDoc[i]; String pattern_RScode="^(rs|RS|Rs)$"; Pattern pattern_RScode_compile = Pattern.compile(pattern_RScode); Matcher pattern_RScode_compile_Matcher = pattern_RScode_compile.matcher(tmp); if(pattern_RScode_compile_Matcher.find()) { RScode="-RScode-"; } else { RScode="__nil__"; } //Patterns String Pattern1=TokensInDoc[i]; String Pattern2=TokensInDoc[i]; String Pattern3=TokensInDoc[i]; String Pattern4=TokensInDoc[i]; Pattern1=Pattern1.replaceAll("[A-Z]","A"); Pattern1=Pattern1.replaceAll("[a-z]","a"); Pattern1=Pattern1.replaceAll("[0-9]","0"); Pattern1="P1:"+Pattern1; Pattern2=Pattern2.replaceAll("[A-Za-z]","a"); Pattern2=Pattern2.replaceAll("[0-9]","0"); Pattern2="P2:"+Pattern2; Pattern3=Pattern3.replaceAll("[A-Z]+","A"); Pattern3=Pattern3.replaceAll("[a-z]+","a"); Pattern3=Pattern3.replaceAll("[0-9]+","0"); Pattern3="P3:"+Pattern3; Pattern4=Pattern4.replaceAll("[A-Za-z]+","a"); Pattern4=Pattern4.replaceAll("[0-9]+","0"); Pattern4="P4:"+Pattern4; //prefix String prefix=""; tmp=TokensInDoc[i]; if(tmp.length()>=1){ prefix=tmp.substring(0, 1);}else{prefix="__nil__";} if(tmp.length()>=2){ prefix=prefix+" "+tmp.substring(0, 2);}else{prefix=prefix+" __nil__";} if(tmp.length()>=3){ prefix=prefix+" "+tmp.substring(0, 3);}else{prefix=prefix+" __nil__";} if(tmp.length()>=4){ prefix=prefix+" "+tmp.substring(0, 4);}else{prefix=prefix+" __nil__";} if(tmp.length()>=5){ prefix=prefix+" "+tmp.substring(0, 5);}else{prefix=prefix+" __nil__";} //suffix String suffix=""; tmp=TokensInDoc[i]; if(tmp.length()>=1){ suffix=tmp.substring(tmp.length()-1, tmp.length());}else{suffix="__nil__";} if(tmp.length()>=2){ suffix=suffix+" "+tmp.substring(tmp.length()-2, tmp.length());}else{suffix=suffix+" __nil__";} if(tmp.length()>=3){ suffix=suffix+" "+tmp.substring(tmp.length()-3, tmp.length());}else{suffix=suffix+" __nil__";} if(tmp.length()>=4){ suffix=suffix+" "+tmp.substring(tmp.length()-4, tmp.length());}else{suffix=suffix+" __nil__";} if(tmp.length()>=5){ suffix=suffix+" "+tmp.substring(tmp.length()-5, tmp.length());}else{suffix=suffix+" __nil__";} /* * Print out: .data */ FileData.write(TokensInDoc[i]+" "+stem+" "+pos+" "+Num_num+" "+Num_Uc+" "+Num_lc+" "+Num_All+" "+SpecificC+" "+ChroKey+" "+MutatType+" "+MutatWord+" "+MutatArticle+" "+Type1+" "+Type2+" "+DNASym+" "+ProteinSym+" "+RScode+" "+Pattern1+" "+Pattern2+" "+Pattern3+" "+Pattern4+" "+prefix+" "+suffix); if(RegEx_HGVs_hash.containsKey(Offset)) { FileData.write(" "+RegEx_HGVs_hash.get(Offset)); } else { FileData.write(" O"); } if(TrainTest.equals("Train")) // Test { if(character_hash.containsKey(Offset)) { FileData.write(" "+character_hash.get(Offset)); } else { FileData.write(" O"); } } FileData.write("\n"); /* * Print out: .location */ FileLocation.write(Pmid+"\t"+TokensInDoc[i]+"\t"+(Offset+1)+"\t"+(Offset+TokensInDoc[i].length())+"\n"); Offset=Offset+TokensInDoc[i].length(); } } else { System.out.println("Error! String not match: '"+DocumentTmp.substring(0,TokensInDoc[i].length())+"'\t'"+TokensInDoc[i]+"'"); } } } FileLocation.write("\n"); FileData.write("\n"); ParagraphType.clear(); ParagraphContent.clear(); annotations.clear(); RegEx_HGVs_hash.clear(); character_hash.clear(); } } inputfile.close(); FileLocation.close(); FileData.close(); } catch(IOException e1){ System.out.println("[MR]: Input file is not exist.");} } /* * Testing by CRF++ */ public void CRF_test(String FilenameData,String FilenameOutput,String TrainTest) throws IOException { File f = new File(FilenameOutput); BufferedWriter fr = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(f), "UTF-8")); Runtime runtime = Runtime.getRuntime(); String OS=System.getProperty("os.name").toLowerCase(); String model="MentionExtractionUB.Model"; String cmd="./CRF/crf_test -m CRF/"+model+" -o "+FilenameOutput+" "+FilenameData; if(TrainTest.equals("Test_FullText")) { model="MentionExtractionUB.fulltext.Model"; } if(OS.contains("windows")) { cmd ="CRF/crf_test -m CRF/"+model+" -o "+FilenameOutput+" "+FilenameData; } else //if(OS.contains("nux")||OS.contains("nix")) { cmd ="./CRF/crf_test -m CRF/"+model+" -o "+FilenameOutput+" "+FilenameData; } try { Process process = runtime.exec(cmd); InputStream is = process.getInputStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); String line=""; while ( (line = br.readLine()) != null) { fr.write(line); fr.newLine(); fr.flush(); } is.close(); isr.close(); br.close(); fr.close(); } catch (IOException e) { System.out.println(e); runtime.exit(0); } } /* * Learning model by CRF++ */ public void CRF_learn(String FilenameData) throws IOException { Process process = null; String line = null; InputStream is = null; InputStreamReader isr = null; BufferedReader br = null; Runtime runtime = Runtime.getRuntime(); String OS=System.getProperty("os.name").toLowerCase(); String cmd="./CRF/crf_learn -f 3 -c 4.0 CRF/template_UB "+FilenameData+" CRF/MentionExtractionUB.Model.new"; if(OS.contains("windows")) { cmd ="CRF/crf_learn -f 3 -c 4.0 CRF/template_UB "+FilenameData+" CRF/MentionExtractionUB.Model.new"; } else //if(OS.contains("nux")||OS.contains("nix")) { cmd ="./CRF/crf_learn -f 3 -c 4.0 CRF/template_UB "+FilenameData+" CRF/MentionExtractionUB.Model.new"; } try { process = runtime.exec(cmd); is = process.getInputStream(); isr = new InputStreamReader(is); br = new BufferedReader(isr); while ( (line = br.readLine()) != null) { System.out.println(line); System.out.flush(); } is.close(); isr.close(); br.close(); } catch (IOException e) { System.out.println(e); runtime.exit(0); } } }
55,253
39.360847
305
java
null
tmVar3-main/src/tmVarlib/PostProcessing.java
package tmVarlib; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.sql.*; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.HashMap; import java.util.Locale; import java.util.TreeMap; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.text.BreakIterator; public class PostProcessing { public void toME(String Filename,String FilenameOutput,String FilenameLoca,String FilenameME)throws IOException { HashMap<String,String> sentence_hash = new HashMap<String,String>(); HashMap<String,String> article_hash = new HashMap<String,String>(); HashMap<String,String> TypeOrder_hash = new HashMap<String,String>(); ArrayList<String> pmidARR = new ArrayList<String>(); try { /* * load input sentences */ int ParagraphType_count=0; BufferedReader inputfile = new BufferedReader(new InputStreamReader(new FileInputStream(Filename), "UTF-8")); String line; while ((line = inputfile.readLine()) != null) { if(line.contains("|")) //Title|Abstract { String Pmid=""; String ParagraphType=""; String ParagraphContent=""; Pattern pat = Pattern.compile("^([^\\|\\t]+)\\|([^\\|\\t]+)\\|(.*)$"); Matcher mat = pat.matcher(line); if(mat.find()) //Title|Abstract { Pmid = mat.group(1); ParagraphType=mat.group(2); ParagraphContent=mat.group(3); //if(ParagraphContent.equals("")) //{ // ParagraphContent="- No text -"; //} } sentence_hash.put(Pmid+"\t"+ParagraphType+"\t"+ParagraphType_count,ParagraphContent); if(article_hash.get(Pmid) != null) { article_hash.put(Pmid,article_hash.get(Pmid)+" "+ParagraphContent); } else { article_hash.put(Pmid,ParagraphContent); } if(TypeOrder_hash.get(Pmid) != null) { TypeOrder_hash.put(Pmid,TypeOrder_hash.get(Pmid)+"\t"+ParagraphType+"|"+ParagraphType_count); } else { TypeOrder_hash.put(Pmid,ParagraphType+"|"+ParagraphType_count); } if(!pmidARR.contains(Pmid)) { pmidARR.add(Pmid); } ParagraphType_count++; } } inputfile.close(); /* * load CRF output */ ArrayList<String> outputArr = new ArrayList<String>(); inputfile = new BufferedReader(new InputStreamReader(new FileInputStream(FilenameOutput), "UTF-8")); while ((line = inputfile.readLine()) != null) { outputArr.add(line); } inputfile.close(); /* * load location */ ArrayList<String> locationArr = new ArrayList<String>(); inputfile = new BufferedReader(new InputStreamReader(new FileInputStream(FilenameLoca), "UTF-8")); while ((line = inputfile.readLine()) != null) { locationArr.add(line); } inputfile.close(); BufferedWriter FileME = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(FilenameME), "UTF-8")); String pmid=""; for(int i=0;i<outputArr.size();i++) { String outputs[]=outputArr.get(i).split("\\t"); /* * Extract the states and tokens from CRF++ output file */ int start=100000000; int last=0; String mention=""; String location[]=locationArr.get(i).split("\\t"); HashMap<String,String> component_hash = new HashMap<String,String>(); if(component_hash.get("A") == null){component_hash.put("A", "");} if(component_hash.get("T") == null){component_hash.put("T", "");} if(component_hash.get("P") == null){component_hash.put("P", "");} if(component_hash.get("W") == null){component_hash.put("W", "");} if(component_hash.get("M") == null){component_hash.put("M", "");} if(component_hash.get("F") == null){component_hash.put("F", "");} if(component_hash.get("S") == null){component_hash.put("S", "");} if(component_hash.get("D") == null){component_hash.put("D", "");} if(component_hash.get("I") == null){component_hash.put("I", "");} if(component_hash.get("R") == null){component_hash.put("R", "");} // print title/abstracts if(location.length > 1 && !pmid.equals(location[0])) { if(!pmid.equals("")){FileME.write("\n");} pmid=location[0]; String TypeOrder[]=TypeOrder_hash.get(pmid).split("\\t"); for(int j=0;j<TypeOrder.length;j++) { String[] TypeOrder_component=TypeOrder[j].split("\\|"); FileME.write(pmid+"|"+TypeOrder_component[0]+"|"+sentence_hash.get(pmid+"\t"+TypeOrder_component[0]+"\t"+TypeOrder_component[1])+"\n"); } } //find mention Pattern pat = Pattern.compile("([ATPWMFSDIR])$"); Matcher mat = pat.matcher(outputs[outputs.length-1]); if((!outputs[0].equals(";")) && mat.find()) { String prestate=""; mat = pat.matcher(outputs[outputs.length-1]); //until the end token of the mention while((!outputs[0].equals(";")) && mat.find()) { String state=mat.group(1); String locationWhile[]=locationArr.get(i).split("\\t"); String tkn=locationWhile[1]; pmid=locationWhile[0]; int start_tmp=Integer.parseInt(locationWhile[2]); int last_tmp=Integer.parseInt(locationWhile[3]); mention = mention + tkn; if(!component_hash.get(state).equals("") && !state.equals(prestate)) { component_hash.put(state, component_hash.get(state)+","+tkn); } else { component_hash.put(state, component_hash.get(state)+tkn); } if(start_tmp<start){start=start_tmp;} if(last_tmp>last){last=last_tmp;} prestate=state; i++; outputs=outputArr.get(i).split("\\t"); mat = pat.matcher(outputs[outputs.length-1]); } if(mention.length()>200) { // remove the mention } else { /* * Recognize the components(identifiers) */ String identifier; String type=""; if(!component_hash.get("D").equals("")) { identifier=component_hash.get("A")+"|"+component_hash.get("T")+"|"+component_hash.get("P")+"|"+component_hash.get("M")+"|"+component_hash.get("D"); } else if(!component_hash.get("T").equals("")) { identifier=component_hash.get("A")+"|"+component_hash.get("T")+"|"+component_hash.get("P")+"|"+component_hash.get("M"); } else if(!component_hash.get("S").equals("")) { identifier=component_hash.get("A")+"|"+component_hash.get("W")+"|"+component_hash.get("P")+"|"+component_hash.get("M")+"|"+component_hash.get("F")+"|"+component_hash.get("S"); type="ProteinMutation"; } else if(!component_hash.get("F").equals("")) { identifier=component_hash.get("A")+"|"+component_hash.get("W")+"|"+component_hash.get("P")+"|"+component_hash.get("M")+"|"+component_hash.get("F"); type="ProteinMutation"; } else if(!component_hash.get("R").equals("")) { identifier=mention; type="SNP"; } else { identifier=component_hash.get("A")+"|"+component_hash.get("W")+"|"+component_hash.get("P")+"|"+component_hash.get("M"); } /* * Recognize the type of mentions: ProteinMutation | DNAMutation | SNP */ if(type.equals("")) { if(!component_hash.get("A").equals("") && ( component_hash.get("A").toLowerCase().equals("c") || component_hash.get("A").toLowerCase().equals("r") || component_hash.get("A").toLowerCase().equals("m") || component_hash.get("A").toLowerCase().equals("g") ) ) { type="DNAMutation"; } else if(!component_hash.get("A").equals("") && component_hash.get("A").toLowerCase().equals("p")) { type="ProteinMutation"; } else if(!component_hash.get("T").equals("") && component_hash.get("T").toLowerCase().equals("delta")) { type="DNAMutation"; } else if( !component_hash.get("P").equals("") && ( component_hash.get("P").toLowerCase().equals("ex") || component_hash.get("P").toLowerCase().equals("intron") || component_hash.get("P").toLowerCase().equals("ivs") ) ) { type="DNAMutation"; } else if((!component_hash.get("T").equals("")) && (!component_hash.get("M").matches(".*[^ATCGYU].*"))) { type="DNAMutation"; } else if(!component_hash.get("M").equals("") && !component_hash.get("W").equals("")) //others { pat = Pattern.compile("^[ATCGatcgu]+$"); Matcher mat_M = pat.matcher(component_hash.get("M")); Matcher mat_W = pat.matcher(component_hash.get("W")); if(!mat_M.find() || !mat_W.find()) { type="ProteinMutation"; } else //default { type="DNAMutation"; } } } if(type.equals("")) { type="ProteinMutation"; } /* * filtering and Print out */ boolean show_removed_cases=false; if( (component_hash.get("W").length() == 3 || component_hash.get("M").length() == 3) && component_hash.get("W").length() != component_hash.get("M").length() && !component_hash.get("W").equals("") && !component_hash.get("M").equals("") && component_hash.get("W").indexOf(",")!=-1 && component_hash.get("M").indexOf(",")!=-1 && ((component_hash.get("W").indexOf("A")!=-1 && component_hash.get("W").indexOf("T")!=-1 && component_hash.get("W").indexOf("C")!=-1 && component_hash.get("W").indexOf("G")!=-1) || (component_hash.get("M").indexOf("A")!=-1 && component_hash.get("M").indexOf("T")!=-1 && component_hash.get("M").indexOf("C")!=-1 && component_hash.get("M").indexOf("G")!=-1)) && component_hash.get("T").equals("") ) {if(show_removed_cases==true){System.out.println("filtering 1:"+article_hash.get(pmid).substring(start-1,last));}} else if((component_hash.get("M").matches("[ISQMNPKDFHLRWVEYX]") || component_hash.get("W").matches("[ISQMNPKDFHLRWVEYX]")) && component_hash.get("P").matches("[6-9][0-9][0-9][0-9]+")){if(show_removed_cases==true){System.out.println("filtering 2:"+article_hash.get(pmid).substring(start-1,last));}} //length > 3000, if protein mutation else if(component_hash.get("M").equals("") && component_hash.get("T").equals("") && component_hash.get("F").equals("") && component_hash.get("P").equals("") && !type.equals("SNP")){} //Arg235 else if(component_hash.get("W").equals("") && component_hash.get("T").equals("") && component_hash.get("F").equals("") && component_hash.get("D").equals("") && (!component_hash.get("M").equals("")) && !type.equals("SNP")){if(show_removed_cases==true){System.out.println("filtering 2.2:"+article_hash.get(pmid).substring(start-1,last));}} //314C else if(component_hash.get("M").equals("") && component_hash.get("T").equals("") && component_hash.get("F").equals("")&& component_hash.get("D").equals("") && (!component_hash.get("W").equals("")) && !type.equals("SNP")){if(show_removed_cases==true){System.out.println("filtering 2.2:"+article_hash.get(pmid).substring(start-1,last));}} //C314 else if(component_hash.get("T").toLowerCase().equals("delta") && (!component_hash.get("M").matches("[ATCG0-9]*")) && component_hash.get("P").equals("")){if(show_removed_cases==true){System.out.println("filtering 3:"+article_hash.get(pmid).substring(start-1,last));}} //DeltaEVIL else if(component_hash.get("T").toLowerCase().equals("delta") && component_hash.get("M").equals("") && component_hash.get("P").equals("")){if(show_removed_cases==true){System.out.println("filtering 3:"+article_hash.get(pmid).substring(start-1,last));}} //Delta else if(component_hash.get("P").matches("^-") && type.equals("ProteinMutation")){if(show_removed_cases==true){System.out.println("filtering 4:"+article_hash.get(pmid).substring(start-1,last));}} //negative protein mutation else if(component_hash.get("W").matches("^[BJOUZ]") || component_hash.get("M").matches("^[BJOUZ]")){if(show_removed_cases==true){System.out.println("filtering 5:"+article_hash.get(pmid).substring(start-1,last));}} //not a mutation else if(component_hash.get("W").matches("^[A-Za-z][a-z]") || component_hash.get("M").matches("^[A-Za-z][a-z]") ){if(show_removed_cases==true){System.out.println("filtering 7:"+article_hash.get(pmid).substring(start-1,last));}} //not a mutation else if( component_hash.get("W").matches("[A-Za-z]") && component_hash.get("M").matches("[A-Za-z][a-z][a-z]+") && (!tmVar.nametothree.containsKey(component_hash.get("M").toUpperCase())) && (!tmVar.threetone.containsKey(component_hash.get("M").toUpperCase())) ){} //T-->infinity else if( component_hash.get("M").matches("[A-Za-z]") && component_hash.get("W").matches("[A-Za-z][a-z][a-z]+") && (!tmVar.nametothree.containsKey(component_hash.get("W").toUpperCase())) && (!tmVar.threetone.containsKey(component_hash.get("W").toUpperCase())) ){} //T-->infinity else if(article_hash.get(pmid).length()>start-1 && start>15 && article_hash.get(pmid).substring(start-15,start-1).matches(".*(Figure|Figures|Table|Fig|Figs|Tab|Tabs|figure|figures|table|fig|figs|tab|tabs)[ \\.].*")){if(show_removed_cases==true){System.out.println("filtering 6.1:"+start+"\t"+last+"\t"+article_hash.get(pmid).substring(start-1,last));}} //Figure S13A else if(article_hash.get(pmid).length()>last+1 && article_hash.get(pmid).substring(last,last+1).matches("[A-Za-z0-9\\>]") && !type.equals("SNP")){if(show_removed_cases==true){System.out.println("filtering 7:"+article_hash.get(pmid).substring(start-1,last));}} //V79 Chinese else if(mention.matches(".+\\).+\\(.+")){if(show_removed_cases==true){System.out.println("filtering - Mention:"+mention);}} //Arg)3(Ser else if(mention.matches(".+\\>.+\\>.+")){if(show_removed_cases==true){System.out.println("filtering - Mention:"+mention);}} //G>T>C else if(mention.matches("[A-Z][a-z][a-z][0-9]+,[A-Z][a-z][a-z][0-9]+")){if(show_removed_cases==true){System.out.println("filtering - Mention:"+mention);}} //Glu207, Thr209 else if(mention.matches("[A-Z][a-z][a-z][0-9]+,[A-Z][a-z][a-z][0-9]+,[A-Z][a-z][a-z][0-9]+")){if(show_removed_cases==true){System.out.println("filtering - Mention:"+mention);}} //Glu207, Thr209, Gly211 else if(mention.matches(".*[gG]\\/L.*")){if(show_removed_cases==true){System.out.println("filtering - Mention:"+mention);}} //450 G/L else if(tmVar.PAM_lowerScorePair.contains(component_hash.get("M")+"\t"+component_hash.get("W"))){if(show_removed_cases==true){System.out.println("filtering - Mention:"+mention);}} //unlikely to occur else if(component_hash.get("W").length()==3 && (!tmVar.threetone.containsKey(component_hash.get("W").toUpperCase()) && !tmVar.threetone_nu.containsKey(component_hash.get("W").toUpperCase()))){if(show_removed_cases==true){System.out.println("filtering - Mention:"+mention+"\tW:"+component_hash.get("W"));}} //The 100 Top else if(component_hash.get("M").length()==3 && (!tmVar.threetone.containsKey(component_hash.get("M").toUpperCase()) && !tmVar.threetone_nu.containsKey(component_hash.get("M").toUpperCase()))){if(show_removed_cases==true){System.out.println("filtering - Mention:"+mention+"\tW:"+component_hash.get("M"));}} //The 100 Top else if(mention.length()>200){if(show_removed_cases==true){System.out.println("filtering - Mention:"+mention);}} //too long else if(article_hash.get(pmid).length()>last) { String men=article_hash.get(pmid).substring(start-1,last); Pattern pat_cp = Pattern.compile("(c\\..*) (p\\..*)"); Pattern pat_pc = Pattern.compile("(p\\..*) (c\\..*)"); Matcher mat_cp = pat_cp.matcher(men); Matcher mat_pc = pat_pc.matcher(men); if(mat_cp.find()) //Title|Abstract { String men_c = mat_cp.group(1); String men_p = mat_cp.group(2); int start_c=start-1; int last_c=start_c+men_c.length(); int start_p=last_c+1; int last_p=start_p+men_p.length(); FileME.write(pmid+"\t"+start_c+"\t"+last_c+"\t"+men_c+"\tDNAMutation\t"+identifier+"\n"); FileME.write(pmid+"\t"+start_p+"\t"+last_p+"\t"+men_p+"\tProteinMutation\t"+identifier+"\n"); } else if(mat_pc.find()) //Title|Abstract { String men_p = mat_pc.group(1); String men_c = mat_pc.group(2); int start_p=start-1; int last_p=start_p+men_p.length(); int start_c=last_p+1; int last_c=start_c+men_c.length(); FileME.write(pmid+"\t"+start_p+"\t"+last_p+"\t"+men_p+"\tProteinMutation\t"+identifier+"\n"); FileME.write(pmid+"\t"+start_c+"\t"+last_c+"\t"+men_c+"\tDNAMutation\t"+identifier+"\n"); } else { FileME.write(pmid+"\t"+(start-1)+"\t"+last+" "+article_hash.get(pmid).substring(start-1,last)+"\t"+type+"\t"+identifier+"\n"); } } } if(!outputs[outputs.length-1].equals("O")) { i--; } } } FileME.write("\n"); FileME.close(); } catch(IOException e1){ System.out.println("[toME]: Input file is not exist.");} } public void toPostME(String FilenameME,String FilenamePostME)throws IOException { Pattern Pattern_Component_1 = Pattern.compile("^([RrSs][Ss][ ]*[0-9]+)[ ]*(and|/|,|or)[ ]*([RrSs][Ss][ ]*[0-9]+)$"); Pattern Pattern_Component_2 = Pattern.compile("^(.*[^0-9])[ ]*([RrSs][Ss][ ]*[0-9]+)$"); Pattern Pattern_Component_3 = Pattern.compile("^([RrSs][Ss][ ]*[0-9]+)[ ]*([^0-9].*)$"); HashMap<String,HashMap<String,String>> Temporary_Pattern_Allele = new HashMap<String,HashMap<String,String>>(); try { BufferedWriter FilePostME = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(FilenamePostME), "UTF-8")); // .location BufferedReader inputfile = new BufferedReader(new InputStreamReader(new FileInputStream(FilenameME), "UTF-8")); ArrayList<String> Annotation = new ArrayList<String>(); String article=""; String Pmid=""; String line=""; while ((line = inputfile.readLine()) != null) { Pattern pat = Pattern.compile("^([^\\|\\t]+)\\|([^\\|\\t]+)\\|(.*)$"); Matcher mat = pat.matcher(line); if(mat.find()) //Title|Abstract { Pmid = mat.group(1); String ParagraphContent=mat.group(3); article=article+ParagraphContent+"\t"; FilePostME.write(line+"\n"); Temporary_Pattern_Allele.put(Pmid,new HashMap<String,String>()); } else if (line.contains("\t")) //Annotation { String anno[]=line.split("\t"); Pmid=anno[0]; String mention=anno[3]; String type=anno[4]; Annotation.add(line); } else if(line.length()==0) //Processing { ArrayList<Integer> RemoveAnno = new ArrayList<Integer>(); /* * Split RSnumber */ for(int i=0;i<Annotation.size();i++) { String anno[]=Annotation.get(i).split("\t"); Pmid=anno[0]; int start = Integer.parseInt(anno[1]); int last = Integer.parseInt(anno[2]); String mention = anno[3]; String type = anno[4]; if(!tmVar.variant_mention_to_filter_overlap_gene.containsKey(Pmid)) { tmVar.variant_mention_to_filter_overlap_gene.put(Pmid, new HashMap<Integer,String>()); } for(int s=start;s<=last;s++) { tmVar.variant_mention_to_filter_overlap_gene.get(Pmid).put(s,""); } /** The common combine tokens: m1: "rs123456 and rs234567" m2: "A134T rs234567" m3: "rs234567 A134T" */ Matcher m1 = Pattern_Component_1.matcher(mention); Matcher m2 = Pattern_Component_2.matcher(mention); Matcher m3 = Pattern_Component_3.matcher(mention); if(m1.find()) { String sub_mention1=m1.group(1); String sub_mention2=m1.group(3); int start1=start; int last1=start+sub_mention1.length(); int start2=last-sub_mention2.length(); int last2=last; RemoveAnno.add(i); Annotation.add(Pmid+"\t"+start1+"\t"+last1+"\t"+sub_mention1+"\tSNP\t"+sub_mention1); Annotation.add(Pmid+"\t"+start2+"\t"+last2+"\t"+sub_mention2+"\tSNP\t"+sub_mention2); } else if(m2.find()) { String sub_mention1=m2.group(1); String sub_mention2=m2.group(2); int start1=start; int last1=start+sub_mention1.length(); int start2=last-sub_mention2.length(); int last2=last; RemoveAnno.add(i); Annotation.add(Pmid+"\t"+start1+"\t"+last1+"\t"+sub_mention1+"\tDNAMutation\t"+sub_mention1); Annotation.add(Pmid+"\t"+start2+"\t"+last2+"\t"+sub_mention2+"\tSNP\t"+sub_mention2); } else if(m3.find()) { String sub_mention1=m3.group(1); String sub_mention2=m3.group(2); int start1=start; int last1=start+sub_mention1.length(); int start2=last-sub_mention2.length(); int last2=last; RemoveAnno.add(i); Annotation.add(Pmid+"\t"+start1+"\t"+last1+"\t"+sub_mention1+"\tSNP\t"+sub_mention1); Annotation.add(Pmid+"\t"+start2+"\t"+last2+"\t"+sub_mention2+"\tDNAMutation\t"+sub_mention2); } } for(int i=RemoveAnno.size()-1;i>=0;i--) { int RemA=RemoveAnno.get(i); Annotation.remove(RemA); } /* * Boundary */ for(int i=0;i<Annotation.size();i++) { String anno[]=Annotation.get(i).split("\t",-1); int start = Integer.parseInt(anno[1]); int last = Integer.parseInt(anno[2]); String mention = anno[3]; String type = anno[4]; String identifier = anno[5]; int check=0; String identifier_component[]=identifier.split("\\|",-1); if(identifier_component.length>=3) { if(type.equals("DNAMutation")) { String position=identifier_component[2]; String W=identifier_component[1]; String M=identifier_component[3]; if(position.matches("[IVS\\+0-9\\*\\- ]+")) { position=position.replaceAll("\\*","\\\\*"); position=position.replaceAll("\\+","\\\\+"); position=position.replaceAll("[\\(\\)\\[\\]\\{\\}]",""); W=W.replaceAll("[\\W\\-\\_]",""); M=M.replaceAll("[\\W\\-\\_]",""); Temporary_Pattern_Allele.get(Pmid).put("([cg]\\.|)([ATCGU]+|[Gg]uanine|[Aa]denine|[Aa]denosine|[Tt]hymine|[Tt]hymidine|[Cc]ytosine|[Cc]ytidine|[Uu]racil|[Uu]ridine)[\\+ ]*"+position,"DNAAllele"); Temporary_Pattern_Allele.get(Pmid).put("([cg]\\.|)"+position+"[ ]*([ATCGU]+|[Gg]uanine|[Aa]denine|[Aa]denosine|[Tt]hymine|[Tt]hymidine|[Cc]ytosine|[Cc]ytidine|[Uu]racil|[Uu]ridine)","DNAAllele"); Temporary_Pattern_Allele.get(Pmid).put("([cg]\\.|)"+W+"[\\- ]*"+position+"[\\- ]*"+W,"DNAAllele"); Temporary_Pattern_Allele.get(Pmid).put("([cg]\\.|)"+M+"[\\- ]*"+position+"[\\- ]*"+M,"DNAAllele"); } if(W.length()>0 && W.length()==M.length() && !W.toLowerCase().matches("(del|ins|dup|indel).*") ) { if((W.matches("[A-Za-z]+")) && (M.matches("[A-Za-z]+"))) { Temporary_Pattern_Allele.get(Pmid).put(W+"[\\- \\/]+"+M,"DNAAcidChange"); Temporary_Pattern_Allele.get(Pmid).put(M+"[\\- \\/]+"+W,"DNAAcidChange"); } } } else if(type.equals("ProteinMutation")) { String position=identifier_component[2]; String W=identifier_component[1]; String M=identifier_component[3]; if(position.matches("[IVS\\+0-9\\*\\- ]+")) { position=position.replaceAll("\\*","\\\\*"); position=position.replaceAll("\\+","\\\\+"); position=position.replaceAll("[\\(\\)\\[\\]\\{\\}]",""); W=W.replaceAll("[\\W\\-\\_]",""); M=M.replaceAll("[\\W\\-\\_]",""); Temporary_Pattern_Allele.get(Pmid).put("(p\\.|)([ATCGU][ATCGU][ATCGU]|Cys|Ile|Ser|Gln|Met|Asn|Pro|Lys|Asp|Thr|Phe|Ala|Gly|His|Leu|Arg|Trp|Val|Glu|Tyr|CYS|ILE|SER|GLN|MET|ASN|PRO|LYS|ASP|THR|PHE|ALA|GLY|HIS|LEU|ARG|TRP|VAL|GLU|TYR|CYs|ILe|SEr|GLn|MEt|ASn|PRo|LYs|ASp|THr|PHe|ALa|GLy|HIs|LEu|ARg|TRp|VAl|GLu|TYr|[gG]lutamine|[Gg]lutamic acid|[Ll]eucine|[Vv]aline|[Ii]soleucine|[Ll]ysine|[Aa]lanine|[Gg]lycine|[Aa]spartate|[Mm]ethionine|[Tt]hreonine|[Hh]istidine|[Aa]spartic acid|[Aa]rginine|[Aa]sparagine|[Tt]ryptophan|[Pp]roline|[Pp]henylalanine|[Cc]ysteine|[Ss]erine|[Gg]lutamate|[Tt]yrosine|[Ss]top|[Tt]erm|[Ss]top codon|[Tt]ermination codon|[Tt]ermination|[CISQMNPKDTFAGHLRWVEYXU])[\\+ ]*"+position,"ProteinAllele"); Temporary_Pattern_Allele.get(Pmid).put("(p\\.|)"+position+"[ ]*([ATCGU][ATCGU][ATCGU]|Cys|Ile|Ser|Gln|Met|Asn|Pro|Lys|Asp|Thr|Phe|Ala|Gly|His|Leu|Arg|Trp|Val|Glu|Tyr|CYS|ILE|SER|GLN|MET|ASN|PRO|LYS|ASP|THR|PHE|ALA|GLY|HIS|LEU|ARG|TRP|VAL|GLU|TYR|CYs|ILe|SEr|GLn|MEt|ASn|PRo|LYs|ASp|THr|PHe|ALa|GLy|HIs|LEu|ARg|TRp|VAl|GLu|TYr|[gG]lutamine|[Gg]lutamic acid|[Ll]eucine|[Vv]aline|[Ii]soleucine|[Ll]ysine|[Aa]lanine|[Gg]lycine|[Aa]spartate|[Mm]ethionine|[Tt]hreonine|[Hh]istidine|[Aa]spartic acid|[Aa]rginine|[Aa]sparagine|[Tt]ryptophan|[Pp]roline|[Pp]henylalanine|[Cc]ysteine|[Ss]erine|[Gg]lutamate|[Tt]yrosine|[Ss]top|[Tt]erm|[Ss]top codon|[Tt]ermination codon|[Tt]ermination|[CISQMNPKDTFAGHLRWVEYXU])","ProteinAllele"); Temporary_Pattern_Allele.get(Pmid).put("(p\\.|)"+W+"[\\- ]*"+position+"[\\- ]*"+W,"ProteinAllele"); Temporary_Pattern_Allele.get(Pmid).put("(p\\.|)"+M+"[\\- ]*"+position+"[\\- ]*"+M,"ProteinAllele"); } if(W.length()>0 && W.length()==M.length() && !W.toLowerCase().matches("(del|ins|dup|indel).*") ) { if((W.matches("[A-Za-z]+")) && (M.matches("[A-Za-z]+"))) { Temporary_Pattern_Allele.get(Pmid).put(W+"[\\- \\/]+"+M,"ProteinAcidChange"); Temporary_Pattern_Allele.get(Pmid).put(M+"[\\- \\/]+"+W,"ProteinAcidChange"); } } } } if(mention.length()>0) { if(mention.matches("^[0-9]") && article.substring(start-1,start).matches("[+-]")) //17000021 251 258 1858C>T --> +1858C>T { check=1; start=start-1; mention=article.substring(start-1,start)+mention; } Pattern ptmp = Pattern.compile("^([\\/,][A-Z])[\\W\\-\\_]"); int last_bound=last+20; if(article.length()<last+20) { last_bound=article.length(); } Matcher mtmp = ptmp.matcher(article.substring(last,last_bound)); if(mtmp.find()) { check=1; last=last+mtmp.group(1).length(); mention=article.substring(start,last); } if(mention.matches("^[^0-9A-Za-z][RrSs][Ss][0-9]+$")) //_rs7207916 { check=1; start=start+1; mention=mention.substring(1,mention.length()); } if(mention.startsWith("(") && !mention.contains(")")) // delete ( { check=1; start=start+1; mention=mention.substring(1,mention.length()); } //mention.substring(mention.length()-1, mention.length()) : the last character of mention else if(mention.substring(mention.length()-1, mention.length()).equals(")") && !mention.contains("(")) // delete ) { check=1; last=last-1; mention=mention.substring(0,mention.length()-1); } else if(start > 0 && article.substring(start-1,start).equals("(") && mention.contains(")") && !mention.contains("(")) // add ( { check=1; start=start-1; mention="("+mention; } else if(start > 0 && article.substring(start-1,start).equals("[") && mention.contains("]") && !mention.contains("[")) // add [ { check=1; start=start-1; mention="["+mention; } else if(article.substring(last,last+1).equals(")") && mention.contains("(") && !mention.contains(")")) // add ) { check=1; last=last+1; mention=mention+")"; } else if(article.substring(last,last+1).equals("]") && mention.contains("[") && !mention.contains("]")) // add ] { check=1; last=last+1; mention=mention+"]"; } else if(mention.startsWith("(") && mention.substring(mention.length()-1, mention.length()).equals(")")) // delete ( ) { check=1; start=start+1; last=last-1; mention=mention.substring(1,mention.length()-1); } } if(check == 1) { Annotation.remove(i); Annotation.add(i,Pmid+"\t"+start+"\t"+last+"\t"+mention+"\t"+type+"\t"+identifier); //problem not solve!!! } } /* * Mention Recognition by Pattern */ /* * Self-pattern: should close in Full text */ /* HashMap<String,String> SelfPattern2type_hash = new HashMap<String,String>(); for(int i=0;i<Annotation.size();i++) { String anno[]=Annotation.get(i).split("\t"); String mention = anno[3]; String type = anno[4]; if(!type.equals("SNP")) { mention = mention.replaceAll("([^A-Za-z0-9])","\\$1"); mention = mention.replaceAll("[0-9]+","[0-9]+"); mention = mention.replaceAll("(IVS|EX)","@@@@"); mention = mention.replaceAll("(rs|ss)","@@@"); mention = mention.replaceAll("[A-Z]","[A-Z]"); mention = mention.replaceAll("@@@@","(IVS|EX)"); mention = mention.replaceAll("@@@","(rs|ss)"); SelfPattern2type_hash.put(mention, type); } } */ /* * Pattern match */ HashMap <String,String> AddList = new HashMap <String,String>(); ArrayList <String> removeList = new ArrayList <String>(); String article_tmp=article; for(int pat_i=0;pat_i<tmVar.MF_Pattern.size();pat_i++) { String pattern_RegEx = tmVar.MF_Pattern.get(pat_i); String pattern_Type = tmVar.MF_Type.get(pat_i); Pattern PATTERN_RegEx; if(pattern_Type.matches(".*(Allele|AcidChange)")) { PATTERN_RegEx = Pattern.compile("^(.*?[ \\(;,\\/])("+pattern_RegEx+")[ \\);,\\/\\.]"); } else { PATTERN_RegEx = Pattern.compile("^(.*?[^A-Za-z0-9])("+pattern_RegEx+")[^A-Za-z0-9]"); } Matcher mp = PATTERN_RegEx.matcher(article_tmp); while (mp.find()) { String pre = mp.group(1); String mention = mp.group(2); if(mention.matches("[0-9]+[\\W\\-\\_]*[a-z]ins")){/*System.out.println(mention);*/} else { //System.out.println(pattern_RegEx+"\t"+mention); boolean ExistLarger = false; int start=pre.length(); int last=start+mention.length(); //Check if overlap with previous annotation for(int a=0;a<Annotation.size();a++) { String Exist[] = Annotation.get(a).split("\t"); int Exist_start = Integer.parseInt(Exist[1]); int Exist_last = Integer.parseInt(Exist[2]); if( (start<Exist_start && last>=Exist_last) || (start<=Exist_start && last>Exist_last) ) { removeList.add(Annotation.get(a)); } else if (((start>Exist_start && start<Exist_last) || (last>Exist_start && last<Exist_last)) && ((last-start)>(Exist_last-Exist_start))) //overlap, but not subset { removeList.add(Annotation.get(a)); } else if( (Exist_start<start && Exist_last>=last) || (Exist_start<=start && Exist_last>last) ) { ExistLarger = true; } } if(ExistLarger == false) { //Check if overlap with previous annotation for(String added : AddList.keySet()) { String Exist[] = added.split("\t"); int Exist_start = Integer.parseInt(Exist[1]); int Exist_last = Integer.parseInt(Exist[2]); if( (start<Exist_start && last>=Exist_last) || (start<=Exist_start && last>Exist_last) ) { AddList.put(added,"remove"); } else if ( ((start>Exist_start && start<Exist_last) || (last>Exist_start && last<Exist_last)) && ((last-start)>(Exist_last-Exist_start)) ) //overlap, but not subset { AddList.put(added,"remove"); } else if( (Exist_start<start && Exist_last>=last) || (Exist_start<=start && Exist_last>last) ) { ExistLarger = true; } } if(ExistLarger == false && !AddList.containsKey(Pmid+"\t"+start+"\t"+last+"\t"+mention)) { if(mention.matches("[A-Z]+[ ]+(for|to)[ ]+[0-9]+")){/*System.out.println(mention);*/} //C for 6 - remove else if(mention.matches("[0-9]+[ ]+(for|to)[ ]+[A-Z]+")){/*System.out.println(mention);*/} //6 to C - remove else { AddList.put(Pmid+"\t"+start+"\t"+last+"\t"+mention,pattern_Type); } } } String tmp=""; for(int j=0;j<mention.length();j++){tmp=tmp+"@";} article_tmp=article_tmp.substring(0,start)+tmp+article_tmp.substring(last); mp = PATTERN_RegEx.matcher(article_tmp); } } } for(String pattern_RegEx:Temporary_Pattern_Allele.get(Pmid).keySet()) { String pattern_Type = Temporary_Pattern_Allele.get(Pmid).get(pattern_RegEx); Pattern PATT_RegEx; if(pattern_Type.matches(".*(Allele|AcidChange)")) { PATT_RegEx = Pattern.compile("^(.*?[ \\(;,\\/\\-])("+pattern_RegEx+")[ \\);,\\/\\.]"); } else { PATT_RegEx = Pattern.compile("^(.*?[^A-Za-z0-9])("+pattern_RegEx+")[^A-Za-z0-9]"); } Matcher mp = PATT_RegEx.matcher(article_tmp); while (mp.find()) { String pre = mp.group(1); String mention = mp.group(2); if(mention.matches("[0-9]+[\\W\\-\\_]*[a-z]ins")){/*System.out.println(mention);*/} else { boolean ExistLarger = false; int start=pre.length(); int last=start+mention.length(); //Check if overlap with previous annotation for(int a=0;a<Annotation.size();a++) { String Exist[] = Annotation.get(a).split("\t"); int Exist_start = Integer.parseInt(Exist[1]); int Exist_last = Integer.parseInt(Exist[2]); if( (start<Exist_start && last>=Exist_last) || (start<=Exist_start && last>Exist_last) ) { removeList.add(Annotation.get(a)); } else if (((start>Exist_start && start<Exist_last) || (last>Exist_start && last<Exist_last)) && ((last-start)>(Exist_last-Exist_start))) //overlap, but not subset { removeList.add(Annotation.get(a)); } else if( (Exist_start<start && Exist_last>=last) || (Exist_start<=start && Exist_last>last) ) { ExistLarger = true; } } if(ExistLarger == false) { //Check if overlap with previous annotation for(String added : AddList.keySet()) { String Exist[] = added.split("\t"); int Exist_start = Integer.parseInt(Exist[1]); int Exist_last = Integer.parseInt(Exist[2]); if( (start<Exist_start && last>=Exist_last) || (start<=Exist_start && last>Exist_last) ) { AddList.put(added,"remove"); } else if ( ((start>Exist_start && start<Exist_last) || (last>Exist_start && last<Exist_last)) && ((last-start)>(Exist_last-Exist_start)) ) //overlap, but not subset { AddList.put(added,"remove"); } else if( (Exist_start<start && Exist_last>=last) || (Exist_start<=start && Exist_last>last) ) { ExistLarger = true; } } if(ExistLarger == false && !AddList.containsKey(Pmid+"\t"+start+"\t"+last+"\t"+mention)) { AddList.put(Pmid+"\t"+start+"\t"+last+"\t"+mention,pattern_Type); } } String tmp=""; for(int j=0;j<mention.length();j++){tmp=tmp+"@";} article_tmp=article_tmp.substring(0,start)+tmp+article_tmp.substring(last); mp = PATT_RegEx.matcher(article_tmp); } } } for(int r=0;r<removeList.size();r++) { Annotation.remove(removeList.get(r)); } for(String added : AddList.keySet()) { if(!AddList.get(added).equals("remove")) { boolean found= false; for(int a=0;a<Annotation.size();a++) { String Anno[] = Annotation.get(a).split("\t"); if(added.equals(Anno[0]+"\t"+Anno[1]+"\t"+Anno[2]+"\t"+Anno[3])) { found = true; } } if(found == false) { Annotation.add(added+"\t"+AddList.get(added)); } } } /* * Pattern match : Self pattern */ /* for(String pattern_RegEx : SelfPattern2type_hash.keySet()) { String pattern_Type = SelfPattern2type_hash.get(pattern_RegEx); Pattern PATTERN_RegEx = Pattern.compile("^(.*[^A-Za-z0-9])("+pattern_RegEx+")[^A-Za-z0-9]"); Matcher mp = PATTERN_RegEx.matcher(article); while (mp.find()) { String pre = mp.group(1); String mention = mp.group(2); int start=pre.length(); int last=start+mention.length(); Annotation.add(Pmid+"\t"+start+"\t"+last+"\t"+mention+"\t"+pattern_Type); String tmp=""; for(int j=0;j<mention.length();j++){tmp=tmp+"@";} article=article.substring(0,start)+tmp+article.substring(last); System.out.println(mention); } } */ for(int i=0;i<Annotation.size();i++) { FilePostME.write(Annotation.get(i)+"\n"); } FilePostME.write("\n"); article=""; Annotation.clear(); } } FilePostME.close(); } catch(IOException e1){ System.out.println("[toPostME]: Input file is not exist.");} } public void toPostMEData(String Filename,String FilenamePostME,String FilenamePostMeML,String FilenamePostMeData,String TrainTest) throws IOException { try { //Parse identifier (components) Pattern Pattern_Component_1 = Pattern.compile("^([^|]*)\\|([^|]*)\\|([^|]*)\\|([^|]*)\\|(fs[^|]*)\\|([^|]*)$"); Pattern Pattern_Component_1_1 = Pattern.compile("^([^|]*)\\|([^|]*(ins|del|Del|dup|-)[^|]*)\\|([^|]*)\\|([^|]*)\\|(fs[^|]*)$"); //append for p.G352fsdelG p|del|352|G,G|fs Pattern Pattern_Component_2 = Pattern.compile("^([^|]*)\\|([^|]*)\\|([^|]*)\\|([^|]*)\\|(fs[^|]*)$"); Pattern Pattern_Component_3 = Pattern.compile("^([^|]*)\\|([^|]*(ins|del|Del|dup|-|insertion|deletion|insertion|deletion|deletion\\/insertion|insertion\\/deletion|indel|delins|duplication|lack|lacked|copy|lose|losing|lacking|inserted|deleted|duplicated|insert|delete|duplicate|repeat|repeated)[^|]*)\\|([^|]*)\\|([^|]*)$"); Pattern Pattern_Component_4 = Pattern.compile("^([^|]*)\\|([^|]*)\\|([^|]*)\\|([^|]*)$"); Pattern Pattern_Component_5 = Pattern.compile("^([^|]*)\\|([^|]*)\\|([^|]*)\\|([^|]*)\\|([^|]*)$"); Pattern Pattern_Component_6 = Pattern.compile("^((\\[rs\\]|[RrSs][Ss]|reference SNP no[.] )[0-9][0-9][0-9]+)$"); HashMap<String,String> mention_hash = new HashMap<String,String>(); HashMap<String,String> mention2type_hash = new HashMap<String,String>(); BufferedReader inputfile; if(TrainTest.equals("Train")) { inputfile = new BufferedReader(new InputStreamReader(new FileInputStream(Filename), "UTF-8")); } else { inputfile = new BufferedReader(new InputStreamReader(new FileInputStream(FilenamePostME), "UTF-8")); } String line; while ((line = inputfile.readLine()) != null) { Pattern pat = Pattern.compile("^([^\\|\\t]+)\\|([^\\|\\t]+)\\|(.*)$"); Matcher mat = pat.matcher(line); if(mat.find()) //Title|Abstract { } else if (line.contains("\t")) //Annotation { String anno[]=line.split("\t"); if(anno.length>=6 && TrainTest.equals("Train")) { String mention=anno[3]; String type=anno[4]; String identifier=anno[5]; mention2type_hash.put(mention, type); mention_hash.put(mention, identifier); } else if(anno.length>=5) { String mention=anno[3]; String type=anno[4]; mention2type_hash.put(mention, type); mention_hash.put(mention, type); } } } inputfile.close(); BufferedWriter mentionlistbw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(FilenamePostMeML), "UTF-8")); // .ml BufferedWriter mentiondata = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(FilenamePostMeData), "UTF-8")); // .location for(String mention : mention_hash.keySet() ) { HashMap<Integer, String> character_hash = new HashMap<Integer, String>(); int start=0; int last=mention.length(); for(int s=start;s<last;s++) { character_hash.put(s,"I"); } if(TrainTest.equals("Train")) { Matcher m1 = Pattern_Component_1.matcher(mention_hash.get(mention)); Matcher m1_1 = Pattern_Component_1_1.matcher(mention_hash.get(mention)); Matcher m2 = Pattern_Component_2.matcher(mention_hash.get(mention)); Matcher m3 = Pattern_Component_3.matcher(mention_hash.get(mention)); Matcher m4 = Pattern_Component_4.matcher(mention_hash.get(mention)); Matcher m5 = Pattern_Component_5.matcher(mention_hash.get(mention)); Matcher m6 = Pattern_Component_6.matcher(mention_hash.get(mention)); if(m1.find()) { String type[]=m1.group(1).split(","); String W[]=m1.group(2).split(","); String P[]=m1.group(3).split(","); String M[]=m1.group(4).split(","); String F[]=m1.group(5).split(","); String S[]=m1.group(6).split(","); String mention_tmp=mention; for(int i=0;i<type.length;i++) { String patt="^(.*?)("+type[i]+")(.*?)$"; Pattern ptmp = Pattern.compile(patt); Matcher mtmp = ptmp.matcher(mention_tmp); if(mtmp.find()) { String mtmp1=mtmp.group(1); for(int j=mtmp1.length();j<(mtmp1.length()+mtmp.group(2).length());j++) { character_hash.put(j,"A"); } String mtmp2_tmp=""; for(int j=0;j<mtmp.group(2).length();j++){mtmp2_tmp=mtmp2_tmp+"@";} mention_tmp=mtmp.group(1)+mtmp2_tmp+mtmp.group(3); } else { System.out.println("Error! Cannot find component: m1\ttype\t"+mention); } } for(int i=0;i<W.length;i++) { String patt="^(.*?)("+W[i]+")(.*?)$"; Pattern ptmp = Pattern.compile(patt); Matcher mtmp = ptmp.matcher(mention_tmp); if(mtmp.find()) { String mtmp1=mtmp.group(1); for(int j=mtmp1.length();j<(mtmp1.length()+mtmp.group(2).length());j++) { character_hash.put(j,"W"); } String mtmp2_tmp=""; for(int j=0;j<mtmp.group(2).length();j++){mtmp2_tmp=mtmp2_tmp+"@";} mention_tmp=mtmp.group(1)+mtmp2_tmp+mtmp.group(3); } else { System.out.println("Error! Cannot find component: m1\tW\t"+mention); } } for(int i=0;i<P.length;i++) { P[i]=P[i].replaceAll("([^A-Za-z0-9@])", "\\\\$1"); String patt="^(.*?)("+P[i]+")(.*?)$"; Pattern ptmp = Pattern.compile(patt); Matcher mtmp = ptmp.matcher(mention_tmp); if(mtmp.find()) { for(int j=mtmp.group(1).length();j<(mtmp.group(1).length()+mtmp.group(2).length());j++) { character_hash.put(j,"P"); } String mtmp2_tmp=""; for(int j=0;j<mtmp.group(2).length();j++){mtmp2_tmp=mtmp2_tmp+"@";} mention_tmp=mtmp.group(1)+mtmp2_tmp+mtmp.group(3); } else { System.out.println("Error! Cannot find component: m1\tP\t"+mention); } } for(int i=0;i<M.length;i++) { M[i]=M[i].replace("*", "\\*"); String patt="^(.*?)("+M[i]+")(.*?)$"; Pattern ptmp = Pattern.compile(patt); Matcher mtmp = ptmp.matcher(mention_tmp); if(mtmp.find()) { for(int j=mtmp.group(1).length();j<(mtmp.group(1).length()+mtmp.group(2).length());j++) { character_hash.put(j,"M"); } String mtmp2_tmp=""; for(int j=0;j<mtmp.group(2).length();j++){mtmp2_tmp=mtmp2_tmp+"@";} mention_tmp=mtmp.group(1)+mtmp2_tmp+mtmp.group(3); } else { System.out.println("Error! Cannot find component: m1\tM\t"+mention); } } for(int i=0;i<F.length;i++) { F[i]=F[i].replaceAll("([^A-Za-z0-9@])", "\\\\$1"); String patt="^(.*?)("+F[i]+")(.*?)$"; Pattern ptmp = Pattern.compile(patt); Matcher mtmp = ptmp.matcher(mention_tmp); if(mtmp.find()) { String mtmp1=mtmp.group(1); for(int j=mtmp1.length();j<(mtmp1.length()+mtmp.group(2).length());j++) { character_hash.put(j,"F"); } String mtmp2_tmp=""; for(int j=0;j<mtmp.group(2).length();j++){mtmp2_tmp=mtmp2_tmp+"@";} mention_tmp=mtmp.group(1)+mtmp2_tmp+mtmp.group(3); } else { System.out.println("Error! Cannot find component: m1\tF\t"+mention); } } for(int i=0;i<S.length;i++) { String patt="^(.*?)("+S[i]+")(.*?)$"; Pattern ptmp = Pattern.compile(patt); Matcher mtmp = ptmp.matcher(mention_tmp); if(mtmp.find()) { String mtmp1=mtmp.group(1); for(int j=mtmp1.length();j<(mtmp1.length()+mtmp.group(2).length());j++) { character_hash.put(j,"S"); } String mtmp2_tmp=""; for(int j=0;j<mtmp.group(2).length();j++){mtmp2_tmp=mtmp2_tmp+"@";} mention_tmp=mtmp.group(1)+mtmp2_tmp+mtmp.group(3); } else { System.out.println("Error! Cannot find component: m1\tS\t"+mention); } } } else if(m1_1.find()) { String type[]=m1_1.group(1).split(","); String T[]=m1_1.group(2).split(","); String P[]=m1_1.group(4).split(","); String M[]=m1_1.group(5).split(","); String F[]=m1_1.group(6).split(","); String mention_tmp=mention; for(int i=0;i<type.length;i++) { String patt="^(.*?)("+type[i]+")(.*?)$"; Pattern ptmp = Pattern.compile(patt); Matcher mtmp = ptmp.matcher(mention_tmp); if(mtmp.find()) { String mtmp1=mtmp.group(1); for(int j=mtmp1.length();j<(mtmp1.length()+mtmp.group(2).length());j++) { character_hash.put(j,"A"); } String mtmp2_tmp=""; for(int j=0;j<mtmp.group(2).length();j++){mtmp2_tmp=mtmp2_tmp+"@";} mention_tmp=mtmp.group(1)+mtmp2_tmp+mtmp.group(3); } else { System.out.println("Error! Cannot find component: m1_1\ttype\t"+mention); } } for(int i=0;i<T.length;i++) { String patt="^(.*?)("+T[i]+")(.*?)$"; Pattern ptmp = Pattern.compile(patt); Matcher mtmp = ptmp.matcher(mention_tmp); if(mtmp.find()) { String mtmp1=mtmp.group(1); for(int j=mtmp1.length();j<(mtmp1.length()+mtmp.group(2).length());j++) { character_hash.put(j,"T"); } String mtmp2_tmp=""; for(int j=0;j<mtmp.group(2).length();j++){mtmp2_tmp=mtmp2_tmp+"@";} mention_tmp=mtmp.group(1)+mtmp2_tmp+mtmp.group(3); } else { System.out.println("Error! Cannot find component: m1_1\tT\t"+mention); } } for(int i=0;i<P.length;i++) { P[i]=P[i].replaceAll("([^A-Za-z0-9@])", "\\\\$1"); String patt="^(.*)("+P[i]+")(.*)$"; Pattern ptmp = Pattern.compile(patt); Matcher mtmp = ptmp.matcher(mention_tmp); if(mtmp.find()) { for(int j=mtmp.group(1).length();j<(mtmp.group(1).length()+mtmp.group(2).length());j++) { character_hash.put(j,"P"); } String mtmp2_tmp=""; for(int j=0;j<mtmp.group(2).length();j++){mtmp2_tmp=mtmp2_tmp+"@";} mention_tmp=mtmp.group(1)+mtmp2_tmp+mtmp.group(3); } else { System.out.println("Error! Cannot find component: m1_1\tP\t"+mention); } } for(int i=0;i<M.length;i++) { M[i]=M[i].replace("*", "\\*"); String patt="^(.*?)("+M[i]+")(.*?)$"; Pattern ptmp = Pattern.compile(patt); Matcher mtmp = ptmp.matcher(mention_tmp); if(mtmp.find()) { for(int j=mtmp.group(1).length();j<(mtmp.group(1).length()+mtmp.group(2).length());j++) { character_hash.put(j,"M"); } String mtmp2_tmp=""; for(int j=0;j<mtmp.group(2).length();j++){mtmp2_tmp=mtmp2_tmp+"@";} mention_tmp=mtmp.group(1)+mtmp2_tmp+mtmp.group(3); } else { System.out.println("Error! Cannot find component: m1_1\tM\t"+mention); } } for(int i=0;i<F.length;i++) { F[i]=F[i].replaceAll("([^A-Za-z0-9@])", "\\\\$1"); String patt="^(.*?)("+F[i]+")(.*?)$"; Pattern ptmp = Pattern.compile(patt); Matcher mtmp = ptmp.matcher(mention_tmp); if(mtmp.find()) { String mtmp1=mtmp.group(1); for(int j=mtmp1.length();j<(mtmp1.length()+mtmp.group(2).length());j++) { character_hash.put(j,"F"); } String mtmp2_tmp=""; for(int j=0;j<mtmp.group(2).length();j++){mtmp2_tmp=mtmp2_tmp+"@";} mention_tmp=mtmp.group(1)+mtmp2_tmp+mtmp.group(3); } else { System.out.println("Error! Cannot find component: m1_1\tF\t"+mention); } } } else if(m2.find()) { String type[]=m2.group(1).split(","); String W[]=m2.group(2).split(","); String P[]=m2.group(3).split(","); String M[]=m2.group(4).split(","); String F[]=m2.group(5).split(","); String mention_tmp=mention; for(int i=0;i<type.length;i++) { String patt="^(.*?)("+type[i]+")(.*?)$"; Pattern ptmp = Pattern.compile(patt); Matcher mtmp = ptmp.matcher(mention_tmp); if(mtmp.find()) { String mtmp1=mtmp.group(1); for(int j=mtmp1.length();j<(mtmp1.length()+mtmp.group(2).length());j++) { character_hash.put(j,"A"); } String mtmp2_tmp=""; for(int j=0;j<mtmp.group(2).length();j++){mtmp2_tmp=mtmp2_tmp+"@";} mention_tmp=mtmp.group(1)+mtmp2_tmp+mtmp.group(3); } else { System.out.println("Error! Cannot find component: m2\tType\t"+mention); } } for(int i=0;i<W.length;i++) { String patt="^(.*?)("+W[i]+")(.*?)$"; Pattern ptmp = Pattern.compile(patt); Matcher mtmp = ptmp.matcher(mention_tmp); if(mtmp.find()) { String mtmp1=mtmp.group(1); for(int j=mtmp1.length();j<(mtmp1.length()+mtmp.group(2).length());j++) { character_hash.put(j,"W"); } String mtmp2_tmp=""; for(int j=0;j<mtmp.group(2).length();j++){mtmp2_tmp=mtmp2_tmp+"@";} mention_tmp=mtmp.group(1)+mtmp2_tmp+mtmp.group(3); } else { System.out.println("Error! Cannot find component: m2\tW\t"+mention); } } for(int i=0;i<P.length;i++) { P[i]=P[i].replaceAll("([^A-Za-z0-9@])", "\\\\$1"); String patt="^(.*?)("+P[i]+")(.*?)$"; Pattern ptmp = Pattern.compile(patt); Matcher mtmp = ptmp.matcher(mention_tmp); if(mtmp.find()) { String mtmp1=mtmp.group(1); for(int j=mtmp1.length();j<(mtmp1.length()+mtmp.group(2).length());j++) { character_hash.put(j,"P"); } String mtmp2_tmp=""; for(int j=0;j<mtmp.group(2).length();j++){mtmp2_tmp=mtmp2_tmp+"@";} mention_tmp=mtmp.group(1)+mtmp2_tmp+mtmp.group(3); } else { System.out.println("Error! Cannot find component: m2\tP\t"+mention); } } for(int i=0;i<M.length;i++) { M[i]=M[i].replace("*", "\\*"); String patt="^(.*?)("+M[i]+")(.*?)$"; Pattern ptmp = Pattern.compile(patt); Matcher mtmp = ptmp.matcher(mention_tmp); if(mtmp.find()) { String mtmp1=mtmp.group(1); for(int j=mtmp1.length();j<(mtmp1.length()+mtmp.group(2).length());j++) { character_hash.put(j,"M"); } String mtmp2_tmp=""; for(int j=0;j<mtmp.group(2).length();j++){mtmp2_tmp=mtmp2_tmp+"@";} mention_tmp=mtmp.group(1)+mtmp2_tmp+mtmp.group(3); } else { System.out.println("Error! Cannot find component: m2\tM\t"+mention); } } for(int i=0;i<F.length;i++) { F[i]=F[i].replaceAll("([^A-Za-z0-9@])", "\\\\$1"); String patt="^(.*?)("+F[i]+")(.*?)$"; Pattern ptmp = Pattern.compile(patt); Matcher mtmp = ptmp.matcher(mention_tmp); if(mtmp.find()) { String mtmp1=mtmp.group(1); for(int j=mtmp1.length();j<(mtmp1.length()+mtmp.group(2).length());j++) { character_hash.put(j,"F"); } String mtmp2_tmp=""; for(int j=0;j<mtmp.group(2).length();j++){mtmp2_tmp=mtmp2_tmp+"@";} mention_tmp=mtmp.group(1)+mtmp2_tmp+mtmp.group(3); } else { System.out.println("Error! Cannot find component: m2\tF\t"+mention); } } } else if(m3.find()) { String type[]=m3.group(1).split(","); String T[]=m3.group(2).split(","); String P[]=m3.group(4).split(","); String M[]=m3.group(5).split(","); String mention_tmp=mention; for(int i=0;i<type.length;i++) { String patt="^(.*?)("+type[i]+")(.*?)$"; Pattern ptmp = Pattern.compile(patt); Matcher mtmp = ptmp.matcher(mention_tmp); if(mtmp.find()) { String mtmp1=mtmp.group(1); for(int j=mtmp1.length();j<(mtmp1.length()+mtmp.group(2).length());j++) { character_hash.put(j,"A"); } String mtmp2_tmp=""; for(int j=0;j<mtmp.group(2).length();j++){mtmp2_tmp=mtmp2_tmp+"@";} mention_tmp=mtmp.group(1)+mtmp2_tmp+mtmp.group(3); } else { System.out.println("Error! Cannot find component: m3\tType\t"+mention); } } for(int i=0;i<P.length;i++) { P[i]=P[i].replaceAll("([^A-Za-z0-9@])", "\\\\$1"); String patt="^(.*?)("+P[i]+")(.*?)$"; Pattern ptmp = Pattern.compile(patt); Matcher mtmp = ptmp.matcher(mention_tmp); if(mtmp.find()) { String mtmp1=mtmp.group(1); for(int j=mtmp1.length();j<(mtmp1.length()+mtmp.group(2).length());j++) { character_hash.put(j,"P"); } String mtmp2_tmp=""; for(int j=0;j<mtmp.group(2).length();j++){mtmp2_tmp=mtmp2_tmp+"@";} mention_tmp=mtmp.group(1)+mtmp2_tmp+mtmp.group(3); } else { System.out.println("Error! Cannot find component: m3\tP\t"+mention); } } for(int i=0;i<T.length;i++) { String patt="^(.*?)("+T[i]+")(.*?)$"; Pattern ptmp = Pattern.compile(patt); Matcher mtmp = ptmp.matcher(mention_tmp); if(mtmp.find()) { String mtmp1=mtmp.group(1); for(int j=mtmp1.length();j<(mtmp1.length()+mtmp.group(2).length());j++) { character_hash.put(j,"T"); } String mtmp2_tmp=""; for(int j=0;j<mtmp.group(2).length();j++){mtmp2_tmp=mtmp2_tmp+"@";} mention_tmp=mtmp.group(1)+mtmp2_tmp+mtmp.group(3); } else { System.out.println("Error! Cannot find component: m3\tT\t"+mention); } } for(int i=0;i<M.length;i++) { M[i]=M[i].replace("*", "\\*"); String patt="^(.*?)("+M[i]+")(.*?)$"; Pattern ptmp = Pattern.compile(patt); Matcher mtmp = ptmp.matcher(mention_tmp); if(mtmp.find()) { String mtmp1=mtmp.group(1); for(int j=mtmp1.length();j<(mtmp1.length()+mtmp.group(2).length());j++) { character_hash.put(j,"M"); } String mtmp2_tmp=""; for(int j=0;j<mtmp.group(2).length();j++){mtmp2_tmp=mtmp2_tmp+"@";} mention_tmp=mtmp.group(1)+mtmp2_tmp+mtmp.group(3); } else { System.out.println("Error! Cannot find component: m3\tM\t"+mention); } } } else if(m4.find()) { String type[]=m4.group(1).split(","); String W[]=m4.group(2).split(","); String P[]=m4.group(3).split(","); String M[]=m4.group(4).split(","); String mention_tmp=mention; for(int i=0;i<type.length;i++) { String patt="^(.*?)("+type[i]+")(.*?)$"; Pattern ptmp = Pattern.compile(patt); Matcher mtmp = ptmp.matcher(mention_tmp); if(mtmp.find()) { String mtmp1=mtmp.group(1); for(int j=mtmp1.length();j<(mtmp1.length()+mtmp.group(2).length());j++) { character_hash.put(j,"A"); } String mtmp2_tmp=""; for(int j=0;j<mtmp.group(2).length();j++){mtmp2_tmp=mtmp2_tmp+"@";} mention_tmp=mtmp.group(1)+mtmp2_tmp+mtmp.group(3); } else { System.out.println("Error! Cannot find component: m4\tType\t"+mention); } } for(int i=0;i<W.length;i++) { String patt="^(.*?)("+W[i]+")(.*?)$"; Pattern ptmp = Pattern.compile(patt); Matcher mtmp = ptmp.matcher(mention_tmp); if(mtmp.find()) { String mtmp1=mtmp.group(1); for(int j=mtmp1.length();j<(mtmp1.length()+mtmp.group(2).length());j++) { character_hash.put(j,"W"); } String mtmp2_tmp=""; for(int j=0;j<mtmp.group(2).length();j++){mtmp2_tmp=mtmp2_tmp+"@";} mention_tmp=mtmp.group(1)+mtmp2_tmp+mtmp.group(3); } else { System.out.println("Error! Cannot find component: m4\tW\t"+mention); } } for(int i=0;i<P.length;i++) { P[i]=P[i].replaceAll("([^A-Za-z0-9@])", "\\\\$1"); String patt="^(.*?)("+P[i]+")(.*?)$"; Pattern ptmp = Pattern.compile(patt); Matcher mtmp = ptmp.matcher(mention_tmp); if(mtmp.find()) { String mtmp1=mtmp.group(1); for(int j=mtmp1.length();j<(mtmp1.length()+mtmp.group(2).length());j++) { character_hash.put(j,"P"); } String mtmp2_tmp=""; for(int j=0;j<mtmp.group(2).length();j++){mtmp2_tmp=mtmp2_tmp+"@";} mention_tmp=mtmp.group(1)+mtmp2_tmp+mtmp.group(3); } else { System.out.println("Error! Cannot find component: m4\tP\t"+mention); } } for(int i=0;i<M.length;i++) { M[i]=M[i].replace("*", "\\*"); String patt="^(.*?)("+M[i]+")(.*?)$"; Pattern ptmp = Pattern.compile(patt); Matcher mtmp = ptmp.matcher(mention_tmp); if(mtmp.find()) { String mtmp1=mtmp.group(1); for(int j=mtmp1.length();j<(mtmp1.length()+mtmp.group(2).length());j++) { character_hash.put(j,"M"); } String mtmp2_tmp=""; for(int j=0;j<mtmp.group(2).length();j++){mtmp2_tmp=mtmp2_tmp+"@";} mention_tmp=mtmp.group(1)+mtmp2_tmp+mtmp.group(3); } else { System.out.println("Error! Cannot find component: m4\tM\t"+mention); } } } else if(m5.find()) { String type[]=m5.group(1).split(","); String T[]=m5.group(2).split(","); String P[]=m5.group(3).split(","); String M[]=m5.group(4).split(","); String D[]=m5.group(5).split(","); String mention_tmp=mention; for(int i=0;i<type.length;i++) { String patt="^(.*?)("+type[i]+")(.*?)$"; Pattern ptmp = Pattern.compile(patt); Matcher mtmp = ptmp.matcher(mention_tmp); if(mtmp.find()) { String mtmp1=mtmp.group(1); for(int j=mtmp1.length();j<(mtmp1.length()+mtmp.group(2).length());j++) { character_hash.put(j,"A"); } String mtmp2_tmp=""; for(int j=0;j<mtmp.group(2).length();j++){mtmp2_tmp=mtmp2_tmp+"@";} mention_tmp=mtmp.group(1)+mtmp2_tmp+mtmp.group(3); } else { System.out.println("Error! Cannot find component: m5\tType\t"+mention); } } for(int i=0;i<T.length;i++) { String patt="^(.*?)("+T[i]+")(.*?)$"; Pattern ptmp = Pattern.compile(patt); Matcher mtmp = ptmp.matcher(mention_tmp); if(mtmp.find()) { String mtmp1=mtmp.group(1); for(int j=mtmp1.length();j<(mtmp1.length()+mtmp.group(2).length());j++) { character_hash.put(j,"T"); } String mtmp2_tmp=""; for(int j=0;j<mtmp.group(2).length();j++){mtmp2_tmp=mtmp2_tmp+"@";} mention_tmp=mtmp.group(1)+mtmp2_tmp+mtmp.group(3); } else { System.out.println("Error! Cannot find component: m5\tT\t"+mention); } } for(int i=0;i<P.length;i++) { P[i]=P[i].replaceAll("([^A-Za-z0-9@])", "\\\\$1"); String patt="^(.*?)("+P[i]+")(.*?)$"; Pattern ptmp = Pattern.compile(patt); Matcher mtmp = ptmp.matcher(mention_tmp); if(mtmp.find()) { String mtmp1=mtmp.group(1); for(int j=mtmp1.length();j<(mtmp1.length()+mtmp.group(2).length());j++) { character_hash.put(j,"P"); } String mtmp2_tmp=""; for(int j=0;j<mtmp.group(2).length();j++){mtmp2_tmp=mtmp2_tmp+"@";} mention_tmp=mtmp.group(1)+mtmp2_tmp+mtmp.group(3); } else { System.out.println("Error! Cannot find component: m5\tP\t"+mention); } } for(int i=0;i<M.length;i++) { M[i]=M[i].replace("*", "\\*"); String patt="^(.*?)("+M[i]+")(.*?)$"; Pattern ptmp = Pattern.compile(patt); Matcher mtmp = ptmp.matcher(mention_tmp); if(mtmp.find()) { String mtmp1=mtmp.group(1); for(int j=mtmp1.length();j<(mtmp1.length()+mtmp.group(2).length());j++) { character_hash.put(j,"M"); } String mtmp2_tmp=""; for(int j=0;j<mtmp.group(2).length();j++){mtmp2_tmp=mtmp2_tmp+"@";} mention_tmp=mtmp.group(1)+mtmp2_tmp+mtmp.group(3); } else { System.out.println("Error! Cannot find component: m5\tM\t"+mention); } } for(int i=0;i<D.length;i++) { D[i]=D[i].replaceAll("([^A-Za-z0-9@])", "\\\\$1"); String patt="^(.*?)("+D[i]+")(.*?)$"; Pattern ptmp = Pattern.compile(patt); Matcher mtmp = ptmp.matcher(mention_tmp); if(mtmp.find()) { String mtmp1=mtmp.group(1); for(int j=mtmp1.length();j<(mtmp1.length()+mtmp.group(2).length());j++) { character_hash.put(j,"D"); } String mtmp2_tmp=""; for(int j=0;j<mtmp.group(2).length();j++){mtmp2_tmp=mtmp2_tmp+"@";} mention_tmp=mtmp.group(1)+mtmp2_tmp+mtmp.group(3); } else { System.out.println("Error! Cannot find component: m5\tD\t"+mention); } } } else if(m6.find()) { String RS[]=m6.group(1).split(","); String mention_tmp=mention; for(int i=0;i<RS.length;i++) { RS[i]=RS[i].replaceAll("([\\[\\]])", "\\\\$1"); String patt="^(.*?)("+RS[i]+")(.*?)$"; Pattern ptmp = Pattern.compile(patt); Matcher mtmp = ptmp.matcher(mention_tmp); if(mtmp.find()) { String mtmp1=mtmp.group(1); for(int j=mtmp1.length();j<(mtmp1.length()+mtmp.group(2).length());j++) { character_hash.put(j,"R"); } String mtmp2_tmp=""; for(int j=0;j<mtmp.group(2).length();j++){mtmp2_tmp=mtmp2_tmp+"@";} mention_tmp=mtmp.group(1)+mtmp2_tmp+mtmp.group(3); } else { System.out.println("Error! Cannot find component: m6\tType\t"+mention); } } } else { System.out.println("Error! Annotation component cannot match RegEx. " + mention); } } mentionlistbw.write(mention+"\t"+mention2type_hash.get(mention)+"\n"); if(TrainTest.equals("Train")) { mentiondata.write("I I I I I I I I I I I I I I I I I I I\n"); } else { mentiondata.write("I I I I I I I I I I I I I I I I I I\n"); } String mention_tmp=mention; String mention_org=mention; mention_tmp = mention_tmp.replaceAll("([0-9])([A-Za-z])", "$1 $2"); mention_tmp = mention_tmp.replaceAll("([A-Za-z])([0-9])", "$1 $2"); mention_tmp = mention_tmp.replaceAll("([A-Z])([a-z])", "$1 $2"); mention_tmp = mention_tmp.replaceAll("([a-z])([A-Z])", "$1 $2"); mention_tmp = mention_tmp.replaceAll("(.+)fs", "$1 fs"); mention_tmp = mention_tmp.replaceAll("fs(.+)", "fs $1"); mention_tmp = mention_tmp.replaceAll("[ ]+", " "); String regex="\\s+|(?=\\p{Punct})|(?<=\\p{Punct})"; String Tokens[]=mention_tmp.split(regex); start=0; last=0; for(int i=0;i<Tokens.length;i++) { if(Tokens[i].length()>0) { String tkni=Tokens[i].replaceAll("([\\{\\}\\[\\]\\+\\-\\(\\)\\*\\?\\/\\\\])", "\\\\$1"); Pattern Pcn = Pattern.compile("^([ ]*)("+tkni+")(.*)$"); Matcher mPcn = Pcn.matcher(mention_org); if(mPcn.find()) { last=last+mPcn.group(1).length(); mention_org=mPcn.group(3); } start=last+1; last=start+Tokens[i].length()-1; //Number of Numbers [0-9] String Num_num=""; String tmp=Tokens[i]; tmp=tmp.replaceAll("[^0-9]",""); if(tmp.length()>3){Num_num="N:4+";}else{Num_num="N:"+ tmp.length();} //Number of Uppercase [A-Z] String Num_Uc=""; tmp=Tokens[i]; tmp=tmp.replaceAll("[^A-Z]",""); if(tmp.length()>3){Num_Uc="U:4+";}else{Num_Uc="U:"+ tmp.length();} //Number of Lowercase [a-z] String Num_Lc=""; tmp=Tokens[i]; tmp=tmp.replaceAll("[^a-z]",""); if(tmp.length()>3){Num_Lc="L:4+";}else{Num_Lc="L:"+ tmp.length();} //Number of ALL char String Num_All=""; if(Tokens[i].length()>3){Num_All="A:4+";}else{Num_All="A:"+ Tokens[i].length();} //specific character (;:,.->+_) String SpecificC=""; tmp=Tokens[i]; if(Tokens[i].equals(";") || Tokens[i].equals(":") || Tokens[i].equals(",") || Tokens[i].equals(".") || Tokens[i].equals("-") || Tokens[i].equals(">") || Tokens[i].equals("+") || Tokens[i].equals("_")) { SpecificC="-SpecificC1-"; } else if(Tokens[i].equals("(") || Tokens[i].equals(")")) { SpecificC="-SpecificC2-"; } else if(Tokens[i].equals("{") || Tokens[i].equals("}")) { SpecificC="-SpecificC3-"; } else if(Tokens[i].equals("[") || Tokens[i].equals("]")) { SpecificC="-SpecificC4-"; } else if(Tokens[i].equals("\\") || Tokens[i].equals("/")) { SpecificC="-SpecificC5-"; } else { SpecificC="__nil__"; } //mutation level String Mlevel=""; if(Tokens[i].equals("p")){Mlevel="-ProteinLevel-";} else if(Tokens[i].matches("^[cgmr]$")){Mlevel="-DNALevel-";} else{Mlevel="__nil__";} //mutation type String Mtype=""; String tkn=Tokens[i].toLowerCase(); String last2_tkn=""; String last_tkn=""; String next_tkn=""; String next2_tkn=""; if(i>1){last2_tkn=Tokens[i-2];} if(i>0){last_tkn=Tokens[i-1];} if(Tokens.length>1 && i<Tokens.length-1){next_tkn=Tokens[i+1];} if(Tokens.length>2 && i<Tokens.length-2){next2_tkn=Tokens[i+2];} if(tkn.toLowerCase().matches("^(insert(ion|ed|ing|)|duplicat(ion|e|ed|ing)|delet(ion|e|ed|ing)|frameshift|missense|lack(|ed|ing)|los(e|ing|ed)|copy|repeat(|ed)|inversion)$")) {Mtype="-Mtype- -MtypeFull-";} else if(tkn.matches("^(nsert(ion|ed|ing|)|uplicat(ion|e|ed|ing)|elet(ion|e|ed|ing)|rameshift|issense|ack(|ed|ing)|os(e|ing|ed)|opy|epeat(|ed)|nversion)$")) {Mtype="-Mtype- -MtypeFull_suffix-";} else if(tkn.matches("^(del|ins|delins|indel|dup|inv)$")) {Mtype="-Mtype- -MtypeTri-";} else if(tkn.matches("^(start[a-z]*|found|identif[a-z]+|substit[a-z]*|lead[a-z]*|exchang[a-z]*|chang[a-z]*|mutant[a-z]*|mutate[a-z]*|devia[a-z]*|modif[a-z]*|alter[a-z]*|switch[a-z]*|variat[a-z]*|instead[a-z]*|replac[a-z]*|in place|convert[a-z]*|becom[a-z]*|transition|transversion)$")) {Mtype="-SurroundingWord- -CausingVerb-";} else if(tkn.matches("^(caus(e|es|ing)|lead(|s|ing|ed)|encod(e|es|ing|ed)|result(|s|ing|ed)|produc(e|es|ing|ed)|chang(e|es|ing|ed)|covert(|s|ing|ed)|correspond(|s|ing|ed)|predict(|s|ing|ed)|cod(e|es|ing|ed)|concordanc(e|es|ing|ed)|concordant|consist(|s|ing|ed)|encod(e|es|ing|ed)|represent(|s|ing|ed)|led|responsible|denot(e|es|ing|ed)|designat(e|es|ing|ed)|introduc(e|es|ing|ed)|characteriz(e|es|ing|ed)|bring|involv(e|es|ing|ed)|implicat(e|es|ing|ed)|indicat(e|es|ing|ed)|express(|s|ing|ed)|behav(e|es|ing|ed)|suggest(|s|ing|ed)|impl(y|ies|ed|ying)|presum(e|es|ing|ed))$")) {Mtype="-SurroundingWord- -CausingVerb-";} else if(tkn.matches("^(polymorphic|site|point|premature|replacement|replac(e|es|ed|ing)|substitution(s|)|polar|charged|amphipathic|hydrophobic|amino|acid(s|)|nucleotide(s|)|mutation(s|)|position(s|)|posi|pos|islet|liver|base|pair(s|)|bp|bps|bp|residue(s|)|radical|codon|aa|nt|alpha|beta|gamma|ezta|theta|delta|tetranucleotide|polymorphism|terminal)$")) {Mtype="-SurroundingWord- -SurroundingWord2-";} else if(tkn.matches("^((has|have|had) been|is|are|was|were)$")) {Mtype="-SurroundingWord- -BeVerb-";} else if(Tokens[i].matches("^(a|an|the|)$")) {Mtype="-SurroundingWord- -Article-";} else if(Tokens[i].matches("^(which|where|what|that)$")) {Mtype="-SurroundingWord- -RelativePronouns-";} else if(Tokens[i].matches("^(in|to|into|for|of|by|with|at|locat(e|ed|es)|among|between|through|rather|than|either)$")) {Mtype="-SurroundingWord- -Preposition-";} else if(tkn.equals("/") && last_tkn.matches("(ins|del)") && next_tkn.toLowerCase().matches("(ins|del)")) {Mtype="-Mtype- -MtypeTri-";} else if((last2_tkn.toLowerCase().equals("/") && last_tkn.toLowerCase().equals("\\")) || (next_tkn.toLowerCase().equals("/") && next2_tkn.toLowerCase().equals("\\"))) {Mtype="-Mtype- -MtypeTri-";} else {Mtype="__nil__ __nil__";} //DNA symbols String DNASym=""; if(tkn.matches("^(adenine|guanine|thymine|cytosine)$")){DNASym="-DNASym- -DNASymFull-";} else if(tkn.matches("^(denine|uanine|hymine|ytosine)$")){DNASym="-DNASym- -DNASymFull_suffix-";} else if(Tokens[i].matches("^[ATCGU]+$")){DNASym="-DNASym- -DNASymChar-";} else {DNASym="__nil__ __nil__";} //Protein symbols String ProteinSym=""; if(tkn.matches("^(glutamine|glutamic|leucine|valine|isoleucine|lysine|alanine|glycine|aspartate|methionine|threonine|histidine|aspartic|asparticacid|arginine|asparagine|tryptophan|proline|phenylalanine|cysteine|serine|glutamate|tyrosine|stop|frameshift)$")){ProteinSym="-ProteinSym- -ProteinSymFull-";} else if(tkn.matches("^(lutamine|lutamic|eucine|aline|soleucine|ysine|lanine|lycine|spartate|ethionine|hreonine|istidine|spartic|sparticacid|rginine|sparagine|ryptophan|roline|henylalanine|ysteine|erine|lutamate|yrosine|top|rameshift)$")){ProteinSym="-ProteinSym- -ProteinSymFull_suffix-";} else if(tkn.matches("^(cys|ile|ser|gln|met|asn|pro|lys|asp|thr|phe|ala|gly|his|leu|arg|trp|val|glu|tyr)$")){ProteinSym="-ProteinSym- -ProteinSymTri-";} else if(tkn.matches("^(ys|le|er|ln|et|sn|ro|ys|sp|hr|phe|la|ly|is|eu|rg|rp|al|lu|yr)$")){ProteinSym="-ProteinSym- -ProteinSymTri_suffix-";} else if(Tokens[i].matches("^[CISQMNPKDTFAGHLRWVEYX]$") && !next_tkn.toLowerCase().matches("^[ylsrhpiera]")) {ProteinSym="-ProteinSym- -ProteinSymChar-";} else if(Tokens[i].matches("^[CISGMPLTHAVF]$") && next_tkn.toLowerCase().matches("^[ylsrhpiera]")) {ProteinSym="-ProteinSym- -ProteinSymChar-";} else {ProteinSym="__nil__ __nil__";} //IVS/EX String IVSEX=""; if(tkn.matches("^(ivs|ex)$")){IVSEX="-IVSEX-";} else if(Tokens[i].equals("E") && last_tkn.equals("x")){IVSEX="-IVSEX-";} else if(last_tkn.equals("E") && Tokens[i].equals("x")){IVSEX="-IVSEX-";} else {IVSEX="__nil__";} //FSX feature String FSXfeature=""; if(tkn.matches("^(fs|fsx|x|\\*)$")){FSXfeature="-FSX-";} else if(last_tkn.toLowerCase().equals("s") && tkn.equals("x")){FSXfeature="-FSX-";} else {FSXfeature="__nil__";} //position type String PositionType=""; if(tkn.matches("^(nucleotide|codon|amino|acid|position|bp|b|base|pair)$")){PositionType="-PositionType-";} else if(tkn.matches("^(single|one|two|three|four|five|six|seven|eight|nine|ten|[0-9]+)$")){PositionType="-PositionNum-";} else {PositionType="__nil__";} //sequence location String SeqLocat=""; if(tkn.matches("^(intron|exon|promoter|utr)$")){SeqLocat="-SeqLocat-";} else {SeqLocat="__nil__";} //RS String RScode=""; if(tkn.equals("rs")){RScode="-RScode-";} else {RScode="__nil__";} if(TrainTest.equals("Train")) { mentiondata.write(Tokens[i]+" "+Num_num+" "+Num_Uc+" "+Num_Lc+" "+Num_All+" "+SpecificC+" "+Mlevel+" "+Mtype+" "+DNASym+" "+ProteinSym+" "+IVSEX+" "+FSXfeature+" "+PositionType+" "+SeqLocat+" "+RScode+" "+character_hash.get(start-1)+"\n"); } else { mentiondata.write(Tokens[i]+" "+Num_num+" "+Num_Uc+" "+Num_Lc+" "+Num_All+" "+SpecificC+" "+Mlevel+" "+Mtype+" "+DNASym+" "+ProteinSym+" "+IVSEX+" "+FSXfeature+" "+PositionType+" "+SeqLocat+" "+RScode+"\n"); } } } mentiondata.write("\n"); } mentionlistbw.close(); mentiondata.close(); } catch(IOException e1){ System.out.println("[toPostMEData]: "+e1+" Input file is not exist.");} } public void toPostMEModel(String FilenamePostMEdata) throws IOException { Process process = null; String line = null; InputStream is = null; InputStreamReader isr = null; BufferedReader br = null; Runtime runtime = Runtime.getRuntime(); String OS=System.getProperty("os.name").toLowerCase(); String cmd=""; if(OS.contains("windows")) { cmd ="CRF/crf_learn -f 3 -c 4.0 CRF/template_UB.mention "+FilenamePostMEdata+" CRF/ComponentExtraction.Model.new"; } else //if(OS.contains("nux")||OS.contains("nix")) { cmd ="./CRF/crf_learn -f 3 -c 4.0 CRF/template_UB.mention "+FilenamePostMEdata+" CRF/ComponentExtraction.Model.new"; } try { process = runtime.exec(cmd); is = process.getInputStream(); isr = new InputStreamReader(is); br = new BufferedReader(isr); while ( (line = br.readLine()) != null) { System.out.println(line); System.out.flush(); } is.close(); isr.close(); br.close(); } catch (IOException e) { System.out.println(e); runtime.exit(0); } } public void toPostMEoutput(String FilenamePostMEdata,String FilenamePostMEoutput) throws IOException { /* * Recognizing components */ Runtime runtime = Runtime.getRuntime(); String OS=System.getProperty("os.name").toLowerCase(); String cmd=""; if(OS.contains("windows")) { cmd ="CRF/crf_test -m CRF/ComponentExtraction.Model -o "+FilenamePostMEoutput+" "+FilenamePostMEdata; } else //if(OS.contains("nux")||OS.contains("nix")) { cmd ="./CRF/crf_test -m CRF/ComponentExtraction.Model -o "+FilenamePostMEoutput+" "+FilenamePostMEdata; } try { File f = new File(FilenamePostMEoutput); BufferedWriter fr = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(f), "UTF-8")); Process process = runtime.exec(cmd); InputStream is = process.getInputStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); String line=""; while ( (line = br.readLine()) != null) { fr.write(line); fr.newLine(); fr.flush(); } is.close(); isr.close(); br.close(); fr.close(); } catch (IOException e) { System.out.println(e); runtime.exit(0); } } public void output2PubTator(String FilenamePostMEml,String FilenamePostMEoutput,String FilenamePostME,String FilenamePubTator) throws IOException { try { ArrayList<String> mentionlist = new ArrayList<String>(); ArrayList<String> identifierlist = new ArrayList<String>(); ArrayList<String> typelist = new ArrayList<String>(); BufferedReader inputfile = new BufferedReader(new InputStreamReader(new FileInputStream(FilenamePostMEml), "UTF-8")); int count=0; HashMap<Integer,Integer> boundary_hash = new HashMap<Integer,Integer>(); HashMap<Integer,String> WMstate_hash = new HashMap<Integer,String>(); String line; while ((line = inputfile.readLine()) != null) { String columns[]=line.split("\\t",-1); String line_nospace=columns[0].replaceAll(" ",""); Pattern pat1 = Pattern.compile("(.+?)(for|inplaceof|insteadof|mutantof|mutantsof|ratherthan|ratherthan|replacementof|replacementsof|replaces|replacing|residueatposition|residuefor|residueinplaceof|residueinsteadof|substitutioat|substitutionfor|substitutionof|substitutionsat|substitutionsfor|substitutionsof|substitutedfor|toreplace)(.+)$"); Matcher mat1 = pat1.matcher(line_nospace.toLowerCase()); Pattern pat2 = Pattern.compile("^(.+?)(>|to|into|of|by|with|at)(.+)$"); Matcher mat2 = pat2.matcher(line_nospace.toLowerCase()); if(mat1.find()) { boundary_hash.put(count,mat1.group(1).length()); WMstate_hash.put(count,"Backward"); } else if(mat2.find()) { boundary_hash.put(count,mat2.group(1).length()); WMstate_hash.put(count,"Forward"); } mentionlist.add(columns[0]); if(columns.length==2) { typelist.add(columns[1]); } else { typelist.add("DNAMutation"); } count++; } inputfile.close(); HashMap<String,String> component_hash = new HashMap<String,String>(); component_hash.put("A", ""); //type component_hash.put("T", ""); //Method component_hash.put("P", ""); //Position component_hash.put("W", ""); //Wide type component_hash.put("M", ""); //Mutant component_hash.put("F", ""); //frame shift component_hash.put("S", ""); //frame shift position component_hash.put("D", ""); // component_hash.put("I", ""); //Inside component_hash.put("R", ""); //RS number BufferedReader PostMEfile = new BufferedReader(new InputStreamReader(new FileInputStream(FilenamePostMEoutput), "UTF-8")); String prestate=""; count=0; int start_count=0; boolean codon_exist=false; HashMap<Integer,String> filteringNum_hash = new HashMap<Integer,String>(); while ((line = PostMEfile.readLine()) != null) { String outputs[]=line.split("\\t",-1); /* * recognize status and mention */ if(outputs.length<=1) { //System.out.println(component_hash.get("W")+"\t"+component_hash.get("P")+"\t"+component_hash.get("M")); /* * Translate : nametothree | threetone | etc */ component_hash.put("W",component_hash.get("W").toUpperCase()); component_hash.put("M",component_hash.get("M").toUpperCase()); component_hash.put("P",component_hash.get("P").toUpperCase()); boolean translate=false; boolean NotAaminoacid=false; boolean exchange_nu=false; //M HashMap<String,String> component_avoidrepeat = new HashMap<String,String>(); String components[]=component_hash.get("M").split(","); component_hash.put("M",""); String component=""; for(int i=0;i<components.length;i++) { if(tmVar.nametothree.containsKey(components[i])) { component=tmVar.nametothree.get(components[i]); translate=true; } else if(tmVar.NTtoATCG.containsKey(components[i])) { component=tmVar.NTtoATCG.get(components[i]); NotAaminoacid=true; } else if(tmVar.threetone_nu.containsKey(components[i]) && NotAaminoacid==false && translate==false) //&& (component_hash.get("P").matches("(.*CODON.*|)") || codon_exist == true) { component=tmVar.threetone_nu.get(components[i]); exchange_nu=true; } else { component=components[i]; } if(component_hash.get("M").equals("")) { component_hash.put("M",component); } else { if(!component_avoidrepeat.containsKey(component)) { component_hash.put("M",component_hash.get("M")+","+component); } } component_avoidrepeat.put(component,""); } component_avoidrepeat = new HashMap<String,String>(); String components2[]=component_hash.get("M").split(","); component_hash.put("M",""); component=""; for(int i=0;i<components2.length;i++) { if(tmVar.threetone.containsKey(components2[i])) { component=tmVar.threetone.get(components2[i]); translate=true; } else if(tmVar.NTtoATCG.containsKey(components2[i])) { component=tmVar.NTtoATCG.get(components2[i]); NotAaminoacid=true; } else if(tmVar.threetone_nu.containsKey(components2[i]) && NotAaminoacid==false && translate==false) //&& (component_hash.get("P").matches("(.*CODON.*|)") || codon_exist == true) { component=tmVar.threetone_nu.get(components2[i]); exchange_nu=true; } else if(components2[i].length()>1) { NotAaminoacid=false; component=components2[i]; } else { component=components2[i]; } if(component_hash.get("M").equals("")) { component_hash.put("M",component); } else { if(!component_avoidrepeat.containsKey(component)) { component_hash.put("M",component_hash.get("M")+","+component); } } component_avoidrepeat.put(component,""); } //W component_avoidrepeat = new HashMap<String,String>(); String components3[]=component_hash.get("W").split(","); component_hash.put("W",""); component=""; for(int i=0;i<components3.length;i++) { if(tmVar.nametothree.containsKey(components3[i])) { component=tmVar.nametothree.get(components3[i]); translate=true; } else if(tmVar.NTtoATCG.containsKey(components3[i])) { component=tmVar.NTtoATCG.get(components3[i]); NotAaminoacid=true; } else if(tmVar.threetone_nu.containsKey(components3[i]) && NotAaminoacid==false && translate==false) //&& (component_hash.get("P").matches("(.*CODON.*|)") || codon_exist == true) { component=tmVar.threetone_nu.get(components3[i]); exchange_nu=true; } else { component=components3[i]; } if(component_hash.get("W").equals("")) { component_hash.put("W",component); } else { if(!component_avoidrepeat.containsKey(component)) { component_hash.put("W",component_hash.get("W")+","+component); } } component_avoidrepeat.put(component,""); } component_avoidrepeat = new HashMap<String,String>(); String components4[]=component_hash.get("W").split(","); component_hash.put("W",""); component=""; for(int i=0;i<components4.length;i++) { if(tmVar.threetone.containsKey(components4[i])) { component=tmVar.threetone.get(components4[i]); translate=true; } else if(tmVar.NTtoATCG.containsKey(components4[i])) { component=tmVar.NTtoATCG.get(components4[i]); NotAaminoacid=true; } else if(tmVar.threetone_nu.containsKey(components4[i]) && NotAaminoacid==false && translate==false) //&& (component_hash.get("P").matches("(.*CODON.*|)") || codon_exist == true) { component=tmVar.threetone_nu.get(components4[i]); exchange_nu=true; } else if(components4[i].length()>1) { NotAaminoacid=false; component=components4[i]; } else { component=components4[i]; } if(component_hash.get("W").equals("")) { component_hash.put("W",component); } else { if(!component_avoidrepeat.containsKey(component)) { component_hash.put("W",component_hash.get("W")+","+component); } } component_avoidrepeat.put(component,""); } //System.out.println(component_hash.get("W")+"\t"+component_hash.get("P")+"\t"+component_hash.get("M")+"\n"); //W/M - 2 if(component_hash.get("W").matches(",") && (component_hash.get("M").equals("") && component_hash.get("T").equals(""))) { String spl[]=component_hash.get("W").split("-"); component_hash.put("W",spl[0]); component_hash.put("M",spl[1]); } if(component_hash.get("M").matches(",") && (component_hash.get("W").equals("") && component_hash.get("T").equals(""))) { String spl[]=component_hash.get("M").split("-"); component_hash.put("W",spl[0]); component_hash.put("M",spl[1]); } if(component_hash.get("M").equals("CODON")) // TGA stop codon at nucleotides 766 to 768 ProteinMutation p|SUB|X|766_768|CODON { component_hash.put("M",""); } //A Pattern pap = Pattern.compile("[+-][0-9]"); Matcher mp = pap.matcher(component_hash.get("P")); component_hash.put("A",component_hash.get("A").toLowerCase()); if(component_hash.get("A").equals("") && component_hash.get("P").matches("[\\+]*[0-9]+") && (component_hash.get("P").matches("[\\-\\+]{0,1}[0-9]{1,8}") && component_hash.get("W").matches("[ATCG]") && component_hash.get("M").matches("[ATCG]") && Integer.parseInt(component_hash.get("P"))>3000)) { component_hash.put("A","g"); } else if(component_hash.get("A").equals("cdna")) { component_hash.put("A","c"); } else if(component_hash.get("A").equals("") && mp.find() && !typelist.get(count).equals("ProteinMutation")) { component_hash.put("A","c"); } else if(component_hash.get("W").matches("^[ATCG]*$") && component_hash.get("M").matches("^[ATCG]*$") && translate==false && component_hash.get("A").equals("")) { component_hash.put("A","c"); } //F if(component_hash.get("F").equals("*")) { component_hash.put("F","X"); } //R component_hash.put("R",component_hash.get("R").toLowerCase()); component_hash.put("R",component_hash.get("R").replaceAll("[\\[\\]]", "")); //P Pattern pat = Pattern.compile("^([0-9]+)[^0-9,]+([0-9]{1,8})$"); Matcher mat = pat.matcher(component_hash.get("P")); if(mat.find()) //Title|Abstract { if(Integer.parseInt(mat.group(1))<Integer.parseInt(mat.group(2))) { component_hash.put("P",mat.group(1)+"_"+mat.group(2)); } } component_hash.put("P",component_hash.get("P").replaceAll("[-\\[]+$", "")); component_hash.put("P",component_hash.get("P").replaceAll("^(POSITION|NUCLEOTIDE|BASE|PAIR[S]*|NT|AA||:)", "")); component_hash.put("P",component_hash.get("P").replaceAll("^(POSITION|NUCLEOTIDE|BASE|PAIR[S]*|NT|AA||:)", "")); if(typelist.get(count).equals("ProteinMutation") || typelist.get(count).equals("ProteinAllele")) { component_hash.put("P",component_hash.get("P").replaceAll("^CODON", "")); } else if(typelist.get(count).equals("DNAMutation")) { if(codon_exist==true) { //add codon back if(component_hash.get("P").matches("[0-9]+")) { component_hash.put("P","CODON"+component_hash.get("P")); } //if(component_hash.get("W").matches("[ATCGUatcgu]") && component_hash.get("M").matches("[ATCGUatcgu]")) //{ // //codon position * 3 // //codon position * 3 - 1 // //codon position * 3 - 2 // String position_wo_codon=component_hash.get("P").replaceAll("^CODON", ""); // int position1=Integer.parseInt(position_wo_codon)*3; // int position2=position1-1; // int position3=position1-2; // component_hash.put("P",position1+","+position2+","+position3); //} } } //T component_hash.put("T",component_hash.get("T").toUpperCase()); //refine the variant types for(String original_type : tmVar.VariantType_hash.keySet()) { String formal_type=tmVar.VariantType_hash.get(original_type); if(component_hash.get("T").equals(original_type)) { component_hash.put("T",formal_type); break; } } if(component_hash.get("T").matches(".*INS.*DEL.*")) {component_hash.put("T","INDEL"); translate=false;} else if(component_hash.get("T").matches(".*DEL.*INS.*")) {component_hash.put("T","INDEL"); translate=false;} else if(component_hash.get("T").matches(".*DUPLICATION.*")) {component_hash.put("T","DUP"); translate=false;} //multiple types : 15148206 778 859 27 bp duplication was found inserted in the 2B domain at nucleotide position 1222 else if(component_hash.get("T").matches(".*INSERTION.*")) {component_hash.put("T","INS"); translate=false;} //multiple types else if(component_hash.get("T").matches(".*DELETION.*")) {component_hash.put("T","DEL"); translate=false;} //multiple types else if(component_hash.get("T").matches(".*INDEL.*")) {component_hash.put("T","INDEL"); translate=false;} //multiple types if(component_hash.get("T").matches("(DEL|INS|DUP|INDEL)") && !(component_hash.get("W").equals("")) && component_hash.get("M").equals("")) { component_hash.put("M",component_hash.get("W")); } else if(component_hash.get("M").matches("(DEL|INS|DUP|INDEL)")) { component_hash.put("T",component_hash.get("M")); component_hash.put("M",""); } else if(component_hash.get("W").matches("(DEL|INS|DUP|INDEL)")) { component_hash.put("T",component_hash.get("W")); component_hash.put("W",""); } else if(!component_hash.get("D").equals("")) { component_hash.put("T","DUP"); } if(tmVar.Number_word2digit.containsKey(component_hash.get("M"))) { component_hash.put("M",tmVar.Number_word2digit.get(component_hash.get("M"))); } //System.out.println(component_hash.get("T")+"\t"+component_hash.get("W")+"\t"+component_hash.get("P")+"\t"+component_hash.get("M")); String type=""; if(exchange_nu==true) { component_hash.put("P",component_hash.get("P").replaceAll("^CODON", "")); component_hash.put("A","p"); type="ProteinMutation"; } String identifier=""; if(component_hash.get("T").equals("DUP") && !component_hash.get("D").equals("")) //dup { identifier=component_hash.get("A")+"|"+component_hash.get("T")+"|"+component_hash.get("P")+"|"+component_hash.get("M")+"|"+component_hash.get("D"); } else if(component_hash.get("T").equals("DUP")) //dup { identifier=component_hash.get("A")+"|"+component_hash.get("T")+"|"+component_hash.get("P")+"|"+component_hash.get("M")+"|"; } else if(!component_hash.get("T").equals("")) //DEL|INS|INDEL { identifier=component_hash.get("A")+"|"+component_hash.get("T")+"|"+component_hash.get("P")+"|"+component_hash.get("M"); } else if(!component_hash.get("F").equals("")) //FS { identifier=component_hash.get("A")+"|FS|"+component_hash.get("W")+"|"+component_hash.get("P")+"|"+component_hash.get("M")+"|"+component_hash.get("S"); type="ProteinMutation"; } else if(!component_hash.get("R").equals("")) //RS { identifier=mentionlist.get(count); type="SNP"; } else if(mentionlist.get(count).matches("^I([RSrs][Ss][0-9].+)")) { String men=mentionlist.get(count); men.substring(1, men.length()); men=men.replaceAll("[\\W-_]", men.toLowerCase()); type="SNP"; } else if(component_hash.get("W").equals("") && !component_hash.get("M").equals("")) //Allele { identifier=component_hash.get("A")+"|Allele|"+component_hash.get("M")+"|"+component_hash.get("P"); } else if(component_hash.get("M").equals("") && !component_hash.get("W").equals("")) //Allele { identifier=component_hash.get("A")+"|Allele|"+component_hash.get("W")+"|"+component_hash.get("P"); } else if((!component_hash.get("M").equals("")) && (!component_hash.get("W").equals("")) && component_hash.get("P").equals("")) //AcidChange { identifier=component_hash.get("A")+"|SUB|"+component_hash.get("W")+"||"+component_hash.get("M"); } else { identifier=component_hash.get("A")+"|SUB|"+component_hash.get("W")+"|"+component_hash.get("P")+"|"+component_hash.get("M"); } // filteringNum_hash //if(component_hash.get("M").equals(component_hash.get("W")) && (!component_hash.get("W").equals("")) && type.equals("DNAMutation")) // remove genotype //{ // filteringNum_hash.put(count, ""); //} //else if(NotAaminoacid==false && type.equals("ProteinMutation")) //E 243 ASPARTATE //{ // filteringNum_hash.put(count, ""); //} //else if(component_hash.get("W").matches(",") && component_hash.get("M").matches(",") && component_hash.get("P").matches("")) //T,C/T,C //{ // filteringNum_hash.put(count, ""); //} //if(component_hash.get("W").equals("") && component_hash.get("M").equals("") && component_hash.get("T").equals("") && !type.equals("SNP")) //exons 5 //{ // filteringNum_hash.put(count, ""); //} if(mentionlist.get(count).matches("^I[RSrs][Ss]") && type.equals("SNP")) //exons 5 { filteringNum_hash.put(count, ""); } // Recognize the type of mentions: ProteinMutation | DNAMutation | SNP if(type.equals("")) { if(NotAaminoacid==true) { type="DNAMutation"; if(!component_hash.get("A").matches("[gmrn]")) { component_hash.put("A","c"); } } else if(translate==true || exchange_nu==true) { type="ProteinMutation"; } else { type="DNAMutation"; } if(component_hash.get("P").matches("^([Ee]x|EX|[In]ntron|IVS|[Ii]vs)")) { type="DNAMutation"; identifier=identifier.replaceAll("^[^|]*\\|","c|"); } else if(component_hash.get("M").matches("[ISQMNPKDFHLRWVEYX]") || component_hash.get("W").matches("[ISQMNPKDFHLRWVEYX]") ) { type="ProteinMutation"; identifier=identifier.replaceAll("^[^|]*\\|","p|"); } else if(component_hash.get("P").matches(".*[\\+\\-\\?].*")) { type="DNAMutation"; identifier=identifier.replaceAll("^[^|]*\\|","c|"); } else if(type.equals("")) { type="DNAMutation"; } if(!component_hash.get("A").equals("") && ( component_hash.get("A").toLowerCase().equals("c") || component_hash.get("A").toLowerCase().equals("r") || component_hash.get("A").toLowerCase().equals("m") || component_hash.get("A").toLowerCase().equals("g") ) ) { type="DNAMutation"; identifier=identifier.replaceAll("^[^|]*\\|",component_hash.get("A")+"|"); } else if(component_hash.get("A").equals("p")) { type="ProteinMutation"; } } if(type.equals("ProteinMutation")) { identifier=identifier.replaceAll("^[^|]*\\|","p|"); } if(type.equals("ProteinMutation") && (!component_hash.get("W").equals("")) && (!component_hash.get("M").equals("")) && component_hash.get("P").equals("")) { type="ProteinAcidChange"; } else if(type.equals("DNAMutation") && (!component_hash.get("W").equals("")) && (!component_hash.get("M").equals("")) && component_hash.get("P").equals("")) { type="DNAAcidChange"; } //else if(type.equals("ProteinMutation") && component_hash.get("T").equals("") && component_hash.get("A").equals("") && (!component_hash.get("W").equals("")) && component_hash.get("W").equals(component_hash.get("M"))) //{ // type="ProteinAllele"; // identifier=component_hash.get("A")+"|Allele|"+component_hash.get("M")+"|"+component_hash.get("P"); //} //else if(type.equals("DNAMutation") && component_hash.get("T").equals("") && (!component_hash.get("W").equals("")) && component_hash.get("W").equals(component_hash.get("M"))) //{ // type="DNAAllele"; // identifier=component_hash.get("A")+"|Allele|"+component_hash.get("M")+"|"+component_hash.get("P"); //} //System.out.println(identifier+"\t"+component_hash.get("T")+"\t"+component_hash.get("W")+"\t"+component_hash.get("P")+"\t"+component_hash.get("M")); boolean show_removed_cases=false; // filtering and Print out if( (component_hash.get("W").length() == 3 || component_hash.get("M").length() == 3) && component_hash.get("W").length() != component_hash.get("M").length() && !component_hash.get("W").equals("") && !component_hash.get("M").equals("") && component_hash.get("W").indexOf(",")!=-1 && component_hash.get("M").indexOf(",")!=-1 && ((component_hash.get("W").indexOf("A")!=-1 && component_hash.get("W").indexOf("T")!=-1 && component_hash.get("W").indexOf("C")!=-1 && component_hash.get("W").indexOf("G")!=-1) || (component_hash.get("M").indexOf("A")!=-1 && component_hash.get("M").indexOf("T")!=-1 && component_hash.get("M").indexOf("C")!=-1 && component_hash.get("M").indexOf("G")!=-1)) && component_hash.get("T").equals("") ) {if(show_removed_cases==true){System.out.println("filtering 1:"+mentionlist.get(count));}identifierlist.add("_Remove_");} else if((component_hash.get("M").matches("[ISQMNPKDFHLRWVEYX]") || component_hash.get("W").matches("[ISQMNPKDFHLRWVEYX]")) && component_hash.get("P").matches("[6-9][0-9][0-9][0-9]+")){if(show_removed_cases==true){System.out.println("filtering 2 length:"+mentionlist.get(count));}identifierlist.add("_Remove_");} //M300000X else if(component_hash.get("T").equals("DUP") && component_hash.get("M").matches("") && component_hash.get("P").equals("") && !type.equals("SNP")){if(show_removed_cases==true){System.out.println("filtering 3:"+mentionlist.get(count));}identifierlist.add("_Remove_");} //|DUP|||4]q33-->qter del[4] q33-->qter del4q33qter //else if(component_hash.get("T").equals("") && component_hash.get("M").matches("[ATCGUatcgu]") && (component_hash.get("M").equals(component_hash.get("W")))){if(show_removed_cases==true){System.out.println("filtering 4:"+mentionlist.get(count));}identifierlist.add("_Remove_");} //T --> T else if(component_hash.get("P").matches("[\\-\\<\\)\\]][0-9]+") && type.equals("ProteinMutation")){if(show_removed_cases==true){System.out.println("filtering 5:"+mentionlist.get(count));}identifierlist.add("_Remove_");} //negative protein mutation else if(component_hash.get("P").matches(".*>.*")){if(show_removed_cases==true){System.out.println("filtering 6:"+mentionlist.get(count));}identifierlist.add("_Remove_");} //negative protein mutation else if(component_hash.get("W").matches("^[BJOUZ]") || component_hash.get("M").matches("^[BJOUZ]")){if(show_removed_cases==true){System.out.println("filtering 7:"+mentionlist.get(count));}identifierlist.add("_Remove_");} //not a mutation else if(component_hash.get("T").equals("&")){if(show_removed_cases==true){System.out.println("filtering 8:"+mentionlist.get(count));}identifierlist.add("_Remove_");} //not a mutation else if((!component_hash.get("T").equals("")) && component_hash.get("P").equals("")){if(show_removed_cases==true){System.out.println("filtering 8-1:"+mentionlist.get(count));}identifierlist.add("_Remove_");} //Delta32 else if(component_hash.get("W").equals("") && component_hash.get("M").equals("") && component_hash.get("T").equals("") && (!type.equals("SNP")) && (!component_hash.get("P").matches(".*\\?.*"))){if(show_removed_cases==true){System.out.println("filtering 9:"+mentionlist.get(count));}identifierlist.add("_Remove_");} //not a mutation else if(type.equals("SNP") && identifier.matches("RS[0-9]+")){if(show_removed_cases==true){System.out.println("filtering 2-1:"+mentionlist.get(count));}identifierlist.add("_Remove_");} //start with RS (uppercase) else if(type.equals("SNP") && identifier.matches("[Rr][Ss][0-9][0-9]{0,1}")){if(show_removed_cases==true){System.out.println("filtering 2-2:"+mentionlist.get(count));}identifierlist.add("_Remove_");} //too short rs number else if(type.equals("SNP") && identifier.matches("[Rr][Ss]0[0-9]*")){if(show_removed_cases==true){System.out.println("filtering 2-3:"+mentionlist.get(count));}identifierlist.add("_Remove_");} //start with 0 else if(type.equals("SNP") && identifier.matches("[Rr][Ss][0-9]{11,}")){if(show_removed_cases==true){System.out.println("filtering 2-4:"+mentionlist.get(count));}identifierlist.add("_Remove_");} //too long rs number; allows 10 numbers or less else if(type.equals("SNP") && identifier.matches("[Rr][Ss][5-9][0-9]{9,}")){if(show_removed_cases==true){System.out.println("filtering 2-5:"+mentionlist.get(count));}identifierlist.add("_Remove_");} //too long rs number; allows 10 numbers or less else if(type.equals("SNP") && identifier.matches("[0-9][0-9]{0,1}[\\W\\-\\_]*delta")){if(show_removed_cases==true){System.out.println("filtering 2-6:"+mentionlist.get(count));}identifierlist.add("_Remove_");} //0 delta //else if(tmVar.PAM_lowerScorePair.contains(component_hash.get("M")+"\t"+component_hash.get("W"))){if(show_removed_cases==true){System.out.println("filtering 7-1:"+mentionlist.get(count));}identifierlist.add("_Remove_");} //unlikely to occur //else if(component_hash.get("P").equals("") && component_hash.get("T").equals("") && (!type.equals("SNP"))){if(show_removed_cases==true){System.out.println("filtering 8-2:"+mentionlist.get(count));}identifierlist.add("_Remove_");} //position is empty else if(component_hash.get("W").equals("") && component_hash.get("M").equals("") && component_hash.get("T").equals("") && (!type.equals("SNP")) && (!component_hash.get("P").contains("?"))){if(show_removed_cases==true){System.out.println("filtering 8-3:"+mentionlist.get(count));}identifierlist.add("_Remove_");} //p.1234 else if(component_hash.get("P").matches("[21][0-9][0-9][0-9]") && (component_hash.get("W").matches("(JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC)") || component_hash.get("M").matches("(JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC)"))){if(show_removed_cases==true){System.out.println("filtering 8-4:"+mentionlist.get(count));}identifierlist.add("_Remove_");} //May 2018The else if(type.equals("AcidChange") && component_hash.get("W").equals(component_hash.get("M"))){if(show_removed_cases==true){System.out.println("filtering 8-5:"+mentionlist.get(count));}identifierlist.add("_Remove_");} //Met/Met Genotype else if(type.matches("DNAMutation|ProteinMutation") && component_hash.get("T").equals("") && (component_hash.get("W").length() != component_hash.get("M").length()) && component_hash.get("W").length()>0 && component_hash.get("M").length()>0 && (!component_hash.get("P").matches(".*\\?.*")) && (!component_hash.get("W").matches(".*,.*")) && (!component_hash.get("M").matches(".*,.*"))){if(show_removed_cases==true){System.out.println("filtering 8-6:"+mentionlist.get(count)+"\t"+component_hash.get("W")+"\t"+component_hash.get("M"));}identifierlist.add("_Remove_");} //GUCA1A else { identifierlist.add(identifier); if(typelist.get(count).matches("DNAAllele|ProteinAllele")){} else { typelist.set(count,type); } } //End component_hash.put("A", ""); component_hash.put("T", ""); component_hash.put("P", ""); component_hash.put("W", ""); component_hash.put("M", ""); component_hash.put("F", ""); component_hash.put("S", ""); component_hash.put("D", ""); component_hash.put("I", ""); component_hash.put("R", ""); count++; start_count=0; } else if(outputs[1].equals("I")) { //Start codon_exist=false; } else if(outputs[outputs.length-1].matches("[ATPWMFSDIR]")) { if(WMstate_hash.containsKey(count) && WMstate_hash.get(count).equals("Forward")) { if(start_count<boundary_hash.get(count) && outputs[outputs.length-1].equals("M")) { outputs[outputs.length-1]="W"; } else if(start_count>boundary_hash.get(count) && outputs[outputs.length-1].equals("W")) { outputs[outputs.length-1]="M"; } } else if(WMstate_hash.containsKey(count) && WMstate_hash.get(count).equals("Backward")) { if(start_count<boundary_hash.get(count) && outputs[outputs.length-1].equals("W")) { outputs[outputs.length-1]="M"; } else if(start_count>boundary_hash.get(count) && outputs[outputs.length-1].equals("M")) { outputs[outputs.length-1]="W"; } } String state=outputs[outputs.length-1]; String tkn=outputs[0]; if(!component_hash.get(state).equals("") && !state.equals(prestate)) //add "," if the words are not together { component_hash.put(state, component_hash.get(state)+","+tkn); } else { component_hash.put(state, component_hash.get(state)+tkn); } prestate=state; if(outputs[0].toLowerCase().equals("codon")) { codon_exist=true; } } start_count=start_count+outputs[0].length(); } PostMEfile.close(); HashMap<String,String> mention2id_hash = new HashMap<String,String>(); for(int i=0;i<count;i++) { if(!filteringNum_hash.containsKey(i) && (!identifierlist.get(i).equals("_Remove_"))) { if(typelist.get(i).equals("SNP")) { String id_rev = identifierlist.get(i); id_rev=id_rev.replaceAll(",",""); identifierlist.set(i, id_rev); } mention2id_hash.put(mentionlist.get(i),typelist.get(i)+"\t"+identifierlist.get(i)); } } String text=" "; String pmid=""; BufferedWriter PubTatorfile = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(FilenamePubTator), "UTF-8")); // .location PostMEfile = new BufferedReader(new InputStreamReader(new FileInputStream(FilenamePostME), "UTF-8")); while ((line = PostMEfile.readLine()) != null) { Pattern pat = Pattern.compile("^([^\\|\\t]+)\\|([^\\|\\t]+)\\|(.*)$"); Matcher mat = pat.matcher(line); if(mat.find()) //Title|Abstract { pmid=mat.group(1); text=text+mat.group(3)+" "; PubTatorfile.write(line+"\n"); } else if(line.contains("\t")) //Annotation { String outputs[]=line.split("\\t"); pmid=outputs[0]; String start=outputs[1]; String last=outputs[2]; String mention=outputs[3]; String mention_tmp=mention.replaceAll(" ", ""); if(Integer.parseInt(start)>16 && text.length()>20 && text.substring(Integer.parseInt(start)-15,Integer.parseInt(start)).matches(".*(Figure|Figures|Table|Fig|Figs|Tab|Tabs|figure|figures|table|fig|figs|tab|tabs)[ \\.].*")) { //System.out.println(start+" "+last+" "+"\t"+mention+" "+text.substring(Integer.parseInt(start)-15,Integer.parseInt(start))); } else if((!tmVar.filteringStr_hash.containsKey(mention_tmp)) && mention2id_hash.containsKey(mention)) { if(mention.matches(".* at")){} else if(mention.matches("C [0-9]+H")){} else { mention2id_hash.put(mention,mention2id_hash.get(mention).replaceAll(" ","")); PubTatorfile.write(pmid+"\t"+start+"\t"+last+"\t"+mention+"\t"+mention2id_hash.get(mention)+"\n"); } } } else { Pattern pat_chro1 = Pattern.compile("^(.*?[\\W\\-\\_])((Chromosome|chromosome|chr|Chr)[ ]*([0-9XY]+)[ \\:]+([0-9][0-9,\\. ]*[0-9])[ ]*([\\-\\_]|to){1,}[ ]*([0-9][0-9,\\. ]*[0-9])[ ]*([MmKk]bp|[MmKk]b|[MmKk]bs|[MmKk]bps|c[MmKk]|bp|bps|b|)[ ]*(del\\/dup|del[0-9,]*|dup[0-9,]*|ins[0-9,]*|indel[0-9,]*|[\\+\\-]|))([\\W\\-\\_].*)$"); Matcher mat_chro1 = pat_chro1.matcher(text); while(mat_chro1.find()) { String pre=mat_chro1.group(1); String men=mat_chro1.group(2); String CNV_chr=mat_chro1.group(4); String CNV_start=mat_chro1.group(5); String CNV_last=mat_chro1.group(7); String unit=mat_chro1.group(8); String type=mat_chro1.group(9); String post=mat_chro1.group(10); CNV_start=CNV_start.replaceAll("[, ]",""); CNV_last=CNV_last.replaceAll("[, ]",""); if(type.equals("-")) {type="del";} else if(type.equals("+")) {type="dup";} else { int pre_distance=100; if(pre.length()<100) {pre_distance=pre.length();} String pre_last100char=pre.substring(pre.length()-pre_distance); int loca_del_dup=pre_last100char.lastIndexOf("deletion/duplication"); int loca_dup_del=pre_last100char.lastIndexOf("duplication/deletion"); int loca_del=pre_last100char.lastIndexOf("deletion"); int loca_del2=pre_last100char.lastIndexOf("loss"); int loca_dup=pre_last100char.lastIndexOf("duplication"); int loca_dup2=pre_last100char.lastIndexOf("gain"); if((loca_del_dup!=-1) || (loca_dup_del!=-1)) { type="del/dup"; } else if(loca_del>-1 && loca_del>loca_dup) { type="del"; } else if(loca_del2>-1 && loca_del2>loca_dup) { type="del"; } else if(loca_dup>-1 && loca_dup>loca_del) { type="dup"; } else if(loca_dup2>-1 && loca_dup2>loca_del) { type="dup"; } } String CNV_id="Chr"+CNV_chr+":"+CNV_start+"-"+CNV_last+type; if(unit.toUpperCase().lastIndexOf("M")!=-1) { CNV_id="Chr"+CNV_chr+":"+CNV_start+"-"+CNV_last+"M"+type; } else if(unit.toUpperCase().lastIndexOf("K")!=-1) { CNV_id="Chr"+CNV_chr+":"+CNV_start+"-"+CNV_last+"K"+type; } else { CNV_start=CNV_start.replaceAll("[\\.]",""); CNV_last=CNV_last.replaceAll("[\\.]",""); } int start=pre.length(); int last=start+men.length(); if(type.equals("")) { PubTatorfile.write(pmid+"\t"+start+"\t"+last+"\t"+men+"\tGenomicRegion\t"+CNV_id+"\n"); } else { PubTatorfile.write(pmid+"\t"+start+"\t"+last+"\t"+men+"\tCopyNumberVariant\t"+CNV_id+"\n"); } men=men.replaceAll(".","@"); text=pre+men+post; mat_chro1 = pat_chro1.matcher(text); } pat_chro1 = Pattern.compile("^(.*?[\\W\\-\\_])((Chromosome|chromosome|chr|Chr)[ ]*([0-9XY]+)[ \\:]+([0-9][0-9,\\. ]*[0-9])[ ]*([MmKk]bp|[MmKk]b|[MmKk]bs|[MmKk]bps|c[MmKk]|bp|bps|b|))([\\W\\-\\_].*)$"); mat_chro1 = pat_chro1.matcher(text); while(mat_chro1.find()) { String pre=mat_chro1.group(1); String men=mat_chro1.group(2); String CNV_chr=mat_chro1.group(4); String CNV_start=mat_chro1.group(5); String unit=mat_chro1.group(6); String post=mat_chro1.group(7); CNV_start=CNV_start.replaceAll("[, ]",""); String CNV_id="Chr"+CNV_chr+":"+CNV_start; if(unit.toUpperCase().lastIndexOf("M")!=-1) { CNV_id="Chr"+CNV_chr+":"+CNV_start+"M"; } else if(unit.toUpperCase().lastIndexOf("K")!=-1) { CNV_id="Chr"+CNV_chr+":"+CNV_start+"K"; } else { CNV_start=CNV_start.replaceAll("[\\.]",""); } int start=pre.length(); int last=start+men.length(); PubTatorfile.write(pmid+"\t"+start+"\t"+last+"\t"+men+"\tGenomicRegion\t"+CNV_id+"\n"); men=men.replaceAll(".","@"); text=pre+men+post; mat_chro1 = pat_chro1.matcher(text); } pat_chro1 = Pattern.compile("^(.*?[\\W\\-\\_])((chromosome|chromosome band|chr)[ ]*(([0-9XY]+)([pq][0-9\\.]+|)))([\\W\\-\\_].*)$"); mat_chro1 = pat_chro1.matcher(text); while(mat_chro1.find()) { String pre=mat_chro1.group(1); String men=mat_chro1.group(2); String chro_num=mat_chro1.group(5); String post=mat_chro1.group(7); if(men.matches("^(.+)\\.$")) { men=men.substring(0, men.length()-1); post="."+post; } int start=pre.length(); int last=start+men.length(); PubTatorfile.write(pmid+"\t"+start+"\t"+last+"\t"+men+"\tChromosome\t"+chro_num+"\n"); men=men.replaceAll(".","@"); text=pre+men+post; mat_chro1 = pat_chro1.matcher(text); } pat_chro1 = Pattern.compile("^(.*?[\\W\\-\\_])(([0-9XY]+)[pq][0-9\\-\\.]+)([\\W\\-\\_].*)$"); mat_chro1 = pat_chro1.matcher(text); while(mat_chro1.find()) { String pre=mat_chro1.group(1); String men=mat_chro1.group(2); String chro_num=mat_chro1.group(3); String post=mat_chro1.group(4); if(men.matches("^(.+)\\.$")) { men=men.substring(0, men.length()-1); post="."+post; } int start=pre.length(); int last=start+men.length(); PubTatorfile.write(pmid+"\t"+start+"\t"+last+"\t"+men+"\tChromosome\t"+chro_num+"\n"); men=men.replaceAll(".","@"); text=pre+men+post; mat_chro1 = pat_chro1.matcher(text); } pat_chro1 = Pattern.compile("^(.*?[\\W\\-\\_])([NX][MPGCRT]\\_[0-9\\.]+)([\\W\\-\\_].*)$"); mat_chro1 = pat_chro1.matcher(text); while(mat_chro1.find()) { String pre=mat_chro1.group(1); String men=mat_chro1.group(2); String post=mat_chro1.group(3); if(men.matches("^(.+)\\.$")) { men=men.substring(0, men.length()-1); post="."+post; } int start=pre.length(); int last=start+men.length(); PubTatorfile.write(pmid+"\t"+start+"\t"+last+"\t"+men+"\tRefSeq\t"+men+"\n"); men=men.replaceAll(".","@"); text=pre+men+post; mat_chro1 = pat_chro1.matcher(text); } PubTatorfile.write(line+"\n"); text=""; } } PostMEfile.close(); PubTatorfile.close(); } catch(IOException e1){ System.out.println("[output2PubTator]: "+e1+" Input file is not exist.");} } public void Normalization(String input,String outputPubTator,String finalPubTator,String DisplayRSnumOnly, String HideMultipleResult, String DisplayChromosome, String DisplayRefSeq, String DisplayGenomicRegion) throws IOException,SQLException { /** * input : gene mentions * outputPubTator : mutation mentions * finalPubTator : normalized result of mutation mentions */ BreakIterator iterator = BreakIterator.getSentenceInstance(Locale.US); /*Database Connection*/ Connection c = null; Statement stmt = null; Connection c_merged = null; Statement stmt_merged = null; Connection c_expired = null; Statement stmt_expired = null; Connection c_gene2rs = null; Statement stmt_gene2rs = null; Connection c_rs2gene = null; Statement stmt_rs2gene = null; Connection c_gene2tax = null; Statement stmt_gene2tax = null; Connection c_gene2humangene = null; Statement stmt_gene2humangene = null; try { Class.forName("org.sqlite.JDBC"); } catch ( Exception e ) { System.err.println( e.getClass().getName() + ": " + e.getMessage() ); System.exit(0); } try { c_merged = DriverManager.getConnection("jdbc:sqlite:Database/Merged.db"); stmt_merged = c_merged.createStatement(); c_expired = DriverManager.getConnection("jdbc:sqlite:Database/Expired.db"); stmt_expired = c_expired.createStatement(); c_gene2rs = DriverManager.getConnection("jdbc:sqlite:Database/gene2rs.db"); stmt_gene2rs = c_gene2rs.createStatement(); c_rs2gene = DriverManager.getConnection("jdbc:sqlite:Database/rs2gene.db"); stmt_rs2gene = c_rs2gene.createStatement(); c_gene2tax = DriverManager.getConnection("jdbc:sqlite:Database/gene2tax.db"); stmt_gene2tax = c_gene2tax.createStatement(); c_gene2humangene = DriverManager.getConnection("jdbc:sqlite:Database/gene2humangene.db"); stmt_gene2humangene = c_gene2humangene.createStatement(); /** * Gene Mention Extraction */ HashMap<String,String> rs2gene = new HashMap<String,String>(); // the corresponding gene of the rs number BufferedReader inputfile = new BufferedReader(new InputStreamReader(new FileInputStream(input), "UTF-8")); HashMap<String,String> pmid_gene2rs = new HashMap<String,String>(); // pmid_gene2rs(pmid,geneid) -> RS#s HashMap<String,String> annotations_gene = new HashMap<String,String>(); String line=""; HashMap<String,HashMap<String,Integer>> SingleGene = new HashMap<String,HashMap<String,Integer>>(); while ((line = inputfile.readLine()) != null) { Pattern pat = Pattern.compile("^([^\\|\\t]+)\\|([^\\|\\t]+)\\|(.*)$"); Matcher mat = pat.matcher(line); if(mat.find()) //Title|Abstract { String Pmid=mat.group(1); SingleGene.put(Pmid,new HashMap<String,Integer>()); } else if (line.contains("\t")) //Gene mentions { String anno[]=line.split("\t"); String Pmid=anno[0]; //System.out.println(line); if(anno.length>=6) { int start=Integer.parseInt(anno[1]); String gene_mention=anno[3]; String mentiontype=anno[4]; if(gene_mention.toLowerCase().equals("raf")) { anno[5]=anno[5]+";673"; } boolean variant_gene_overlap=false; if(tmVar.variant_mention_to_filter_overlap_gene.containsKey(Pmid)) { if(tmVar.variant_mention_to_filter_overlap_gene.get(Pmid).containsKey(start)) { } for(int var_mention_start : tmVar.variant_mention_to_filter_overlap_gene.get(Pmid).keySet()) { if(var_mention_start == start) // the gene mention is the same to one of the variant mention { variant_gene_overlap=true; } } } if(mentiontype.equals("Gene") && variant_gene_overlap==false) { /* * Search Database - Gene */ String geneids[]=anno[5].split(";"); for(int gi=0;gi<geneids.length;gi++) { annotations_gene.put(anno[0]+"\t"+anno[1]+"\t"+anno[2]+"\t"+anno[3]+"\t"+geneids[gi],""); if(SingleGene.get(anno[0]).containsKey(geneids[gi])) { SingleGene.get(anno[0]).put(geneids[gi],SingleGene.get(anno[0]).get(geneids[gi])+1); } else { SingleGene.get(anno[0]).put(geneids[gi],1); } /* pmid_gene2rs(pmid,geneid) -> RS#s */ /* annotations_gene(pmid,start,last,mention,geneid) -> RS#s */ if(pmid_gene2rs.containsKey(anno[0]+"\t"+geneids[gi])) { annotations_gene.put(anno[0]+"\t"+anno[1]+"\t"+anno[2]+"\t"+anno[3]+"\t"+geneids[gi],pmid_gene2rs.get(anno[0]+"\t"+geneids[gi])); } else { String gene_id=geneids[gi]; if(tmVar.Gene2HumanGene_hash.containsKey(gene_id)) //translate to human gene { gene_id=tmVar.Gene2HumanGene_hash.get(gene_id); } ResultSet rs = stmt_gene2rs.executeQuery("SELECT rs FROM gene2rs WHERE gene='"+gene_id+"' order by rs asc limit 1;"); if ( rs.next() ) { String rsNumber = rs.getString("rs"); annotations_gene.put(anno[0]+"\t"+anno[1]+"\t"+anno[2]+"\t"+anno[3]+"\t"+geneids[gi],rsNumber); pmid_gene2rs.put(anno[0]+"\t"+geneids[gi],rsNumber); String rsNumbers[]=rsNumber.split("\\|"); for(int i=0;i<rsNumbers.length;i++) { rs2gene.put(Pmid+"\t"+rsNumbers[i],geneids[gi]); } } } } } } } } inputfile.close(); /** * Chromosome & RefSeq Mention Extraction */ inputfile = new BufferedReader(new InputStreamReader(new FileInputStream(outputPubTator), "UTF-8")); HashMap<String,String> annotations_CNV = new HashMap<String,String>(); HashMap<String,String> annotations_chromosome = new HashMap<String,String>(); HashMap<String,String> annotations_RefSeq = new HashMap<String,String>(); while ((line = inputfile.readLine()) != null) { Pattern pat = Pattern.compile("^([^\\|\\t]+)\\|([^\\|\\t]+)\\|(.*)$"); Matcher mat = pat.matcher(line); if(mat.find()) {}//Title|Abstract else if (line.contains("\t")) //Annotation { String anno[]=line.split("\t"); if(anno.length>=6) { String mentiontype=anno[4]; if(mentiontype.equals("Chromosome")) { String chr_id=anno[5]; annotations_chromosome.put(anno[0]+"\t"+anno[1]+"\t"+anno[2]+"\t"+anno[3]+"\t"+chr_id,"chr"+chr_id); } else if(mentiontype.equals("RefSeq")) { String RefSeq=anno[3]; annotations_RefSeq.put(anno[0]+"\t"+anno[1]+"\t"+anno[2]+"\t"+anno[3]+"\t"+RefSeq,RefSeq); } } } } inputfile.close(); /** * RS_DNA_Protein Pattern Extraction */ String article=""; String Pmid=""; HashMap<String,Integer> Flag_Protein_WPM=new HashMap<String,Integer>(); HashMap<String,Integer> Flag_DNA_gt_Format=new HashMap<String,Integer>(); HashMap<String,String> RSnumberList = new HashMap<String,String>(); HashMap<Integer,String> start2id = new HashMap<Integer,String>(); //tmp HashMap<String,String> MentionPatternMap2rs = new HashMap<String,String>(); //Assign RS# to the DNA/Protein mutations in the same pattern range HashMap<String,String> MentionPatternMap = new HashMap<String,String>(); // group DNA/Protein mutations (will assign the same RS# if possible) HashMap<String,String> MentionPatternMap2rs_extend = new HashMap<String,String>(); //by pattern [PMID:24073655] c.169G>C (p.Gly57Arg) -- map to rs764352037 inputfile = new BufferedReader(new InputStreamReader(new FileInputStream(outputPubTator), "UTF-8")); HashMap<String,ArrayList<Integer>> PMID2SentenceOffsets = new HashMap<String,ArrayList<Integer>>(); while ((line = inputfile.readLine()) != null) { Pattern pat = Pattern.compile("^([^\\|\\t]+)\\|([^\\|\\t]+)\\|(.*)$"); Matcher mat = pat.matcher(line); if(mat.find()) //Title|Abstract { Pmid = mat.group(1); String ParagraphContent=mat.group(3); article=article+ParagraphContent+"\t"; // split sentences (get the start offset of every sentence) iterator.setText(article); ArrayList<Integer> Sentence_offsets = new ArrayList<Integer>(); int Sent_start = iterator.first(); for (int Sent_last = iterator.next(); Sent_last != BreakIterator.DONE; Sent_start = Sent_last, Sent_last = iterator.next()) { Sentence_offsets.add(Sent_start); } PMID2SentenceOffsets.put(Pmid, Sentence_offsets); } else if (line.contains("\t")) //Annotation { String anno[]=line.split("\t"); if(anno.length>=6) { Pmid = anno[0]; int start = Integer.parseInt(anno[1]); int last = Integer.parseInt(anno[2]); String mention=anno[3]; String mentiontype=anno[4]; if(mention.matches("^c\\.[0-9]+[ ]*[ATCG][ ]*>[ ]*[ATCG]$")) // if exists 12345A>G, or A1556E or E1356A, the A154T should be protein mutation { if(Flag_DNA_gt_Format.containsKey(Pmid)) { Flag_DNA_gt_Format.put(Pmid,Flag_DNA_gt_Format.get(Pmid)+1); } else { Flag_DNA_gt_Format.put(Pmid,1); } } else if(mention.matches("^[ATCGISQMNPKDFHLRWVEYX][0-9]+[ISQMNPKDFHLRWVEYX]$") || mention.matches("^[ATCGISQMNPKDFHLRWVEYX][0-9]+[ISQMNPKDFHLRWVEYX]$")) { if(Flag_Protein_WPM.containsKey(Pmid)) { Flag_Protein_WPM.put(Pmid,Flag_Protein_WPM.get(Pmid)+1); } else { Flag_Protein_WPM.put(Pmid,1); } } if(anno[5].matches("\\|.*")) { if(mentiontype.matches(".*Protein.*")) { anno[5]="p"+anno[5]; } else { anno[5]="c"+anno[5]; } } String id=anno[5]; if(mentiontype.matches("DNA.*")) { if(article.substring(start,last).equals(mention)) { String tmp = mention; tmp=tmp.replaceAll(".","D"); article=article.substring(0,start)+tmp+article.substring(last,article.length()); // replace DNAMutation|DNAAllele|DNAAcidChange to DDDDD } start2id.put(start,id); } else if(mentiontype.matches("Protein.*")) { if(article.substring(start,last).equals(mention)) { String tmp = mention; tmp=tmp.replaceAll(".","P"); article=article.substring(0,start)+tmp+article.substring(last,article.length()); // replace ProteinMutation|ProteinAllele|ProteinAcidChange to PPPPP } start2id.put(start,id); } else if(mentiontype.equals("SNP")) { anno[5]=anno[5].replaceAll("^rs",""); RSnumberList.put(anno[0]+"\t"+anno[5],""); if(article.substring(start,last).equals(mention)) { String tmp = mention; tmp=tmp.replaceAll(".","S"); article=article.substring(0,start)+tmp+article.substring(last,article.length()); // replace SNP to SSSSS } start2id.put(start,id); } } } else if(line.length()==0) { String text=article; for(int i=0;i<tmVar.RS_DNA_Protein.size();i++) // patterns : PP[P]+[ ]*[\(\[][ ]*DD[D]+[ ]*[\)\]][ ]*[\(\[][ ]*SS[S]+[ ]*[\)\]] { pat = Pattern.compile("^(.*?)("+tmVar.RS_DNA_Protein.get(i)+")"); mat = pat.matcher(text); while(mat.find()) { String pre=mat.group(1); String match_string=mat.group(2); int start=pre.length(); int last=start+match_string.length(); if(!match_string.matches(".*[\\W\\_\\-](and|or)[\\W\\_\\-].*")) // the variants are different. { ArrayList<String> DP = new ArrayList<String>(); String S = ""; // the RS# in the pattern for(int s : start2id.keySet()) { if(s>=start && s<last) { Pattern pat_rs = Pattern.compile("[Rr][Ss]([0-9]+)$"); Matcher mat_rs = pat_rs.matcher(start2id.get(s)); if(mat_rs.find()) { S = mat_rs.group(1); } else { DP.add(start2id.get(s)); } } } if(!S.equals("")) //RS number is in the pattern { for(int dp=0;dp<DP.size();dp++) { MentionPatternMap2rs.put(Pmid+"\t"+DP.get(dp),S); // assign the RS# to the DNA/Protein Mutations } } else { if(DP.size()>1) { //group the DNA/Protein mutations together MentionPatternMap.put(Pmid+"\t"+DP.get(0),DP.get(1)); MentionPatternMap.put(Pmid+"\t"+DP.get(1),DP.get(0)); } } } String tmp = mat.group(2); tmp=tmp.replaceAll(".", "F"); //finished text = text.substring(0, start)+tmp+text.substring(last,text.length()); pat = Pattern.compile("^(.*?)("+tmVar.RS_DNA_Protein.get(i)+")"); // next run mat = pat.matcher(text); } } article=""; start2id.clear(); } } inputfile.close(); /** * DNAMutation|ProteinMutation normalization */ BufferedWriter outputfile = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(finalPubTator), "UTF-8")); // .location inputfile = new BufferedReader(new InputStreamReader(new FileInputStream(outputPubTator), "UTF-8")); HashMap<String,String> normalized_mutation = new HashMap<String,String>(); HashMap<String,String> changetype = new HashMap<String,String>(); //eg., G469A from DNA to Protein mutation HashMap<String,String> mutation2rs_indatabase = new HashMap<String,String>(); HashMap<String,String> rs_foundbefore_hash = new HashMap<String,String>(); HashMap<String,String> rs_foundinText_hash = new HashMap<String,String>(); HashMap<String,HashMap<String,String>> P2variant = new HashMap<String,HashMap<String,String>>(); HashMap<String,HashMap<String,String>> WM2variant = new HashMap<String,HashMap<String,String>>(); String outputSTR=""; String tiabs=""; String pmid=""; String articleid=""; while ((line = inputfile.readLine()) != null) { Pattern pat = Pattern.compile("^([^\\|\\t]+)\\|([^\\|\\t]+)\\|(.*)$"); Matcher mat = pat.matcher(line); if(mat.find()) //Title|Abstract { outputSTR=outputSTR+line+"\n"; pmid=mat.group(1); tiabs=tiabs+mat.group(3)+"\t"; } else if (line.contains("\t")) //Annotation { String anno[]=line.split("\t"); String mentiontype=anno[4]; String mention=anno[3]; String Flag_Seq=""; if(mention.matches("^[mgcrn]\\..*")) { Flag_Seq="c"; mentiontype=mentiontype.replaceAll("Protein","DNA"); } else if(mention.matches("^p\\..*")) { Flag_Seq="p"; mentiontype=mentiontype.replaceAll("DNA","Protein"); } else if(mention.matches(".*[ATCG]>[ATCG]")) { Flag_Seq="c"; mentiontype=mentiontype.replaceAll("Protein","DNA"); } else if(mention.matches("[A-Z][a-z][a-z][0-9]+[A-Z][a-z][a-z]")) { Flag_Seq="p"; anno[5]=anno[5].replaceAll("[mgcrnc]\\|","p|"); mentiontype=mentiontype.replaceAll("DNA","Protein"); } else if(mention.matches("^[ATCG][0-9]+[ATCG]$") && ((Flag_Protein_WPM.containsKey(Pmid) && Flag_DNA_gt_Format.containsKey(Pmid)) || (Flag_Protein_WPM.containsKey(Pmid) && Flag_Protein_WPM.get(Pmid)>50))) //5236G>C and G1738R --> G1706A (ProteinMutation) { Flag_Seq="p"; anno[5]=anno[5].replaceAll("c\\|","p|"); mentiontype=mentiontype.replaceAll("DNA","Protein"); } if(anno.length>=6) { if(mentiontype.matches("(DNAMutation|ProteinMutation|ProteinAllele|DNAAllele|DNAAcidChange|ProteinAcidChange)")) { int start=Integer.parseInt(anno[1]); int pre_start=0; if(start>20){pre_start=start-20;} String pre_text=tiabs.substring(pre_start, start); Pattern pat_NM = Pattern.compile("^.*([NX][MPGCRT]\\_[0-9\\.\\_]+[\\:\\; ]+)$"); Matcher mat_NM = pat_NM.matcher(pre_text); if(mat_NM.find()) //NM_001046020:c.12A>G { String RefSeq=mat_NM.group(1); line=anno[0]+"\t"+(start-RefSeq.length())+"\t"+anno[2]+"\t"+RefSeq+anno[3]+"\t"+mentiontype+"\t"+anno[5]; } String component[]=anno[5].split("\\|",-1); String NormalizedForm=""; String NormalizedForm_reverse=""; String NormalizedForm_plus1=""; String NormalizedForm_minus1=""; String NormalizedForm_protein=""; /* * translate the tmVar format to HGVS format */ if(component.length>=3) { if(component[1].equals("Allele")) { //to extract the location and WM for variant grouping String Seq="c"; if(component[0].matches("[gcnrm]")){Seq="c";} if(!component[3].equals("")) { if(!P2variant.containsKey(pmid+"\t"+Seq+"\tSUB\t"+component[3])) //position { P2variant.put(pmid+"\t"+Seq+"\tSUB\t"+component[3],new HashMap<String,String>()); } P2variant.get(pmid+"\t"+Seq+"\tSUB\t"+component[3]).put(pmid+"\t"+anno[5],""); } } else if(component[1].equals("SUB")) { //to extract the location and WM for variant grouping String Seq="c"; if(component[0].matches("[gcnrm]")){Seq="c";} if(!component[3].equals("")) { if(!P2variant.containsKey(pmid+"\t"+Seq+"\tSUB\t"+component[3])) //position { P2variant.put(pmid+"\t"+Seq+"\tSUB\t"+component[3],new HashMap<String,String>()); } P2variant.get(pmid+"\t"+Seq+"\tSUB\t"+component[3]).put(pmid+"\t"+anno[5],""); } if(!WM2variant.containsKey(pmid+"\t"+Seq+"\tSUB\t"+component[2]+"\t\t"+component[4])) //W,M { WM2variant.put(pmid+"\t"+Seq+"\tSUB\t"+component[2]+"\t\t"+component[4],new HashMap<String,String>()); } WM2variant.get(pmid+"\t"+Seq+"\tSUB\t"+component[2]+"\t\t"+component[4]).put(pmid+"\t"+anno[5],component[3]); if(component[0].equals("p")) { String tmp=""; /*one -> three*/ for(int len=0;len<component[2].length();len++) { if(tmVar.one2three.containsKey(component[2].substring(len, len+1))) { if(tmp.equals("")) { tmp = tmVar.one2three.get(component[2].substring(len, len+1)); } else { tmp = tmp +","+ tmVar.one2three.get(component[2].substring(len, len+1)); } } } component[2]=tmp; tmp=""; for(int len=0;len<component[4].length();len++) { if(tmVar.one2three.containsKey(component[4].substring(len, len+1))) { if(tmp.equals("")) { tmp = tmVar.one2three.get(component[4].substring(len, len+1)); } else { tmp = tmp +","+ tmVar.one2three.get(component[4].substring(len, len+1)); } } } component[4]=tmp; if(component[2].equals(component[4])) { NormalizedForm=component[0]+"."+component[2]+component[3]+"="; } else { NormalizedForm=component[0]+"."+component[2]+component[3]+component[4]; NormalizedForm_reverse=component[0]+"."+component[4]+component[3]+component[2]; } String wildtype[]=component[2].split(","); String mutant[]=component[4].split(","); String positions[]=component[3].split(","); if(wildtype.length == positions.length && wildtype.length>1) //Pair of wildtype&position { for (int i=0;i<wildtype.length;i++) //May have more than one pair { for (int j=0;j<mutant.length;j++) { NormalizedForm=NormalizedForm+"|"+component[0]+"."+wildtype[i]+positions[i]+mutant[j]; } } } else { for (int i=0;i<wildtype.length;i++) //May have more than one pair { for (int j=0;j<mutant.length;j++) { NormalizedForm=NormalizedForm+"|"+component[0]+"."+wildtype[i]+component[3]+mutant[j]; } } } } else //[rmgc] { if(component.length>4) { component[3]=component[3].replaceAll("^\\+", ""); NormalizedForm=component[0]+"."+component[3]+component[2]+">"+component[4]; NormalizedForm_reverse=component[0]+"."+component[3]+component[4]+">"+component[2]; if(component[3].matches("[\\+\\-]{0,1}[0-9]{1,8}")) { NormalizedForm_plus1=component[0]+"."+(Integer.parseInt(component[3])+1)+""+component[2]+">"+component[4]; NormalizedForm_minus1=component[0]+"."+(Integer.parseInt(component[3])-1)+""+component[2]+">"+component[4]; } String wildtype[]=component[2].split(","); String mutant[]=component[4].split(","); String positions[]=component[3].split(","); if(wildtype.length == positions.length && wildtype.length>1) //Pair of wildtype&position { for (int i=0;i<wildtype.length;i++) //May have more than one pair { for (int j=0;j<mutant.length;j++) { NormalizedForm=NormalizedForm+"|"+component[0]+"."+positions[i]+wildtype[i]+">"+mutant[j]; } } } else { for (int i=0;i<wildtype.length;i++) //May have more than one pair { for (int j=0;j<mutant.length;j++) { NormalizedForm=NormalizedForm+"|"+component[0]+"."+component[3]+wildtype[i]+">"+mutant[j]; } } component[3]=component[3].replaceAll(",", ""); } if(component[3].matches("[0-9]{5,}")) { component[0]="g"; NormalizedForm=NormalizedForm+"|"+component[0]+"."+component[3]+component[2]+">"+component[4]; } //protein { String tmp=""; /*one -> three*/ for(int len=0;len<component[2].length();len++) { if(tmVar.one2three.containsKey(component[2].substring(len, len+1))) { if(tmp.equals("")) { tmp = tmVar.one2three.get(component[2].substring(len, len+1)); } else { tmp = tmp +","+ tmVar.one2three.get(component[2].substring(len, len+1)); } } } component[2]=tmp; tmp=""; for(int len=0;len<component[4].length();len++) { if(tmVar.one2three.containsKey(component[4].substring(len, len+1))) { if(tmp.equals("")) { tmp = tmVar.one2three.get(component[4].substring(len, len+1)); } else { tmp = tmp +","+ tmVar.one2three.get(component[4].substring(len, len+1)); } } } component[4]=tmp; if(component[2].equals(component[4])) { NormalizedForm_protein="p."+component[2]+component[3]+"="; } else { NormalizedForm_protein="p."+component[2]+component[3]+component[4]; } wildtype=component[2].split(","); mutant=component[4].split(","); positions=component[3].split(","); if(wildtype.length == positions.length && wildtype.length>1) //Pair of wildtype&position { for (int i=0;i<wildtype.length;i++) //May have more than one pair { for (int j=0;j<mutant.length;j++) { NormalizedForm_protein=NormalizedForm_protein+"|"+"p."+wildtype[i]+positions[i]+mutant[j]; } } } else { for (int i=0;i<wildtype.length;i++) //May have more than one pair { for (int j=0;j<mutant.length;j++) { NormalizedForm_protein=NormalizedForm_protein+"|"+"p."+wildtype[i]+component[3]+mutant[j]; } } } } } } } else if(component[1].equals("DEL")) { //to extract the location and WM for variant grouping String Seq="c"; //if(component[0].matches("[gcnrm]")){component[0]="c";} if(!component[2].equals("")) { if(!P2variant.containsKey(pmid+"\t"+Seq+"\t"+component[1]+"\t"+component[2])) //position { P2variant.put(pmid+"\t"+Seq+"\t"+component[1]+"\t"+component[2],new HashMap<String,String>()); } P2variant.get(pmid+"\t"+Seq+"\t"+component[1]+"\t"+component[2]).put(pmid+"\t"+anno[5],""); } if(component.length>3) { if(component[0].equals("p")) { String tmp=""; for(int len=0;len<component[3].length();len++) { tmp = tmp + tmVar.one2three.get(component[3].substring(len, len+1)); } component[3]=tmp; } NormalizedForm=component[0]+"."+component[2]+"del"+component[3]; } NormalizedForm=NormalizedForm+"|"+component[0]+"."+component[2]+"del"; } else if(component[1].equals("INS")) { //to extract the location and WM for variant grouping String Seq="c"; //if(component[0].matches("[gcnrm]")){component[0]="c";} if(!component[2].equals("")) { if(!P2variant.containsKey(pmid+"\t"+Seq+"\t"+component[1]+"\t"+component[2])) //position { P2variant.put(pmid+"\t"+Seq+"\t"+component[1]+"\t"+component[2],new HashMap<String,String>()); } P2variant.get(pmid+"\t"+Seq+"\t"+component[1]+"\t"+component[2]).put(pmid+"\t"+anno[5],""); } if(component.length>3) { if(component[0].equals("p")) { String tmp=""; for(int len=0;len<component[3].length();len++) { tmp = tmp + tmVar.one2three.get(component[3].substring(len, len+1)); } component[3]=tmp; } NormalizedForm=component[0]+"."+component[2]+"ins"+component[3]; } NormalizedForm=NormalizedForm+"|"+component[0]+"."+component[2]+"ins"; } else if(component[1].equals("INDEL")) { //to extract the location and WM for variant grouping String Seq="c"; //if(component[0].matches("[gcnrm]")){component[0]="c";} if(!component[2].equals("")) { if(!P2variant.containsKey(pmid+"\t"+Seq+"\t"+component[1]+"\t"+component[2])) //position { P2variant.put(pmid+"\t"+Seq+"\t"+component[1]+"\t"+component[2],new HashMap<String,String>()); } P2variant.get(pmid+"\t"+Seq+"\t"+component[1]+"\t"+component[2]).put(pmid+"\t"+anno[5],""); } if(component.length>3) { //c.*2361_*2362delAAinsA //c.2153_2155delinsTCCTGGTTTA if(component[0].equals("p")) { String tmp=""; for(int len=0;len<component[3].length();len++) { tmp = tmp + tmVar.one2three.get(component[3].substring(len, len+1)); } component[3]=tmp; } NormalizedForm=component[0]+"."+component[2]+"delins"+component[3]; } } else if(component[1].equals("DUP")) { //to extract the location and WM for variant grouping String Seq="c"; //if(component[0].matches("[gcnrm]")){component[0]="c";} if(!component[2].equals("")) { if(!P2variant.containsKey(pmid+"\t"+Seq+"\t"+component[1]+"\t"+component[2])) //position { P2variant.put(pmid+"\t"+Seq+"\t"+component[1]+"\t"+component[2],new HashMap<String,String>()); } P2variant.get(pmid+"\t"+Seq+"\t"+component[1]+"\t"+component[2]).put(pmid+"\t"+anno[5],""); } if(component.length>3) { if(component[0].equals("p")) { String tmp=""; for(int len=0;len<component[3].length();len++) { tmp = tmp + tmVar.one2three.get(component[3].substring(len, len+1)); } component[3]=tmp; } NormalizedForm=component[0]+"."+component[2]+"dup"+component[3]; } NormalizedForm=NormalizedForm+"|"+component[0]+"."+component[2]+"dup"; } else if(component[1].equals("FS")) { //to extract the location and WM for variant grouping String Seq="c"; //if(component[0].matches("[gcnrm]")){component[0]="c";} if(!component[3].equals("")) { if(!P2variant.containsKey(pmid+"\t"+Seq+"\tSUB\t"+component[3])) //position { P2variant.put(pmid+"\t"+Seq+"\tSUB\t"+component[3],new HashMap<String,String>()); } P2variant.get(pmid+"\t"+Seq+"\tSUB\t"+component[3]).put(pmid+"\t"+anno[5],""); } if(component[0].equals("p")) { String tmp=""; for(int len=0;len<component[2].length();len++) { tmp = tmp + tmVar.one2three.get(component[2].substring(len, len+1)); } component[2]=tmp; tmp=""; if(component.length>=5) { for(int len=0;len<component[4].length();len++) { tmp = tmp + tmVar.one2three.get(component[4].substring(len, len+1)); } component[4]=tmp; } } if(component.length>=5) { NormalizedForm=component[0]+"."+component[2]+component[3]+component[4]+"fs"; } else if(component.length==4) { NormalizedForm=component[0]+"."+component[2]+component[3]+"fs"; } } } // array --> hash --> array (remove the duplicates) String NormalizedForms[]=NormalizedForm.split("\\|"); HashMap<String,String> NormalizedForm_hash = new HashMap<String,String>(); for(int n=0;n<NormalizedForms.length;n++) { NormalizedForm_hash.put(NormalizedForms[n], ""); } NormalizedForm=""; for(String NF : NormalizedForm_hash.keySet()) { if(NormalizedForm.equals("")) { NormalizedForm=NF; } else { NormalizedForm=NormalizedForm+"|"+NF; } } //Assign RS# to the DNA/Protein mutations in the same pattern range if(MentionPatternMap2rs.containsKey(anno[0]+"\t"+anno[5])) { String RSNum=MentionPatternMap2rs.get(anno[0]+"\t"+anno[5]); //Expired ResultSet rs = stmt_expired.executeQuery("SELECT rs FROM Expired WHERE rs='"+RSNum+"' limit 1;"); if ( rs.next() ) { outputSTR=outputSTR+anno[0]+"\t"+anno[1]+"\t"+anno[2]+"\t"+anno[3]+"\t"+mentiontype+"\t"+anno[5]+";CorrespondingGene:"+rs2gene.get(pmid+"\t"+RSNum)+";Pattern-RS#:"+RSNum+"(Expired)\n"; } else { //Merged rs = stmt_merged.executeQuery("SELECT merged FROM Merged WHERE origin='"+RSNum+"' limit 1;"); if ( rs.next() ) { outputSTR=outputSTR+anno[0]+"\t"+anno[1]+"\t"+anno[2]+"\t"+anno[3]+"\t"+mentiontype+"\t"+anno[5]+";CorrespondingGene:"+rs2gene.get(pmid+"\t"+RSNum)+";Pattern-RS#:"+rs.getString("merged")+"\n"; } else { outputSTR=outputSTR+anno[0]+"\t"+anno[1]+"\t"+anno[2]+"\t"+anno[3]+"\t"+mentiontype+"\t"+anno[5]+";CorrespondingGene:"+rs2gene.get(pmid+"\t"+RSNum)+";Pattern-RS#:"+RSNum+"\n"; } } } else if(rs_foundinText_hash.containsKey(anno[0]+"\t"+NormalizedForm)) //recognized (RS# in the text, no need to compare with gene-related-RS#) { String RSNum=rs_foundinText_hash.get(anno[0]+"\t"+NormalizedForm); //Expired ResultSet rs = stmt_expired.executeQuery("SELECT rs FROM Expired WHERE rs='"+RSNum+"' limit 1;"); if ( rs.next() ) { outputSTR=outputSTR+anno[0]+"\t"+anno[1]+"\t"+anno[2]+"\t"+anno[3]+"\t"+mentiontype+"\t"+anno[5]+";CorrespondingGene:"+rs2gene.get(pmid+"\t"+RSNum)+";Recognized-RS#:"+RSNum+"(Expired)\n"; } else { //Merged rs = stmt_merged.executeQuery("SELECT merged FROM Merged WHERE origin='"+RSNum+"' limit 1;"); if ( rs.next() ) { outputSTR=outputSTR+anno[0]+"\t"+anno[1]+"\t"+anno[2]+"\t"+anno[3]+"\t"+mentiontype+"\t"+anno[5]+";CorrespondingGene:"+rs2gene.get(pmid+"\t"+RSNum)+";Recognized-RS#:"+rs.getString("merged")+"\n"; } else { outputSTR=outputSTR+anno[0]+"\t"+anno[1]+"\t"+anno[2]+"\t"+anno[3]+"\t"+mentiontype+"\t"+anno[5]+";CorrespondingGene:"+rs2gene.get(pmid+"\t"+RSNum)+";Recognized-RS#:"+RSNum+"\n"; } } } else if(rs_foundbefore_hash.containsKey(anno[0]+"\t"+NormalizedForm)) //already found by dictionary-lookup (no need to repeat the action) { String RSNum=rs_foundbefore_hash.get(anno[0]+"\t"+NormalizedForm); //Expired ResultSet rs = stmt_expired.executeQuery("SELECT rs FROM Expired WHERE rs='"+RSNum+"' limit 1;"); if ( rs.next() ) { outputSTR=outputSTR+anno[0]+"\t"+anno[1]+"\t"+anno[2]+"\t"+anno[3]+"\t"+mentiontype+"\t"+anno[5]+";CorrespondingGene:"+rs2gene.get(pmid+"\t"+RSNum)+";Foundbefore-RS#:"+RSNum+"(Expired)\n"; MentionPatternMap2rs_extend.put(anno[0]+"\t"+anno[5],RSNum+"(Expired)"); } else { //Merged rs = stmt_merged.executeQuery("SELECT merged FROM Merged WHERE origin='"+RSNum+"' limit 1;"); if ( rs.next() ) { outputSTR=outputSTR+anno[0]+"\t"+anno[1]+"\t"+anno[2]+"\t"+anno[3]+"\t"+mentiontype+"\t"+anno[5]+";CorrespondingGene:"+rs2gene.get(pmid+"\t"+RSNum)+";Foundbefore-RS#:"+rs.getString("merged")+"\n"; MentionPatternMap2rs_extend.put(anno[0]+"\t"+anno[5],rs.getString("merged")); } else { outputSTR=outputSTR+anno[0]+"\t"+anno[1]+"\t"+anno[2]+"\t"+anno[3]+"\t"+mentiontype+"\t"+anno[5]+";CorrespondingGene:"+rs2gene.get(pmid+"\t"+RSNum)+";Foundbefore-RS#:"+RSNum+"\n"; MentionPatternMap2rs_extend.put(anno[0]+"\t"+anno[5],RSNum); } } } else { boolean found=false; String tmVarid_tmp=anno[5]; //c|SUB|C|1749|T tmVarid_tmp=tmVarid_tmp.replaceAll("^\\+", ""); /** * 1. compare with history * 2. compare with RS# in text (the mutation should exist in database) * 3. compare with RefSeq * 4. compare with gene2rs * 5. Extended * 6. compare with chromosome# */ /* * 1. compare with history */ for(String pmid_geneid : pmid_gene2rs.keySet()) { String pmid_geneid_split[] = pmid_geneid.split("\t"); String pmidID=pmid_geneid_split[0]; String geneid=pmid_geneid_split[1]; if(pmidID.equals(anno[0])) { if(tmVar.Mutation_RS_Geneid_hash.containsKey(tmVarid_tmp+"\t"+geneid)) //in history { String RSNum=tmVar.Mutation_RS_Geneid_hash.get(tmVarid_tmp+"\t"+geneid); //Expired ResultSet rs = stmt_expired.executeQuery("SELECT rs FROM Expired WHERE rs='"+RSNum+"' limit 1;"); if ( rs.next() ) { outputSTR=outputSTR+anno[0]+"\t"+anno[1]+"\t"+anno[2]+"\t"+anno[3]+"\t"+mentiontype+"\t"+anno[5]+";CorrespondingGene:"+rs2gene.get(pmid+"\t"+RSNum)+";Mapping-RS#:"+RSNum+"(Expired)\n"; MentionPatternMap2rs_extend.put(anno[0]+"\t"+anno[5],RSNum+"(Expired)"); } else { //Merged rs = stmt_merged.executeQuery("SELECT merged FROM Merged WHERE origin='"+RSNum+"' limit 1;"); if ( rs.next() ) { outputSTR=outputSTR+anno[0]+"\t"+anno[1]+"\t"+anno[2]+"\t"+anno[3]+"\t"+mentiontype+"\t"+anno[5]+";CorrespondingGene:"+rs2gene.get(pmid+"\t"+RSNum)+";Mapping-RS#:"+rs.getString("merged")+"\n"; MentionPatternMap2rs_extend.put(anno[0]+"\t"+anno[5],rs.getString("merged")); } else { outputSTR=outputSTR+anno[0]+"\t"+anno[1]+"\t"+anno[2]+"\t"+anno[3]+"\t"+mentiontype+"\t"+anno[5]+";CorrespondingGene:"+rs2gene.get(pmid+"\t"+RSNum)+";Mapping-RS#:"+RSNum+"\n"; MentionPatternMap2rs_extend.put(anno[0]+"\t"+anno[5],RSNum); } } found=true; break; } } } if(found == false) { HashMap<String,String> rs2var = new HashMap<String,String>(); //Search database for normalization if(normalized_mutation.containsKey(anno[5])) // The variant has been normalized { mutation2rs_indatabase.put(anno[0]+"\t"+anno[1]+"\t"+anno[2]+"\t"+anno[3]+"\t"+anno[5],normalized_mutation.get(anno[5])); } else { try { String DB="var2rs_p"; String Table="var2rs_p"; if(component[0].equals("p")) { DB="var2rs_p"; Table="var2rs_p"; } else if(component[0].equals("c") || component[0].equals("r")) { DB="var2rs_c"; Table="var2rs_c"; } else if(component[0].equals("m")) { DB="var2rs_m"; Table="var2rs_m"; } else if(component[0].equals("n")) { DB="var2rs_n"; Table="var2rs_n"; } else if(component[0].equals("g")) { //DB="var2rs_g";Table="var2rs_g"; if(component[3].matches("^10.*$")) {DB="var2rs_g.10";Table="var2rs";} else if(component[3].matches("^11.*$")) {DB="var2rs_g.11";Table="var2rs";} else if(component[3].matches("^12.*$")) {DB="var2rs_g.12";Table="var2rs";} else if(component[3].matches("^13.*$")) {DB="var2rs_g.13";Table="var2rs";} else if(component[3].matches("^14.*$")) {DB="var2rs_g.14";Table="var2rs";} else if(component[3].matches("^15.*$")) {DB="var2rs_g.15";Table="var2rs";} else if(component[3].matches("^16.*$")) {DB="var2rs_g.16";Table="var2rs";} else if(component[3].matches("^17.*$")) {DB="var2rs_g.17";Table="var2rs";} else if(component[3].matches("^18.*$")) {DB="var2rs_g.18";Table="var2rs";} else if(component[3].matches("^19.*$")) {DB="var2rs_g.19";Table="var2rs";} else if(component[3].matches("^2.*$")) {DB="var2rs_g.2";Table="var2rs";} else if(component[3].matches("^3.*$")) {DB="var2rs_g.3";Table="var2rs";} else if(component[3].matches("^4.*$")) {DB="var2rs_g.4";Table="var2rs";} else if(component[3].matches("^5.*$")) {DB="var2rs_g.5";Table="var2rs";} else if(component[3].matches("^6.*$")) {DB="var2rs_g.6";Table="var2rs";} else if(component[3].matches("^7.*$")) {DB="var2rs_g.7";Table="var2rs";} else if(component[3].matches("^8.*$")) {DB="var2rs_g.8";Table="var2rs";} else if(component[3].matches("^9.*$")) {DB="var2rs_g.9";Table="var2rs";} else{DB="var2rs_g.19";Table="var2rs";} } String rsNumber=""; //N prefix { c = DriverManager.getConnection("jdbc:sqlite:Database/"+DB+".db"); stmt = c.createStatement(); String NormalizedForm_arr[]=NormalizedForm.split("\\|"); String SQL="SELECT rs,var FROM "+Table+" WHERE "; for(int nfa=0;nfa<NormalizedForm_arr.length;nfa++) { SQL=SQL+"var='"+NormalizedForm_arr[nfa]+"' or "; } SQL=SQL.replaceAll(" or $", ""); ResultSet rs = stmt.executeQuery(SQL+" order by var"); while ( rs.next() ) { String rss[]=rs.getString("rs").split("\\|"); for(int rsi=0;rsi<rss.length;rsi++) { rs2var.put(rss[rsi], rs.getString("var")); } if(rsNumber.equals("")) { rsNumber = rs.getString("rs"); } else { rsNumber = rsNumber+"|"+rs.getString("rs"); } } stmt.close(); c.close(); rsNumber=rsNumber+"|end"; } //NormalizedForm_reverse if(!NormalizedForm_reverse.equals("")) { c = DriverManager.getConnection("jdbc:sqlite:Database/"+DB+".db"); stmt = c.createStatement(); String NormalizedForm_arr[]=NormalizedForm_reverse.split("\\|"); String SQL="SELECT rs,var FROM "+Table+" WHERE "; for(int nfa=0;nfa<NormalizedForm_arr.length;nfa++) { SQL=SQL+"var='"+NormalizedForm_arr[nfa]+"' or "; } SQL=SQL.replaceAll(" or $", ""); ResultSet rs = stmt.executeQuery(SQL+" order by var"); while ( rs.next() ) { String rss[]=rs.getString("rs").split("\\|"); for(int rsi=0;rsi<rss.length;rsi++) { rs2var.put(rss[rsi], rs.getString("var")); } if(rsNumber.equals("")) { rsNumber = rs.getString("rs"); } else { rsNumber = rsNumber+"|"+rs.getString("rs"); } } stmt.close(); c.close(); rsNumber=rsNumber+"|end"; } //NormalizedForm - proteinchange if(!Flag_Seq.equals("c")) { c = DriverManager.getConnection("jdbc:sqlite:Database/var2rs_clinvar_proteinchange.db"); stmt = c.createStatement(); String NormalizedForm_arr[]=NormalizedForm.split("\\|"); String SQL="SELECT rs,var FROM var2rs_clinvar_proteinchange WHERE "; for(int nfa=0;nfa<NormalizedForm_arr.length;nfa++) { SQL=SQL+"var='"+NormalizedForm_arr[nfa]+"' or "; } SQL=SQL.replaceAll(" or $", ""); ResultSet rs = stmt.executeQuery(SQL+" order by var"); while ( rs.next() ) { String rss[]=rs.getString("rs").split("\\|"); for(int rsi=0;rsi<rss.length;rsi++) { rs2var.put(rss[rsi], rs.getString("var")); } if(rsNumber.equals("")) { rsNumber = rs.getString("rs"); } else { rsNumber = rsNumber+"|"+rs.getString("rs"); } } stmt.close(); c.close(); rsNumber=rsNumber+"|end"; } //NormalizedForm - reverse_proteinchange if(!Flag_Seq.equals("c")) { c = DriverManager.getConnection("jdbc:sqlite:Database/var2rs_clinvar_proteinchange.db"); stmt = c.createStatement(); String NormalizedForm_arr[]=NormalizedForm_reverse.split("\\|"); String SQL="SELECT rs,var FROM var2rs_clinvar_proteinchange WHERE "; for(int nfa=0;nfa<NormalizedForm_arr.length;nfa++) { SQL=SQL+"var='"+NormalizedForm_arr[nfa]+"' or "; } SQL=SQL.replaceAll(" or $", ""); ResultSet rs = stmt.executeQuery(SQL+" order by var"); while ( rs.next() ) { String rss[]=rs.getString("rs").split("\\|"); for(int rsi=0;rsi<rss.length;rsi++) { rs2var.put(rss[rsi], rs.getString("var")); } if(rsNumber.equals("")) { rsNumber = rs.getString("rs"); } else { rsNumber = rsNumber+"|"+rs.getString("rs"); } } stmt.close(); c.close(); rsNumber=rsNumber+"|end"; } //if DNA cannot found, try protein if((!NormalizedForm_protein.equals("")) && (!Flag_Seq.equals("c"))) { DB="var2rs_p"; Table="var2rs_p"; boolean found_changetype=false; c = DriverManager.getConnection("jdbc:sqlite:Database/"+DB+".db"); stmt = c.createStatement(); String NormalizedForm_arr[]=NormalizedForm_protein.split("\\|"); String SQL="SELECT rs,var FROM "+Table+" WHERE "; for(int nfa=0;nfa<NormalizedForm_arr.length;nfa++) { SQL=SQL+"var='"+NormalizedForm_arr[nfa]+"' or "; } SQL=SQL.replaceAll(" or $", ""); ResultSet rs = stmt.executeQuery(SQL+" order by var"); while ( rs.next() ) { found_changetype=true; String rss[]=rs.getString("rs").split("\\|"); for(int rsi=0;rsi<rss.length;rsi++) { rs2var.put(rss[rsi], rs.getString("var")); } if(rsNumber.equals("")) { rsNumber = rs.getString("rs"); } else { rsNumber = rsNumber+"|"+rs.getString("rs"); } } stmt.close(); c.close(); rsNumber=rsNumber+"|end"; } //System.out.println(anno[0]+"\t"+anno[1]+"\t"+anno[2]+"\t"+anno[3]+"\t"+anno[5]+"\t"+rsNumber); mutation2rs_indatabase.put(anno[0]+"\t"+anno[1]+"\t"+anno[2]+"\t"+anno[3]+"\t"+anno[5],rsNumber); normalized_mutation.put(anno[5],rsNumber); } catch ( SQLException e ) { System.err.println( e.getClass().getName() + ": " + e.getMessage() ); } } /* * 2. compare with co-occurred RS# in text (the mutation should exist in database) */ if(mutation2rs_indatabase.containsKey(anno[0]+"\t"+anno[1]+"\t"+anno[2]+"\t"+anno[3]+"\t"+anno[5])) //the mutation mention can find RS#s in dictionary { String rsNumbers_arr[] = mutation2rs_indatabase.get(anno[0]+"\t"+anno[1]+"\t"+anno[2]+"\t"+anno[3]+"\t"+anno[5]).split("\\|"); for(int ra=0;ra<rsNumbers_arr.length;ra++) { String RSNum=rsNumbers_arr[ra]; pat = Pattern.compile("^([0-9]+)[\\-\\/](.*)$"); mat = pat.matcher(rsNumbers_arr[ra]); if(mat.find()) { RSNum = mat.group(1); } if(RSnumberList.containsKey(anno[0]+"\t"+RSNum)) //one of the RS#s is in the text, no need to normalized by gene { rs_foundinText_hash.put(anno[0]+"\t"+NormalizedForm, RSNum); //Expired ResultSet rs = stmt_expired.executeQuery("SELECT rs FROM Expired WHERE rs='"+RSNum+"' limit 1;"); if ( rs.next() ) { outputSTR=outputSTR+anno[0]+"\t"+anno[1]+"\t"+anno[2]+"\t"+anno[3]+"\t"+mentiontype+"\t"+anno[5]+";CorrespondingGene:"+rs2gene.get(pmid+"\t"+RSNum)+";SNPinText-RS#:"+RSNum+"(Expired)\n"; MentionPatternMap2rs_extend.put(anno[0]+"\t"+anno[5],RSNum+"(Expired)"); } else { //Merged rs = stmt_merged.executeQuery("SELECT merged FROM Merged WHERE origin='"+RSNum+"' limit 1;"); if ( rs.next() ) { outputSTR=outputSTR+anno[0]+"\t"+anno[1]+"\t"+anno[2]+"\t"+anno[3]+"\t"+mentiontype+"\t"+anno[5]+";CorrespondingGene:"+rs2gene.get(pmid+"\t"+RSNum)+";SNPinText-RS#:"+rs.getString("merged")+"\n"; MentionPatternMap2rs_extend.put(anno[0]+"\t"+anno[5],rs.getString("merged")); } else { outputSTR=outputSTR+anno[0]+"\t"+anno[1]+"\t"+anno[2]+"\t"+anno[3]+"\t"+mentiontype+"\t"+anno[5]+";CorrespondingGene:"+rs2gene.get(pmid+"\t"+RSNum)+";SNPinText-RS#:"+RSNum+"\n"; MentionPatternMap2rs_extend.put(anno[0]+"\t"+anno[5],RSNum); } } ra = rsNumbers_arr.length; //last found=true; } } } /* * 3. compare with RefSeq */ if(found == false) { HashMap<String,String> Unique_RefSeq = new HashMap<String,String>(); for(String RefSeq : annotations_RefSeq.keySet()) { String RefSeq_anno[] = RefSeq.split("\t"); //pmid,start,last,mention,RefSeq if(anno[0].equals(RefSeq_anno[0]) && RefSeq_anno.length>=5) { Unique_RefSeq.put(annotations_RefSeq.get(RefSeq),""); } } if(mutation2rs_indatabase.containsKey(anno[0]+"\t"+anno[1]+"\t"+anno[2]+"\t"+anno[3]+"\t"+anno[5])) { String rsNumbers_arr[]=mutation2rs_indatabase.get(anno[0]+"\t"+anno[1]+"\t"+anno[2]+"\t"+anno[3]+"\t"+anno[5]).split("\\|"); for(int ra=0;ra<rsNumbers_arr.length;ra++) { String RSNum=rsNumbers_arr[ra]; pat = Pattern.compile("^([0-9]+)[\\-\\/](.*)$"); mat = pat.matcher(rsNumbers_arr[ra]); if(mat.find()) { RSNum = mat.group(1); String Chro_RefSeqs = mat.group(2); String Chro_RefSeq_arr[] = Chro_RefSeqs.split("/"); for(int ch=0;ch<Chro_RefSeq_arr.length;ch++) { if(Unique_RefSeq.containsKey(Chro_RefSeq_arr[ch])) { //Expired ResultSet rs = stmt_expired.executeQuery("SELECT rs FROM Expired WHERE rs='"+RSNum+"' limit 1;"); if ( rs.next() ) { outputSTR=outputSTR+anno[0]+"\t"+anno[1]+"\t"+anno[2]+"\t"+anno[3]+"\t"+mentiontype+"\t"+anno[5]+";CorrespondingGene:"+rs2gene.get(pmid+"\t"+RSNum)+";RefSeq-RS#:"+RSNum+"(Expired)\n"; MentionPatternMap2rs_extend.put(anno[0]+"\t"+anno[5],RSNum+"(Expired)"); } else { //Merged rs = stmt_merged.executeQuery("SELECT merged FROM Merged WHERE origin='"+RSNum+"' limit 1;"); if ( rs.next() ) { outputSTR=outputSTR+anno[0]+"\t"+anno[1]+"\t"+anno[2]+"\t"+anno[3]+"\t"+mentiontype+"\t"+anno[5]+";CorrespondingGene:"+rs2gene.get(pmid+"\t"+RSNum)+";RefSeq-RS#:"+rs.getString("merged")+"\n"; MentionPatternMap2rs_extend.put(anno[0]+"\t"+anno[5],rs.getString("merged")); } else { outputSTR=outputSTR+anno[0]+"\t"+anno[1]+"\t"+anno[2]+"\t"+anno[3]+"\t"+mentiontype+"\t"+anno[5]+";CorrespondingGene:"+rs2gene.get(pmid+"\t"+RSNum)+";RefSeq-RS#:"+RSNum+"\n"; MentionPatternMap2rs_extend.put(anno[0]+"\t"+anno[5],RSNum); } } ra = rsNumbers_arr.length; //last found=true; } } } } } } /* * 4. compare with gene2rs */ if(found == false) // can't find relevant RS# in text { HashMap<String,Integer> geneRS2distance_hash= new HashMap<String,Integer>(); HashMap<Integer,ArrayList<String>> sentencelocation_gene_hash= new HashMap<Integer,ArrayList<String>>(); //sentence --> gene ids int sentencelocation_rs=0; int sentencelocation_gene=0; //detect the sentence boundaries for gene and RS# for(String gene : annotations_gene.keySet()) { String gene_anno[] = gene.split("\t"); //pmid,start,last,mention,geneid if(anno[0].equals(gene_anno[0]) && gene_anno.length>=5) { ArrayList<Integer> SentenceOffsets = PMID2SentenceOffsets.get(anno[0]); for(int si=0;si<SentenceOffsets.size();si++) // find sentence location for gene mention { if(Integer.parseInt(gene_anno[1])<SentenceOffsets.get(si)) //gene_anno[1] = start { if(!sentencelocation_gene_hash.containsKey(si-1)) { sentencelocation_gene_hash.put(si-1,new ArrayList<String>()); } sentencelocation_gene_hash.get(si-1).add(gene_anno[4]); //gene_info[4] = gene identifier sentencelocation_gene=si-1; break; } } for(int si=0;si<SentenceOffsets.size();si++) // find sentence location for rs mention { if(Integer.parseInt(anno[1])<SentenceOffsets.get(si)) { sentencelocation_rs=si-1; break; } } if(Integer.parseInt(gene_anno[2])<=Integer.parseInt(anno[1])) // gene --- mutation { int distance = Integer.parseInt(anno[1])-Integer.parseInt(gene_anno[2]); if(sentencelocation_gene != sentencelocation_rs){distance=distance+1000;} if(!geneRS2distance_hash.containsKey(annotations_gene.get(gene))) { geneRS2distance_hash.put(annotations_gene.get(gene),distance); } else if(distance<geneRS2distance_hash.get(annotations_gene.get(gene))) { geneRS2distance_hash.put(annotations_gene.get(gene),distance); } } else if(Integer.parseInt(gene_anno[1])>=Integer.parseInt(anno[2])) // mutation --- gene { int distance = Integer.parseInt(gene_anno[1])-Integer.parseInt(anno[2]); if(sentencelocation_gene != sentencelocation_rs){distance=distance+1000;} if(!geneRS2distance_hash.containsKey(annotations_gene.get(gene))) { geneRS2distance_hash.put(annotations_gene.get(gene),distance); } else if(distance<geneRS2distance_hash.get(annotations_gene.get(gene))) { geneRS2distance_hash.put(annotations_gene.get(gene),distance); } } else // mutation & gene may overlap { geneRS2distance_hash.put(annotations_gene.get(gene),0); } } } // ranking the geneRS based on the distance ArrayList <String> geneRS_ranked = new ArrayList <String>(); while(!geneRS2distance_hash.isEmpty()) { int closet_distance=10000000; String closet_geneRS=""; for (String geneRS : geneRS2distance_hash.keySet()) { if(geneRS2distance_hash.get(geneRS)<closet_distance) { closet_distance=geneRS2distance_hash.get(geneRS); closet_geneRS=geneRS; } } if(closet_geneRS.equals("")) { break; } geneRS_ranked.add(closet_geneRS); geneRS2distance_hash.remove(closet_geneRS); } // if at least one gene and RS# are in the same sentence, only look at those genes in the same sentence. int number_geneRS=geneRS_ranked.size(); /* if(number_geneRS>0 && sentencelocation_gene_hash.containsKey(sentencelocation_rs)) { if(number_geneRS>sentencelocation_gene_hash.get(sentencelocation_rs).size()) { number_geneRS=sentencelocation_gene_hash.get(sentencelocation_rs).size(); } } */ for(int rsg=0;rsg<number_geneRS;rsg++) { String target_gene_rs=geneRS_ranked.get(rsg); String geneRSs[]=target_gene_rs.split("\\|"); if(mutation2rs_indatabase.containsKey(anno[0]+"\t"+anno[1]+"\t"+anno[2]+"\t"+anno[3]+"\t"+anno[5])) { String rsNumbers_arr[]=mutation2rs_indatabase.get(anno[0]+"\t"+anno[1]+"\t"+anno[2]+"\t"+anno[3]+"\t"+anno[5]).split("\\|"); String found_rs = ""; /* * Compare the RS#s found by Gene and Variants * RS#s (Gene) <-----> RS#s (Variant) */ HashMap<String,Integer> rshash = new HashMap<String,Integer>(); String lastvar=""; for(int ra=0;ra<rsNumbers_arr.length;ra++) { String RSNum=rsNumbers_arr[ra]; pat = Pattern.compile("^([0-9]+)[\\-\\/](.*)$"); mat = pat.matcher(rsNumbers_arr[ra]); if(mat.find()) { RSNum = mat.group(1); } for(int g=0;g<geneRSs.length;g++) { if(found==true && RSNum.equals("end")) { //leave the loop ra=rsNumbers_arr.length; g=geneRSs.length; } else if(geneRSs[g].equals(RSNum) && !geneRSs[g].equals("")) { if(rshash.containsKey(geneRSs[g])) { // removed duplicated RSs : RS#:747319628|747319628 } else { found=true; String currentvar=""; if(rs2var.containsKey(RSNum)){currentvar=rs2var.get(RSNum);} if(found_rs.equals("")) { found_rs = geneRSs[g]; } else { if(lastvar.equals("") || lastvar.equals(currentvar)) { found_rs = found_rs+"|"+ geneRSs[g]; } else { found_rs = found_rs+";"+ geneRSs[g]; } } lastvar=currentvar; rshash.put(geneRSs[g], 1); } } } } if(!found_rs.equals("")) { rs_foundbefore_hash.put(anno[0]+"\t"+NormalizedForm, found_rs); } if(found == true) { String RSNum=found_rs; //Expired ResultSet rs = stmt_expired.executeQuery("SELECT rs FROM Expired WHERE rs='"+RSNum+"' limit 1;"); if ( rs.next() ) { outputSTR=outputSTR+anno[0]+"\t"+anno[1]+"\t"+anno[2]+"\t"+anno[3]+"\t"+mentiontype+"\t"+anno[5]+";CorrespondingGene:"+rs2gene.get(pmid+"\t"+RSNum)+";GeneNormalized-RS#:"+RSNum+"(Expired)\n"; MentionPatternMap2rs_extend.put(anno[0]+"\t"+anno[5],RSNum+"(Expired)"); } else { //Merged rs = stmt_merged.executeQuery("SELECT merged FROM Merged WHERE origin='"+RSNum+"' limit 1;"); if ( rs.next() ) { outputSTR=outputSTR+anno[0]+"\t"+anno[1]+"\t"+anno[2]+"\t"+anno[3]+"\t"+mentiontype+"\t"+anno[5]+";CorrespondingGene:"+rs2gene.get(pmid+"\t"+RSNum)+";GeneNormalized-RS#:"+rs.getString("merged")+"\n"; MentionPatternMap2rs_extend.put(anno[0]+"\t"+anno[5],rs.getString("merged")); } else { outputSTR=outputSTR+anno[0]+"\t"+anno[1]+"\t"+anno[2]+"\t"+anno[3]+"\t"+mentiontype+"\t"+anno[5]+";CorrespondingGene:"+rs2gene.get(pmid+"\t"+RSNum)+";GeneNormalized-RS#:"+RSNum+"\n"; MentionPatternMap2rs_extend.put(anno[0]+"\t"+anno[5],RSNum); } } rsg=geneRS_ranked.size(); } } } } /* * 5. Extended */ if(found == false) { if(MentionPatternMap2rs_extend.containsKey(anno[0]+"\t"+anno[5])) //by pattern [PMID:24073655] c.169G>C (p.Gly57Arg) -- map to rs764352037 { String RSNum=MentionPatternMap2rs_extend.get(anno[0]+"\t"+anno[5]); outputSTR=outputSTR+anno[0]+"\t"+anno[1]+"\t"+anno[2]+"\t"+anno[3]+"\t"+mentiontype+"\t"+anno[5]+";CorrespondingGene:"+rs2gene.get(pmid+"\t"+RSNum)+";Extended-RS#:"+RSNum+"\n"; found=true; } } /* * 6. Variant2MostCorrespondingGene_hash */ if(found == false) // can't find relevant RS# in text { if(tmVar.Variant2MostCorrespondingGene_hash.containsKey(anno[3].toLowerCase())) { String nt[]=tmVar.Variant2MostCorrespondingGene_hash.get(anno[3].toLowerCase()).split("\t"); //4524 1801133 MTHFR C677T String geneid=nt[0]; String rsid=nt[1]; outputSTR=outputSTR+anno[0]+"\t"+anno[1]+"\t"+anno[2]+"\t"+anno[3]+"\t"+mentiontype+"\t"+anno[5]+";CorrespondingGene:"+geneid+";RS#:"+rsid+"\n"; found=true; } } /* * Others */ if(found == false) { outputSTR=outputSTR+anno[0]+"\t"+anno[1]+"\t"+anno[2]+"\t"+anno[3]+"\t"+mentiontype+"\t"+anno[5]+"\n"; } } } if(MentionPatternMap2rs_extend.containsKey(anno[0]+"\t"+anno[5])) { if(MentionPatternMap.containsKey(anno[0]+"\t"+anno[5])) { MentionPatternMap2rs_extend.put(anno[0]+"\t"+MentionPatternMap.get(anno[0]+"\t"+anno[5]), MentionPatternMap2rs_extend.get(anno[0]+"\t"+anno[5])); String tmp_anno5 = MentionPatternMap.get(anno[0]+"\t"+anno[5]).replaceAll("([^A-Za-z0-9])","\\\\$1"); String RSNum=MentionPatternMap2rs_extend.get(anno[0]+"\t"+anno[5]); outputSTR=outputSTR.replaceAll(tmp_anno5+"\n", tmp_anno5+";CorrespondingGene:"+rs2gene.get(pmid+"\t"+RSNum)+";Extended-RS#:"+RSNum+"\n"); } else { MentionPatternMap2rs_extend.put(anno[0]+"\t"+anno[5], MentionPatternMap2rs_extend.get(anno[0]+"\t"+anno[5])); String tmp_anno5 = anno[5].replaceAll("([^A-Za-z0-9])","\\\\$1"); String RSNum=MentionPatternMap2rs_extend.get(anno[0]+"\t"+anno[5]); outputSTR=outputSTR.replaceAll(tmp_anno5+"\n", tmp_anno5+";CorrespondingGene:"+rs2gene.get(pmid+"\t"+RSNum)+";Extended-RS#:"+RSNum+"\n"); } } } else if(mentiontype.equals("SNP")) { String RSNum=anno[5].replace("[Rr][Ss]", ""); RSNum=RSNum.replaceAll("[\\W\\-\\_]", ""); //Expired ResultSet rs = stmt_expired.executeQuery("SELECT rs FROM Expired WHERE rs='"+RSNum+"' limit 1;"); if ( rs.next() ) { String RSnum=anno[5]; RSnum=RSnum.replaceAll("[\\W\\-\\_RrSs]", ""); outputSTR=outputSTR+anno[0]+"\t"+anno[1]+"\t"+anno[2]+"\t"+anno[3]+"\t"+mentiontype+"\t"+anno[5]+"(Expired)"+";CorrespondingGene:"+rs2gene.get(pmid+"\t"+RSnum)+";RS#:"+RSnum+"\n"; } else { //Merged rs = stmt_merged.executeQuery("SELECT merged FROM Merged WHERE origin='"+RSNum+"' limit 1;"); if ( rs.next() ) { String RSnum=rs.getString("merged"); outputSTR=outputSTR+anno[0]+"\t"+anno[1]+"\t"+anno[2]+"\t"+anno[3]+"\t"+mentiontype+"\t"+anno[5]+";CorrespondingGene:"+rs2gene.get(pmid+"\t"+RSnum)+";RS#:"+RSnum+"\n"; } else { String RSnum=anno[5]; RSnum=RSnum.replaceAll("[\\W\\-\\_RrSs]", ""); outputSTR=outputSTR+anno[0]+"\t"+anno[1]+"\t"+anno[2]+"\t"+anno[3]+"\t"+mentiontype+"\t"+anno[5]+";CorrespondingGene:"+rs2gene.get(pmid+"\t"+RSnum)+";RS#:"+RSnum+"\n"; } } } else { outputSTR=outputSTR+anno[0]+"\t"+anno[1]+"\t"+anno[2]+"\t"+anno[3]+"\t"+mentiontype+"\t"+anno[5]+"\n"; } } else { outputSTR=outputSTR+anno[0]+"\t"+anno[1]+"\t"+anno[2]+"\t"+anno[3]+"\t"+mentiontype+"\t"+anno[5]+"\n"; } } else if (line.equals("")) { HashMap <String,String> OnlyOneRSnumbers=new HashMap<String,String>(); /* * 1) Consistency: C.1799C>A and V600E should be normalized to the same RS#. * 2) Sorting tmVar.VariantFrequency * 3) G469A from DNA to Protein mutation * 4) BRAFV600E */ String tiabs_rev = tiabs.replaceAll("[\\-\\_]", " "); String BCon="Variant"; int PrefixTranslation = 1; int Tok_NumCharPartialMatch = 0; ArrayList<String> locations = tmVar.PT_GeneVariantMention.SearchMentionLocation(tiabs_rev,tiabs,BCon,PrefixTranslation,Tok_NumCharPartialMatch); for (int k = 0 ; k < locations.size() ; k++) { String anno[]=locations.get(k).split("\t"); String start=anno[0]; String last=anno[1]; String ment=anno[2]; String type=anno[3]; String rsid=anno[4]; outputSTR=outputSTR.replaceAll(pmid+"\t[0-9]+\t"+last+"\t.*\n",""); outputSTR=outputSTR+pmid+"\t"+start+"\t"+last+"\t"+ment+"\t"+type+"\t"+rsid+"\n"; } HashMap<String,HashMap<String,String>> VariantLinking = new HashMap<String,HashMap<String,String>>(); HashMap<String,HashMap<Integer,Integer>> VarID2Mention = new HashMap<String,HashMap<Integer,Integer>>(); //for variant-gene assocation only String outputSTR_tmp=""; boolean DNAProteinMutation_exists=false; String outputSTR_line[]=outputSTR.split("\n"); for(int l=0;l<outputSTR_line.length;l++) { String lstr=outputSTR_line[l]; String lstr_column[]=lstr.split("\t"); if(lstr_column.length>=5) { if(lstr_column[1].matches("[0-9]+") && lstr_column[2].matches("[0-9]+")) // in case the text contains "\t" { int start=Integer.parseInt(lstr_column[1]); int last=Integer.parseInt(lstr_column[2]); String mention=lstr_column[3]; String type=lstr_column[4]; String IDcolumn=lstr_column[5]; pat = Pattern.compile("^(.+);CorrespondingGene:[0-9null]+;(|SameGroup-|GeneNormalized-|Pattern-|Extended-|Recognized-|Mapping-|SNPinText-|Foundbefore-|RefSeq-)RS#:(.+)$"); mat = pat.matcher(IDcolumn); if(mat.find()) { IDcolumn = mat.group(1); String RSnum = "rs"+mat.group(3); if(!VariantLinking.containsKey(pmid+"\t"+RSnum)) { VariantLinking.put(pmid+"\t"+RSnum,new HashMap<String,String>()); } VariantLinking.get(pmid+"\t"+RSnum).put(pmid+"\t"+IDcolumn,""); if(!VariantLinking.containsKey(pmid+"\t"+IDcolumn)) { VariantLinking.put(pmid+"\t"+IDcolumn,new HashMap<String,String>()); } VariantLinking.get(pmid+"\t"+IDcolumn).put(pmid+"\t"+RSnum,""); } //for variant-gene association only: Variant# <p|SUB|V|600|E> --> Mentions (Hash) if(!VarID2Mention.containsKey(pmid+"\t"+IDcolumn)) { VarID2Mention.put(pmid+"\t"+IDcolumn, new HashMap<Integer,Integer>()); } VarID2Mention.get(pmid+"\t"+IDcolumn).put(start,last);//start+"\t"+last+"\t"+mention if(type.matches("(DNAMutation|ProteinMutation|SNP)")) // used to remove Allele only { DNAProteinMutation_exists = true; } // Sort the rsids pat = Pattern.compile("^(.+RS#:)(.+)$"); mat = pat.matcher(lstr); if(mat.find()) { if(changetype.containsKey(lstr_column[3])) { lstr=lstr.replaceAll("\tDNAMutation\tc", "\tProteinMutation\tp"); } String pre = mat.group(1); String rsids = mat.group(2); String individualconcept_rsids[]=rsids.split(";"); rsids=""; for(int ics=0;ics<individualconcept_rsids.length;ics++) { String individualconcept_rsid[]=individualconcept_rsids[ics].split("\\|"); if(individualconcept_rsid.length>1) { //sorting for(int ic=0;ic<individualconcept_rsid.length;ic++) { for(int jc=1;jc<(individualconcept_rsid.length-ic);jc++) { int var1=0; int var2=0; if(tmVar.VariantFrequency.containsKey("rs"+individualconcept_rsid[jc-1])){var1=tmVar.VariantFrequency.get("rs"+individualconcept_rsid[jc-1]);} if(tmVar.VariantFrequency.containsKey("rs"+individualconcept_rsid[jc])){var2=tmVar.VariantFrequency.get("rs"+individualconcept_rsid[jc]);} if(var1 < var2) { String temp = individualconcept_rsid[jc-1]; individualconcept_rsid[jc-1] = individualconcept_rsid[jc]; individualconcept_rsid[jc] = temp; } } } int rsid_len=individualconcept_rsid.length; for(int ic=0;ic<rsid_len;ic++) { if(rsids.equals("")) { rsids=individualconcept_rsid[ic]; } else { if(ic==0) { rsids=rsids+","+individualconcept_rsid[ic]; } else { rsids=rsids+"|"+individualconcept_rsid[ic]; } } } } else { if(rsids.equals("")) { rsids=individualconcept_rsids[ics]; } else { rsids=rsids+","+individualconcept_rsids[ics]; } } if(individualconcept_rsids.length==1 && individualconcept_rsid.length==1) // 113488022|121913377 (V600E) && 113488022 (c.1799T>G) --> 113488022 (V600E) && 113488022 (c.1799T>G) { OnlyOneRSnumbers.put(individualconcept_rsid[0],""); } } lstr=pre+rsids; } } outputSTR_tmp=outputSTR_tmp+lstr+"\n"; } else { outputSTR_tmp=outputSTR_tmp+lstr+"\n"; } } outputSTR=outputSTR_tmp; // 113488022|121913377 (V600E) && 113488022 (c.1799T>G) --> 113488022 (V600E) && 113488022 (c.1799T>G) outputSTR_tmp=""; outputSTR_line=outputSTR.split("\n"); for(int l=0;l<outputSTR_line.length;l++) { String lstr=outputSTR_line[l]; String lstr_column[]=lstr.split("\t"); if(lstr_column.length>=5) { if(lstr_column[1].matches("[0-9]+") && lstr_column[2].matches("[0-9]+")) { String type = lstr_column[4]; int mention_len = lstr_column[3].length(); if(DNAProteinMutation_exists==true || type.matches("(Chromosome|RefSeq|AcidChange|GenomicRegion|CopyNumberVariant)") || mention_len>20) // at least one variant (mention_len>20: natural language mention) { pat = Pattern.compile("^(.+RS#:)(.+)$"); mat = pat.matcher(lstr); if(mat.find()) { String pre = mat.group(1); String rsids = mat.group(2); String individualconcept_rsids[]=rsids.split(";"); rsids=""; for(int ics=0;ics<individualconcept_rsids.length;ics++) { String individualconcept_rsid[]=individualconcept_rsids[ics].split("\\|"); if(individualconcept_rsid.length>1) { for(String OnlyOne : OnlyOneRSnumbers.keySet()) { if(individualconcept_rsids[ics].matches(".+\\|"+OnlyOne+".*") || individualconcept_rsids[ics].matches(".*"+OnlyOne+"\\|.+")) { individualconcept_rsids[ics]=OnlyOne; } } } if(rsids.equals("")) { rsids=individualconcept_rsids[ics]; } else { rsids=rsids+";"+individualconcept_rsids[ics]; } } lstr=pre+rsids; } outputSTR_tmp=outputSTR_tmp+lstr+"\n"; } } else { outputSTR_tmp=outputSTR_tmp+lstr+"\n"; } } else { outputSTR_tmp=outputSTR_tmp+lstr+"\n"; } } outputSTR=outputSTR_tmp; /** * corresponding gene and grouping variants */ for(String x:MentionPatternMap.keySet()) { if(x.matches(pmid+"\t.*")) { String y=pmid+"\t"+MentionPatternMap.get(x); if(!VariantLinking.containsKey(x)) { VariantLinking.put(x,new HashMap<String,String>()); } VariantLinking.get(x).put(y,""); if(!VariantLinking.containsKey(y)) { VariantLinking.put(y,new HashMap<String,String>()); } VariantLinking.get(y).put(x,""); } } for(String x : P2variant.keySet()) { for(String y : P2variant.get(x).keySet()) { for(String z : P2variant.get(x).keySet()) { if(!y.equals(z)) { if(!VariantLinking.containsKey(y)) { VariantLinking.put(y,new HashMap<String,String>()); } VariantLinking.get(y).put(z,""); if(!VariantLinking.containsKey(z)) { VariantLinking.put(z,new HashMap<String,String>()); } VariantLinking.get(z).put(y,""); } } } } /* - remove for(String x : WM2variant.keySet()) { for(String y : WM2variant.get(x).keySet()) { String y_position=WM2variant.get(x).get(y); for(String z : WM2variant.get(x).keySet()) { String z_position=WM2variant.get(x).get(z); if(!y.equals(z)) { if(y_position.equals("") || z_position.equals("")) { if(!VariantLinking.containsKey(y)) { VariantLinking.put(y,new HashMap<String,String>()); } VariantLinking.get(y).put(z,""); if(!VariantLinking.containsKey(z)) { VariantLinking.put(z,new HashMap<String,String>()); } VariantLinking.get(z).put(y,""); } } } } } */ //VariantLinking: link the protein and DNA mutations HashMap<String,Boolean> NoPositionVar = new HashMap<String,Boolean>(); // no position var can only group with one variant for(String tmp1 : VarID2Mention.keySet()) { String pmid_variantid1[]=tmp1.split("\t"); String pmid1=pmid_variantid1[0]; String variantid1=pmid_variantid1[1]; String component1[]=variantid1.split("\\|",-1); if(component1.length>=5) { String W1=component1[2]; String P1=component1[3]; String M1=component1[4]; if(P1.length()<10 && component1[0].equals("p") && component1[1].equals("SUB")) //1st is ProteinMutation { for(String tmp2 : VarID2Mention.keySet()) { String pmid_variantid2[]=tmp2.split("\t"); String pmid2=pmid_variantid2[0]; String variantid2=pmid_variantid2[1]; String component2[]=variantid2.split("\\|",-1); if(component2.length>=5) { String W2=component2[2]; String P2=component2[3]; String M2=component2[4]; if(pmid1.equals(pmid2)) // the same pmid { if(P2.length()<10 && component2[0].equals("c") && component2[1].equals("SUB"))//2nd is DNAMutation { if(tmVar.nu2aa_hash.containsKey(W1+"\t"+M1+"\t"+W2+"\t"+M2)) // nu2aa_hash { if(P1.equals("") && (!P2.equals("")) && NoPositionVar.containsKey(tmp1)) { if(!VariantLinking.containsKey(tmp1)) { VariantLinking.put(tmp1,new HashMap<String,String>()); VariantLinking.get(tmp1).put(tmp2,""); // if the G>G was linked with others, don't link it. if(!VariantLinking.containsKey(tmp2)) { VariantLinking.put(tmp2,new HashMap<String,String>()); } VariantLinking.get(tmp2).put(tmp1,""); // if the G>G was linked with others, don't link it. NoPositionVar.put(P1,true); } } else if(P2.equals("") && (!P1.equals("")) && NoPositionVar.containsKey(tmp2)) { if(!VariantLinking.containsKey(tmp2)) { VariantLinking.put(tmp2,new HashMap<String,String>()); VariantLinking.get(tmp2).put(tmp1,""); // if the G>G was linked with others, don't link it. if(!VariantLinking.containsKey(tmp1)) { VariantLinking.put(tmp1,new HashMap<String,String>()); } VariantLinking.get(tmp1).put(tmp2,""); // if the G>G was linked with others, don't link it. NoPositionVar.put(P1,true); } } else { if(P1.matches("^[0-9]+$") && P2.matches("^[0-9]+$")) { if((Integer.parseInt(P1)-1)*3<Integer.parseInt(P2) && Integer.parseInt(P1)*3>Integer.parseInt(P2)) { if(!VariantLinking.containsKey(tmp1)) { VariantLinking.put(tmp1,new HashMap<String,String>()); } VariantLinking.get(tmp1).put(tmp2,""); if(!VariantLinking.containsKey(tmp2)) { VariantLinking.put(tmp2,new HashMap<String,String>()); } VariantLinking.get(tmp2).put(tmp1,""); } } } } } } } } } } } //implicit relation to direct relation for(String x:VariantLinking.keySet()) { if(!x.matches(".*\\|\\|.*")) { for(String y:VariantLinking.get(x).keySet()) { for(String z:VariantLinking.get(x).keySet()) { if((!y.matches(".*\\|\\|.*")) || (!z.matches(".*\\|\\|.*"))) { if(!y.equals(z)) { if(!VariantLinking.containsKey(y)) { VariantLinking.put(y,new HashMap<String,String>()); } VariantLinking.get(y).put(z,""); if(!VariantLinking.containsKey(z)) { VariantLinking.put(z,new HashMap<String,String>()); } VariantLinking.get(z).put(y,""); } } } } } } /* * to group#: * * 17003357 c|SUB|C|1858|T -> 0 17003357 c|Allele|T|1858 -> 0 */ int group_id=0; HashMap<String,Integer> VariantGroup = new HashMap<String,Integer>(); for(String x:VariantLinking.keySet()) { boolean found=false; for(String y:VariantLinking.get(x).keySet()) { if(VariantGroup.containsKey(y)) { found=true; VariantGroup.put(x,VariantGroup.get(y)); } } if(found==false) { VariantGroup.put(x,group_id); group_id++; } } for(String VarID : VarID2Mention.keySet()) { if (!VariantGroup.containsKey(VarID)) { VariantGroup.put(VarID,group_id); group_id++; } } //for(String tmpx : VariantGroup.keySet()) //{ // System.out.println(tmpx+"\t"+VariantGroup.get(tmpx)); //} /* * group# 2 RS#: * * 0 -> 2476601 */ HashMap<String,Integer> RS2VariantGroup = new HashMap<String,Integer>(); // VariantGroup to RS# HashMap<Integer,String> VariantGroup2RS = new HashMap<Integer,String>(); // VariantGroup to RS# for(String s:MentionPatternMap2rs.keySet()) //s : <pmid,variant> { if(VariantGroup.containsKey(s)) { int gid=VariantGroup.get(s); VariantGroup2RS.put(gid,MentionPatternMap2rs.get(s)); RS2VariantGroup.put("rs"+MentionPatternMap2rs.get(s),gid); } } for(String s:MentionPatternMap2rs_extend.keySet()) { if(VariantGroup.containsKey(s)) { int gid=VariantGroup.get(s); VariantGroup2RS.put(gid,MentionPatternMap2rs_extend.get(s)); RS2VariantGroup.put("rs"+MentionPatternMap2rs_extend.get(s),gid); } } /* * VariantGroup to GeneID */ HashMap<Integer,HashMap<String,String>> sentencelocation_gene2_hash= new HashMap<Integer,HashMap<String,String>>(); // sentence--> gene start --> geneid ArrayList<Integer> SentenceOffsets = PMID2SentenceOffsets.get(pmid); //Gene in sentence for(String annotation_gene:annotations_gene.keySet()) { String annotation_gene_column[]=annotation_gene.split("\t"); if(pmid.equals(annotation_gene_column[0])) { int gene_start=Integer.parseInt(annotation_gene_column[1]); int gene_last=Integer.parseInt(annotation_gene_column[2]); String gene_id=annotation_gene_column[4]; for(int si=0;si<SentenceOffsets.size();si++) // find sentence location for gene mention { if(gene_start<SentenceOffsets.get(si)) //gene_anno[1] = start { if(!sentencelocation_gene2_hash.containsKey(si-1)) { sentencelocation_gene2_hash.put(si-1,new HashMap<String,String>()); } sentencelocation_gene2_hash.get(si-1).put(gene_start+"\t"+gene_last,gene_id); break; } } } } HashMap<Integer,String> gid2gene_hash= new HashMap<Integer,String>(); for(int gid=0;gid<group_id;gid++) //group to variant ids { int min_distance=100000000; String gene_with_min_distance=""; for(String Variant:VariantGroup.keySet()) { if(VariantGroup.get(Variant)==gid && VarID2Mention.containsKey(Variant)) //Variants in group { HashMap<Integer,Integer> Mentions = VarID2Mention.get(Variant);//variant id to mentions for(int mutation_start : Mentions.keySet()) { int mutation_last=Mentions.get(mutation_start); int sentencelocation_var=0; boolean found=false; for(int si=0;si<SentenceOffsets.size();si++) // find sentence location for variant mention { if(mutation_start<SentenceOffsets.get(si)) { sentencelocation_var=si-1; found=true; break; } } if(found==false) // in the last sentence { sentencelocation_var=SentenceOffsets.size(); } HashMap<String,String> genes_in_targetvariant_sentence=new HashMap<String,String>(); if(sentencelocation_gene2_hash.containsKey(sentencelocation_var)) { genes_in_targetvariant_sentence=sentencelocation_gene2_hash.get(sentencelocation_var); //System.out.println(gid+"\t"+Variant+"\t"+mutation_start+"\t"+sentencelocation_var+"\t"+genes_in_targetvariant_sentence+"\t"+min_distance+"\t"+gene_with_min_distance); for(String gene_start_last : genes_in_targetvariant_sentence.keySet()) { String gene_start_last_column[]=gene_start_last.split("\t"); int gene_start=Integer.parseInt(gene_start_last_column[0]); int gene_last=Integer.parseInt(gene_start_last_column[1]); String gene_id=genes_in_targetvariant_sentence.get(gene_start_last); if(mutation_last<gene_start) // mutation --- gene { if(min_distance>gene_start-mutation_last) { min_distance=gene_start-mutation_last; gene_with_min_distance=gene_id; } } else if(gene_last<mutation_start) //gene --- mutation { if(min_distance>mutation_start-gene_last) { min_distance=mutation_start-gene_last; gene_with_min_distance=gene_id; } } } //System.out.println(gid+"\t"+Variant+"\t"+mutation_start+"\t"+sentencelocation_var+"\t"+genes_in_targetvariant_sentence+"\t"+min_distance+"\t"+gene_with_min_distance+"\n"); } else if(sentencelocation_var>=1 && sentencelocation_gene2_hash.containsKey(sentencelocation_var-1)) // the gene in previous sentence { genes_in_targetvariant_sentence=sentencelocation_gene2_hash.get(sentencelocation_var-1); //System.out.println(gid+"\t"+Variant+"\t"+mutation_start+"\t"+sentencelocation_var+"\t"+genes_in_targetvariant_sentence+"\t-1\t"+min_distance+"\t"+gene_with_min_distance); for(String gene_start_last : genes_in_targetvariant_sentence.keySet()) { String gene_start_last_column[]=gene_start_last.split("\t"); int gene_last=Integer.parseInt(gene_start_last_column[1]); String gene_id=genes_in_targetvariant_sentence.get(gene_start_last); if(min_distance>mutation_start-gene_last+1000) { min_distance=mutation_start-gene_last+1000; gene_with_min_distance=gene_id; } } //System.out.println(gid+"\t"+Variant+"\t"+mutation_start+"\t"+sentencelocation_var+"\t"+genes_in_targetvariant_sentence+"\t-1\t"+min_distance+"\t"+gene_with_min_distance+"\n"); } else if(sentencelocation_var<SentenceOffsets.size()-1 && sentencelocation_gene2_hash.containsKey(sentencelocation_var+1)) // the gene in next sentence { genes_in_targetvariant_sentence=sentencelocation_gene2_hash.get(sentencelocation_var+1); //System.out.println(gid+"\t"+Variant+"\t"+mutation_start+"\t"+sentencelocation_var+"\t"+genes_in_targetvariant_sentence+"\t-1\t"+min_distance+"\t"+gene_with_min_distance); for(String gene_start_last : genes_in_targetvariant_sentence.keySet()) { String gene_start_last_column[]=gene_start_last.split("\t"); int gene_start=Integer.parseInt(gene_start_last_column[0]); String gene_id=genes_in_targetvariant_sentence.get(gene_start_last); if(min_distance>gene_start-mutation_last+2000) { min_distance=gene_start-mutation_last+2000; gene_with_min_distance=gene_id; } } //System.out.println(gid+"\t"+Variant+"\t"+mutation_start+"\t"+sentencelocation_var+"\t"+genes_in_targetvariant_sentence+"\t-1\t"+min_distance+"\t"+gene_with_min_distance+"\n"); } else if(sentencelocation_gene2_hash.containsKey(0))// the gene in title sentence { genes_in_targetvariant_sentence=sentencelocation_gene2_hash.get(0); //System.out.println(gid+"\t"+Variant+"\t"+mutation_start+"\t"+sentencelocation_var+"\t"+genes_in_targetvariant_sentence+"\t"+min_distance+"\t"+gene_with_min_distance); for(String gene_start_last : genes_in_targetvariant_sentence.keySet()) { String gene_start_last_column[]=gene_start_last.split("\t"); int gene_last=Integer.parseInt(gene_start_last_column[1]); String gene_id=genes_in_targetvariant_sentence.get(gene_start_last); if(min_distance>mutation_start-gene_last+3000) { min_distance=mutation_start-gene_last+3000; gene_with_min_distance=gene_id; } } //System.out.println(gid+"\t"+Variant+"\t"+mutation_start+"\t"+sentencelocation_var+"\t"+genes_in_targetvariant_sentence+"\t"+min_distance+"\t"+gene_with_min_distance+"\n"); } else { for(int x=sentencelocation_var-1;x>=0;x--) // reach the previous sentence until find genes { if(sentencelocation_gene2_hash.containsKey(x)) { genes_in_targetvariant_sentence=sentencelocation_gene2_hash.get(x); boolean gene_found=false; for(String gene_start_last : genes_in_targetvariant_sentence.keySet()) { String gene_start_last_column[]=gene_start_last.split("\t"); int gene_last=Integer.parseInt(gene_start_last_column[1]); String gene_id=genes_in_targetvariant_sentence.get(gene_start_last); if(min_distance>mutation_start-gene_last+4000) { min_distance=mutation_start-gene_last+4000; gene_with_min_distance=gene_id; } gene_found=true; } if(gene_found == true) { break; } } } } } } } if(!gene_with_min_distance.equals("")) { gid2gene_hash.put(gid,gene_with_min_distance); } } /* * Extending the RS# to other group members */ outputSTR_tmp=""; outputSTR_line=outputSTR.split("\n"); for(int l=0;l<outputSTR_line.length;l++) { String lstr=outputSTR_line[l]; String lstr_column[]=lstr.split("\t"); if(lstr_column.length>=5) { if(lstr_column[1].matches("[0-9]+") && lstr_column[2].matches("[0-9]+")) // in case the text contains "\t" { int mutation_start=Integer.parseInt(lstr_column[1]); int mutation_last=Integer.parseInt(lstr_column[2]); String mention=lstr_column[3]; String type=lstr_column[4]; String IDcolumn=lstr_column[5]; pat = Pattern.compile("^(.+);CorrespondingGene:([0-9null]+);(|SameGroup-|GeneNormalized-|Pattern-|Extended-|Recognized-|Mapping-|SNPinText-|Foundbefore-|RefSeq-)RS#:(.+)$"); mat = pat.matcher(IDcolumn); String RSID=""; String geneid=""; String CorrespondingGene=""; String RSID_extract_type=""; if(mat.find()) { IDcolumn = mat.group(1); geneid = mat.group(2); RSID_extract_type = mat.group(3); RSID = mat.group(4); } String RSID_for_gene=RSID.replaceAll("\\(.*\\)$",""); if(VariantGroup.containsKey(pmid+"\t"+IDcolumn)) { int GroupID=VariantGroup.get(pmid+"\t"+IDcolumn); if(VariantGroup2RS.containsKey(GroupID)) { if(VariantGroup2RS.get(GroupID).equals(RSID)) { if(RSID_extract_type.equals("")){RSID_extract_type="SameGroup-";} } else if(RSID.equals("")) { RSID=VariantGroup2RS.get(GroupID); if(RSID_extract_type.equals("")){RSID_extract_type="SameGroup-";} } else { VariantGroup.put(pmid+"\t"+IDcolumn,group_id); VariantGroup2RS.put(group_id,RSID); group_id++; } } else if(gid2gene_hash.containsKey(GroupID)) { CorrespondingGene=gid2gene_hash.get(GroupID); } } else { int sentencelocation_var=0; boolean found=false; for(int si=0;si<SentenceOffsets.size();si++) // find sentence location for variant mention { if(mutation_start<SentenceOffsets.get(si)) { sentencelocation_var=si-1; found=true; break; } } if(found==false) // in the last sentence { sentencelocation_var=SentenceOffsets.size(); } int min_distance=100000000; String gene_with_min_distance=""; HashMap<String,String> genes_in_targetvariant_sentence=new HashMap<String,String>(); if(sentencelocation_gene2_hash.containsKey(sentencelocation_var)) { genes_in_targetvariant_sentence=sentencelocation_gene2_hash.get(sentencelocation_var); //System.out.println(mention+"\t"+IDcolumn+"\t"+mutation_start+"\t"+sentencelocation_var+"\t"+genes_in_targetvariant_sentence+"\t"+min_distance+"\t"+gene_with_min_distance); for(String gene_start_last : genes_in_targetvariant_sentence.keySet()) { String gene_start_last_column[]=gene_start_last.split("\t"); int gene_start=Integer.parseInt(gene_start_last_column[0]); int gene_last=Integer.parseInt(gene_start_last_column[1]); String gene_id=genes_in_targetvariant_sentence.get(gene_start_last); if(mutation_last<gene_start) // mutation --- gene { if(min_distance>gene_start-mutation_last) { min_distance=gene_start-mutation_last; gene_with_min_distance=gene_id; } } else if(gene_last<mutation_start) //gene --- mutation { if(min_distance>mutation_start-gene_last) { min_distance=mutation_start-gene_last; gene_with_min_distance=gene_id; } } } //System.out.println(mention+"\t"+IDcolumn+"\t"+mutation_start+"\t"+sentencelocation_var+"\t"+genes_in_targetvariant_sentence+"\t"+min_distance+"\t"+gene_with_min_distance+"\n"); } else if(sentencelocation_var>=1 && sentencelocation_gene2_hash.containsKey(sentencelocation_var-1)) // the gene in previous sentence { genes_in_targetvariant_sentence=sentencelocation_gene2_hash.get(sentencelocation_var-1); //System.out.println(mention+"\t"+IDcolumn+"\t"+mutation_start+"\t"+sentencelocation_var+"\t"+genes_in_targetvariant_sentence+"\t-1\t"+min_distance+"\t"+gene_with_min_distance); for(String gene_start_last : genes_in_targetvariant_sentence.keySet()) { String gene_start_last_column[]=gene_start_last.split("\t"); int gene_last=Integer.parseInt(gene_start_last_column[1]); String gene_id=genes_in_targetvariant_sentence.get(gene_start_last); if(min_distance>mutation_start-gene_last+1000) { min_distance=mutation_start-gene_last+1000; gene_with_min_distance=gene_id; } } //System.out.println(mention+"\t"+IDcolumn+"\t"+mutation_start+"\t"+sentencelocation_var+"\t"+genes_in_targetvariant_sentence+"\t-1\t"+min_distance+"\t"+gene_with_min_distance+"\n"); } else if(sentencelocation_var<SentenceOffsets.size()-1 && sentencelocation_gene2_hash.containsKey(sentencelocation_var+1)) // the gene in next sentence { genes_in_targetvariant_sentence=sentencelocation_gene2_hash.get(sentencelocation_var+1); //System.out.println(mention+"\t"+IDcolumn+"\t"+mutation_start+"\t"+sentencelocation_var+"\t"+genes_in_targetvariant_sentence+"\t-1\t"+min_distance+"\t"+gene_with_min_distance); for(String gene_start_last : genes_in_targetvariant_sentence.keySet()) { String gene_start_last_column[]=gene_start_last.split("\t"); int gene_start=Integer.parseInt(gene_start_last_column[0]); String gene_id=genes_in_targetvariant_sentence.get(gene_start_last); if(min_distance>gene_start-mutation_last+2000) { min_distance=gene_start-mutation_last+2000; gene_with_min_distance=gene_id; } } //System.out.println(mention+"\t"+IDcolumn+"\t"+mutation_start+"\t"+sentencelocation_var+"\t"+genes_in_targetvariant_sentence+"\t-1\t"+min_distance+"\t"+gene_with_min_distance+"\n"); } else if(sentencelocation_gene2_hash.containsKey(0))// the gene in title sentence { genes_in_targetvariant_sentence=sentencelocation_gene2_hash.get(0); //System.out.println(mention+"\t"+IDcolumn+"\t"+mutation_start+"\t"+sentencelocation_var+"\t"+genes_in_targetvariant_sentence+"\t"+min_distance+"\t"+gene_with_min_distance); for(String gene_start_last : genes_in_targetvariant_sentence.keySet()) { String gene_start_last_column[]=gene_start_last.split("\t"); int gene_last=Integer.parseInt(gene_start_last_column[1]); String gene_id=genes_in_targetvariant_sentence.get(gene_start_last); if(min_distance>mutation_start-gene_last+10000) { min_distance=mutation_start-gene_last+10000; gene_with_min_distance=gene_id; } } //System.out.println(mention+"\t"+IDcolumn+"\t"+mutation_start+"\t"+sentencelocation_var+"\t"+genes_in_targetvariant_sentence+"\t"+min_distance+"\t"+gene_with_min_distance+"\n"); } CorrespondingGene=gene_with_min_distance; } if(CorrespondingGene.equals("")) { int count=0; int max=0; String gene_max=""; for(String SingleG : SingleGene.get(pmid).keySet()) { count++; if(SingleGene.get(pmid).get(SingleG)>max) { max=SingleGene.get(pmid).get(SingleG); gene_max=SingleG; } } if(count==1 && max>=3) { CorrespondingGene=gene_max; } } String VariantGroupNum=""; HashMap<String,String> VariantGroupNum2geneid_hash=new HashMap<String,String>(); if(VariantGroup.containsKey(pmid+"\t"+IDcolumn)) { VariantGroupNum=Integer.toString(VariantGroup.get(pmid+"\t"+IDcolumn)); } else if(RS2VariantGroup.containsKey(IDcolumn)) { VariantGroupNum=Integer.toString(RS2VariantGroup.get(IDcolumn)); } else { if(type.equals("Chromosome") || type.equals("RefSeq")) {} else { VariantGroup.put(pmid+"\t"+IDcolumn,group_id); VariantGroupNum=Integer.toString(group_id); group_id++; } } Pattern RegEx_RSnum = Pattern.compile("rs([0-9]+)"); Matcher mp_RSnum = RegEx_RSnum.matcher(IDcolumn); if (mp_RSnum.find()) { RSID = mp_RSnum.group(1); } if (HideMultipleResult.equals("True")) //chose the most popular RSID { RSID=PrioritizeRS_by_RS2Frequency(RSID); } /*HGVS format*/ String ID_HGVS=""; String component[]=IDcolumn.split("\\|",-1); String RSID_tmp=RSID.replaceAll("\\((Expired|Merged)\\)",""); if(component.length>3 && tmVar.RSandPosition2Seq_hash.containsKey(RSID_tmp+"\t"+component[3])) { IDcolumn=IDcolumn.replaceAll("^[a-z]\\|",tmVar.RSandPosition2Seq_hash.get(RSID_tmp+"\t"+component[3])+"|"); component=IDcolumn.split("\\|",-1); if(tmVar.RSandPosition2Seq_hash.get(RSID_tmp+"\t"+component[3]).equals("p")) { type="ProteinMutation"; } else { type="DNAMutation"; } } if(component[0].equals("p")) { if(component[1].equals("SUB") && component.length>=5) { ID_HGVS=component[0]+"."+component[2]+component[3]+component[4]; } else if(component[1].equals("INS") && component.length>=4) //"c.104insT" --> "c|INS|104|T" { ID_HGVS=component[0]+"."+component[2]+"ins"+component[3]; } else if(component[1].equals("DEL") && component.length>=4) //"c.104delT" --> "c|DEL|104|T" { ID_HGVS=component[0]+"."+component[2]+"del"+component[3]; } else if(component[1].equals("INDEL") && component.length>=4) //"c.2153_2155delinsTCCTGGTTTA" --> "c|INDEL|2153_2155|TCCTGGTTTA" { ID_HGVS=component[0]+"."+component[2]+"delins"+component[3]; } else if(component[1].equals("DUP") && component.length>=4) //"c.1285-1301dup" --> "c|DUP|1285_1301||" { ID_HGVS=component[0]+"."+component[2]+"dup"+component[3]; } else if(component[1].equals("FS") && component.length>=6) //"p.Val35AlafsX25" --> "p|FS|V|35|A|25" { ID_HGVS=component[0]+"."+component[2]+component[3]+component[4]+"fsX"+component[5]; } } else if(component[0].equals("c") || component[0].equals("g")) { if(component[1].equals("SUB") && component.length>=5) { ID_HGVS=component[0]+"."+component[3]+component[2]+">"+component[4]; } else if(component[1].equals("INS") && component.length>=4) { ID_HGVS=component[0]+"."+component[2]+"ins"+component[3]; } else if(component[1].equals("DEL") && component.length>=4) { ID_HGVS=component[0]+"."+component[2]+"del"+component[3]; } else if(component[1].equals("INDEL") && component.length>=4) { ID_HGVS=component[0]+"."+component[2]+"delins"+component[3]; } else if(component[1].equals("DUP") && component.length>=4) { ID_HGVS=component[0]+"."+component[2]+"dup"+component[3]; } else if(component[1].equals("FS") && component.length>=6) { ID_HGVS=component[0]+"."+component[2]+component[3]+component[4]+"fsX"+component[5]; } } else if(component[0].equals("")) { if(component[1].equals("SUB") && component.length>=5) { ID_HGVS="c."+component[3]+component[2]+">"+component[4]; } else if(component[1].equals("INS") && component.length>=4) { ID_HGVS="c."+component[2]+"ins"+component[3]; } else if(component[1].equals("DEL") && component.length>=4) { ID_HGVS="c."+component[2]+"del"+component[3]; } else if(component[1].equals("INDEL") && component.length>=4) { ID_HGVS="c."+component[2]+"delins"+component[3]; } else if(component[1].equals("DUP") && component.length>=4) { ID_HGVS="c."+component[2]+"dup"+component[3]; } else if(component[1].equals("FS") && component.length>=6) { ID_HGVS="p."+component[2]+component[3]+component[4]+"fsX"+component[5]; } } if(ID_HGVS.equals("")){} else if (type.equals("DNAAcidChange")){ID_HGVS="";} else if (type.equals("ProteinAcidChange")){ID_HGVS="";} else { ID_HGVS=";HGVS:"+ID_HGVS; } if(type.equals("DNAMutation")) { if(IDcolumn.matches("\\|Allele\\|")) { type="DNAAllele"; } } else if(type.equals("ProteinMutation")) { if(IDcolumn.matches("\\|Allele\\|")) { type="ProteinAllele"; } } if(!RSID.equals("")) // add RSID { if(rs2gene.containsKey(pmid+"\t"+RSID_for_gene)) { outputSTR_tmp=outputSTR_tmp+pmid+"\t"+mutation_start+"\t"+mutation_last+"\t"+mention+"\t"+type+"\ttmVar:"+IDcolumn+ID_HGVS+";VariantGroup:"+VariantGroupNum+";CorrespondingGene:"+rs2gene.get(pmid+"\t"+RSID_for_gene)+";"+RSID_extract_type+"RS#:"+RSID+"\n"; VariantGroupNum2geneid_hash.put(VariantGroupNum,rs2gene.get(pmid+"\t"+RSID_for_gene)); } else if(rs2gene.containsKey(pmid+"\t"+RSID)) { outputSTR_tmp=outputSTR_tmp+pmid+"\t"+mutation_start+"\t"+mutation_last+"\t"+mention+"\t"+type+"\ttmVar:"+IDcolumn+ID_HGVS+";VariantGroup:"+VariantGroupNum+";CorrespondingGene:"+rs2gene.get(pmid+"\t"+RSID)+";"+RSID_extract_type+"RS#:"+RSID+"\n"; VariantGroupNum2geneid_hash.put(VariantGroupNum,rs2gene.get(pmid+"\t"+RSID)); } else { ResultSet gene = stmt_rs2gene.executeQuery("SELECT gene FROM rs2gene WHERE rs='"+RSID+"'order by gene asc limit 1"); while ( gene.next() ) { String gene_id = gene.getString("gene"); rs2gene.put(pmid+"\t"+RSID,gene_id); } outputSTR_tmp=outputSTR_tmp+pmid+"\t"+mutation_start+"\t"+mutation_last+"\t"+mention+"\t"+type+"\ttmVar:"+IDcolumn+ID_HGVS+";VariantGroup:"+VariantGroupNum+";CorrespondingGene:"+rs2gene.get(pmid+"\t"+RSID)+";"+RSID_extract_type+"RS#:"+RSID+"\n"; VariantGroupNum2geneid_hash.put(VariantGroupNum,geneid); } } else if(!CorrespondingGene.equals("") && !CorrespondingGene.equals("null") && !type.matches("(Chromosome|RefSeq|GenomicRegion|CopyNumberVariant)")) // add Gene { outputSTR_tmp=outputSTR_tmp+pmid+"\t"+mutation_start+"\t"+mutation_last+"\t"+mention+"\t"+type+"\ttmVar:"+IDcolumn+ID_HGVS+";VariantGroup:"+VariantGroupNum+";CorrespondingGene:"+CorrespondingGene+"\n"; VariantGroupNum2geneid_hash.put(VariantGroupNum,CorrespondingGene); } else { if(type.equals("Chromosome")) { if(DisplayChromosome.equals("True")) { outputSTR_tmp=outputSTR_tmp+pmid+"\t"+mutation_start+"\t"+mutation_last+"\t"+mention+"\t"+type+"\t"+IDcolumn+"\n"; } } else if(type.equals("RefSeq")) { if(DisplayRefSeq.equals("True")) { outputSTR_tmp=outputSTR_tmp+pmid+"\t"+mutation_start+"\t"+mutation_last+"\t"+mention+"\t"+type+"\t"+IDcolumn+"\n"; } } else if(type.equals("GenomicRegion")) { if(DisplayGenomicRegion.equals("True")) { outputSTR_tmp=outputSTR_tmp+pmid+"\t"+mutation_start+"\t"+mutation_last+"\t"+mention+"\t"+type+"\t"+IDcolumn+"\n"; } } else if(type.equals("CopyNumberVariant")) { outputSTR_tmp=outputSTR_tmp+pmid+"\t"+mutation_start+"\t"+mutation_last+"\t"+mention+"\t"+type+"\t"+IDcolumn+"\n"; } else if(CorrespondingGene.equals("null") || CorrespondingGene.equals("")) { outputSTR_tmp=outputSTR_tmp+pmid+"\t"+mutation_start+"\t"+mutation_last+"\t"+mention+"\t"+type+"\ttmVar:"+IDcolumn+ID_HGVS+";VariantGroup:"+VariantGroupNum+"\n"; } else { outputSTR_tmp=outputSTR_tmp+pmid+"\t"+mutation_start+"\t"+mutation_last+"\t"+mention+"\t"+type+"\ttmVar:"+IDcolumn+ID_HGVS+";VariantGroup:"+VariantGroupNum+";CorrespondingGene:"+CorrespondingGene+"\n"; } } } else { outputSTR_tmp=outputSTR_tmp+lstr+"\n"; } } else { outputSTR_tmp=outputSTR_tmp+lstr+"\n"; } } outputSTR=outputSTR_tmp; /** * refine corresponding gene & human gene & species & cA# */ outputSTR_tmp=""; outputSTR_line=outputSTR.split("\n"); for(int l=0;l<outputSTR_line.length;l++) { String lstr=outputSTR_line[l]; String lstr_column[]=lstr.split("\t"); if(lstr_column.length>=5) { if(lstr_column[1].matches("[0-9]+") && lstr_column[2].matches("[0-9]+")) // in case the text contains "\t" { String IDcolumn=lstr_column[5]; String RSID=""; String gene_id=""; String tax_id=""; String tmVarForm=""; pat = Pattern.compile("^(.*)tmVar:(.+?);.*CorrespondingGene:([0-9null]+);(|SameGroup-|GeneNormalized-|Pattern-|Extended-|Recognized-|Mapping-|SNPinText-|Foundbefore-|RefSeq-)RS#:([0-9]+).*$"); mat = pat.matcher(IDcolumn); Pattern pat2 = Pattern.compile("^(.*)CorrespondingGene:([0-9null]+)(.*)$"); Matcher mat2 = pat2.matcher(IDcolumn); if(mat.find()) { tmVarForm = mat.group(2); gene_id = mat.group(3); RSID = mat.group(5); if(tmVar.Gene2HumanGene_hash.containsKey(gene_id)) //translate to human gene by homologene { lstr=lstr.replaceAll("CorrespondingGene:"+gene_id,"OriginalGene:"+gene_id+";CorrespondingGene:"+tmVar.Gene2HumanGene_hash.get(gene_id)); } else // translate to human gene by NCBI ortholog { ResultSet humangene = stmt_gene2humangene.executeQuery("SELECT humangene FROM gene2humangene WHERE gene='"+gene_id+"'"); if ( humangene.next() ) { String humangene_id = humangene.getString("humangene"); lstr=lstr.replaceAll("CorrespondingGene:"+gene_id,"OriginalGene:"+gene_id+";CorrespondingGene:"+humangene_id); } } } else if(mat2.find()) { gene_id = mat2.group(2); if(tmVar.Gene2HumanGene_hash.containsKey(gene_id)) //translate to human gene { lstr=lstr.replaceAll("CorrespondingGene:"+gene_id,"OriginalGene:"+gene_id+";CorrespondingGene:"+tmVar.Gene2HumanGene_hash.get(gene_id)); } else { ResultSet humangene = stmt_gene2humangene.executeQuery("SELECT humangene FROM gene2humangene WHERE gene='"+gene_id+"'"); if ( humangene.next() ) { String humangene_id = humangene.getString("humangene"); lstr=lstr.replaceAll("CorrespondingGene:"+gene_id,"OriginalGene:"+gene_id+";CorrespondingGene:"+humangene_id); } } } ResultSet tax = stmt_gene2tax.executeQuery("SELECT tax FROM gene2tax WHERE gene='"+gene_id+"'"); if ( tax.next() ) { tax_id = tax.getString("tax"); } HashMap<String,String> ATCG_MAP=new HashMap<String,String>(); ATCG_MAP.put("A", "T"); ATCG_MAP.put("C", "G"); ATCG_MAP.put("T", "A"); ATCG_MAP.put("G", "C"); String CAID=""; String num_rs=""; c = DriverManager.getConnection("jdbc:sqlite:Database/RS2CA_tmVarForm.db"); stmt = c.createStatement(); ResultSet count_rs = stmt.executeQuery("SELECT count(CA) as num_rs FROM RS2CA_tmVarForm WHERE RS='"+RSID+"'"); count_rs.next(); num_rs = count_rs.getString("num_rs"); ResultSet rs = stmt.executeQuery("SELECT CA,DNAVariant,ProteinVariant FROM RS2CA_tmVarForm WHERE RS='"+RSID+"'"); while ( rs.next() ) { String CA = rs.getString("CA"); String DNAVariant = rs.getString("DNAVariant"); String ProteinVariant = rs.getString("ProteinVariant"); if(DNAVariant.equals(tmVarForm)) // DNA Variant exact match { CAID=CA; break; } else if(ProteinVariant.equals(tmVarForm)) // Protein Variant exact match { CAID=CA; break; } else { String IDcolumn_column[]=tmVarForm.split("\\|",-1); String DV_column[]=DNAVariant.split("\\|",-1); String PV_column[]=ProteinVariant.split("\\|",-1); if(IDcolumn_column.length>4 && DV_column.length>4 && IDcolumn_column[2].equals(DV_column[2]) && IDcolumn_column[4].equals(DV_column[4])) // DNA Variant W+M match { CAID=CA; break; } else if(IDcolumn_column.length>4 && DV_column.length>4 && IDcolumn_column[2].equals(ATCG_MAP.get(DV_column[2])) && IDcolumn_column[4].equals(ATCG_MAP.get(DV_column[4]))) // DNA Variant W+M match { CAID=CA; break; } else if(IDcolumn_column.length>4 && DV_column.length>4 && IDcolumn_column[2].equals(DV_column[4]) && IDcolumn_column[4].equals(DV_column[2])) // DNA Variant W+M match { CAID=CA; break; } else if(IDcolumn_column.length>4 && DV_column.length>4 && IDcolumn_column[2].equals(ATCG_MAP.get(DV_column[4])) && IDcolumn_column[4].equals(ATCG_MAP.get(DV_column[2]))) // DNA Variant W+M match { CAID=CA; break; } else if(IDcolumn_column.length>4 && PV_column.length>4 && IDcolumn_column[2].equals(PV_column[2]) && IDcolumn_column[4].equals(PV_column[4])) // Protein Variant W+M match { CAID=CA; break; } else if(IDcolumn_column.length>4 && PV_column.length>4 && IDcolumn_column[2].equals(PV_column[4]) && IDcolumn_column[4].equals(PV_column[2])) // Protein Variant W+M match { CAID=CA; break; } else if(IDcolumn_column.length>3 && PV_column.length>3 && IDcolumn_column[1].matches("(DEL|INS|INDEL)") && IDcolumn_column[3].equals(PV_column[3])) // DEL/INS Variant W match { CAID=CA; break; } } } if (!tax_id.equals("")) { lstr=lstr+";CorrespondingSpecies:"+tax_id; } if (CAID.equals("")) { outputSTR_tmp=outputSTR_tmp+lstr+"\n"; } else { outputSTR_tmp=outputSTR_tmp+lstr+";CA#:"+CAID+"\n"; } } else { outputSTR_tmp=outputSTR_tmp+lstr+"\n"; } } else { outputSTR_tmp=outputSTR_tmp+lstr+"\n"; } } outputSTR=outputSTR_tmp; // hide the types of the normalization methods if(DisplayRSnumOnly.equals("True")) { outputSTR=outputSTR.replaceAll(";(|SameGroup-|GeneNormalized-|Pattern-|Extended-|Recognized-|Mapping-|SNPinText-|Foundbefore-|RefSeq-)RS#:", ";RS#:"); } outputSTR=outputSTR.replaceAll(";RS#:[0-9\\|]+(.*RS#:[0-9\\|]+)","$1"); outputSTR=outputSTR.replaceAll("(;CorrespondingGene:[0-9]+.*);CorrespondingGene:[0-9]+","$1"); outputSTR=outputSTR.replaceAll("CorrespondingGene:null",""); outputSTR=outputSTR.replaceAll(";;RS#:",";RS#:"); outputfile.write(outputSTR+"\n"); outputSTR=""; tiabs=""; VariantLinking=new HashMap<String,HashMap<String,String>>(); VariantGroup=new HashMap<String,Integer>(); MentionPatternMap=new HashMap<String,String>(); P2variant=new HashMap<String,HashMap<String,String>>(); WM2variant=new HashMap<String,HashMap<String,String>>(); } else { outputSTR=outputSTR+line+"\n"; } } inputfile.close(); outputfile.close(); } catch(IOException e1){ System.out.println("[normalization]: "+e1+" Input file is not exist.");} } /* RS#:121913377|113488022 -> RS#:113488022 */ public String PrioritizeRS_by_RS2Frequency(String RSID)throws IOException { String RSIDs[]=RSID.split("\\|"); int max_freq=0; String RSID_with_max_freq=""; for(int i=0;i<RSIDs.length;i++) { if(i==0) { RSID_with_max_freq=RSIDs[i]; if( tmVar.RS2Frequency_hash.containsKey(RSIDs[i])) { max_freq=tmVar.RS2Frequency_hash.get(RSIDs[i]); } } else if(tmVar.RS2Frequency_hash.containsKey(RSIDs[i]) && tmVar.RS2Frequency_hash.get(RSIDs[i])>max_freq) { max_freq=tmVar.RS2Frequency_hash.get(RSIDs[i]); RSID_with_max_freq=RSIDs[i]; } } return RSID_with_max_freq; } }
249,586
42.218528
733
java
null
tmVar3-main/src/tmVarlib/PrefixTree.java
/** * Project: * Function: Dictionary lookup by Prefix Tree */ package tmVarlib; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.*; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; public class PrefixTree { private Tree Tr=new Tree(); /** * Hash2Tree(HashMap<String, String> ID2Names) * Dictionary2Tree_Combine(String Filename,String StopWords,String MentionType) * Dictionary2Tree_UniqueGene(String Filename,String StopWords) //olr1831ps 10116:*405718 * TreeFile2Tree(String Filename) * */ public static HashMap<String, String> StopWord_hash = new HashMap<String, String>(); public void Hash2Tree(HashMap<String, String> ID2Names) { for(String ID : ID2Names.keySet()) { Tr.insertMention(ID2Names.get(ID),ID); } } /* * Type Identifier Names * Species 9606 ttdh3pv|igl027/99|igl027/98|sw 1463 */ public void Dictionary2Tree(String Filename,String StopWords) { try { /** Stop Word */ BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(StopWords), "UTF-8")); String line=""; while ((line = br.readLine()) != null) { StopWord_hash.put(line, "StopWord"); } br.close(); BufferedReader inputfile = new BufferedReader(new InputStreamReader(new FileInputStream(Filename), "UTF-8")); line=""; while ((line = inputfile.readLine()) != null) { line = line.replaceAll("ω","w");line = line.replaceAll("μ","u");line = line.replaceAll("κ","k");line = line.replaceAll("α","a");line = line.replaceAll("γ","r");line = line.replaceAll("β","b");line = line.replaceAll("×","x");line = line.replaceAll("¹","1");line = line.replaceAll("²","2");line = line.replaceAll("°","o");line = line.replaceAll("ö","o");line = line.replaceAll("é","e");line = line.replaceAll("à","a");line = line.replaceAll("Á","A");line = line.replaceAll("ε","e");line = line.replaceAll("θ","O");line = line.replaceAll("•",".");line = line.replaceAll("µ","u");line = line.replaceAll("λ","r");line = line.replaceAll("⁺","+");line = line.replaceAll("ν","v");line = line.replaceAll("ï","i");line = line.replaceAll("ã","a");line = line.replaceAll("≡","=");line = line.replaceAll("ó","o");line = line.replaceAll("³","3");line = line.replaceAll("〖","[");line = line.replaceAll("〗","]");line = line.replaceAll("Å","A");line = line.replaceAll("ρ","p");line = line.replaceAll("ü","u");line = line.replaceAll("ɛ","e");line = line.replaceAll("č","c");line = line.replaceAll("š","s");line = line.replaceAll("ß","b");line = line.replaceAll("═","=");line = line.replaceAll("£","L");line = line.replaceAll("Ł","L");line = line.replaceAll("ƒ","f");line = line.replaceAll("ä","a");line = line.replaceAll("–","-");line = line.replaceAll("⁻","-");line = line.replaceAll("〈","<");line = line.replaceAll("〉",">");line = line.replaceAll("χ","X");line = line.replaceAll("Đ","D");line = line.replaceAll("‰","%");line = line.replaceAll("·",".");line = line.replaceAll("→",">");line = line.replaceAll("←","<");line = line.replaceAll("ζ","z");line = line.replaceAll("π","p");line = line.replaceAll("τ","t");line = line.replaceAll("ξ","X");line = line.replaceAll("η","h");line = line.replaceAll("ø","0");line = line.replaceAll("Δ","D");line = line.replaceAll("∆","D");line = line.replaceAll("∑","S");line = line.replaceAll("Ω","O");line = line.replaceAll("δ","d");line = line.replaceAll("σ","s"); String Column[]=line.split("\t",-1); if(Column.length>2) { String ConceptType=Column[0]; String ConceptID=Column[1]; String ConceptNames=Column[2]; /* * Specific usage for Species */ if( ConceptType.equals("Species")) { ConceptID=ConceptID.replace("species:ncbi:",""); ConceptNames=ConceptNames.replaceAll(" strain=", " "); ConceptNames=ConceptNames.replaceAll("[\\W\\-\\_](str.|strain|substr.|substrain|var.|variant|subsp.|subspecies|pv.|pathovars|pathovar|br.|biovar)[\\W\\-\\_]", " "); ConceptNames=ConceptNames.replaceAll("[\\(\\)]", " "); } String NameColumn[]=ConceptNames.split("\\|"); for(int i=0;i<NameColumn.length;i++) { String tmp = NameColumn[i]; tmp=tmp.replaceAll("[\\W\\-\\_0-9]", ""); /* * Specific usage for Species */ if( ConceptType.equals("Species")) { if ( (!NameColumn[i].substring(0, 1).matches("[\\W\\-\\_]")) && (!NameColumn[i].matches("a[\\W\\-\\_].*")) && tmp.length()>=3) { String tmp_mention=NameColumn[i].toLowerCase(); if(!StopWord_hash.containsKey(tmp_mention)) { Tr.insertMention(NameColumn[i],ConceptType+"\t"+ConceptID); } } } /* * Specific usage for Gene & Cell */ else if ((ConceptType.equals("Gene") || ConceptType.equals("Cell")) ) { if ( (!NameColumn[i].substring(0, 1).matches("[\\W\\-\\_]")) && tmp.length()>=3) { String tmp_mention=NameColumn[i].toLowerCase(); if(!StopWord_hash.containsKey(tmp_mention)) { Tr.insertMention(NameColumn[i],ConceptType+"\t"+ConceptID); } } } /* * Other Concepts */ else { if ( (!NameColumn[i].equals("")) && (!NameColumn[i].substring(0, 1).matches("[\\W\\-\\_]")) ) { String tmp_mention=NameColumn[i].toLowerCase(); if(!StopWord_hash.containsKey(tmp_mention)) { Tr.insertMention(NameColumn[i],ConceptType+"\t"+ConceptID); } } } } } else { System.out.println("[Dictionary2Tree_Combine]: Lexicon format error! Please follow : Type | Identifier | Names (Identifier can be NULL)"); } } inputfile.close(); } catch(IOException e1){ System.out.println("[Dictionary2Tree_Combine]: Input file is not exist.");} } /* * Type Identifier Names * Species 9606 ttdh3pv|igl027/99|igl027/98|sw 1463 * * @ Prefix */ public void Dictionary2Tree(String Filename,String StopWords,String Prefix) { try { /** Stop Word */ BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(StopWords), "UTF-8")); String line=""; while ((line = br.readLine()) != null) { StopWord_hash.put(line, "StopWord"); } br.close(); /** Parsing Input */ BufferedReader inputfile = new BufferedReader(new InputStreamReader(new FileInputStream(Filename), "UTF-8")); line=""; while ((line = inputfile.readLine()) != null) { line = line.replaceAll("ω","w");line = line.replaceAll("μ","u");line = line.replaceAll("κ","k");line = line.replaceAll("α","a");line = line.replaceAll("γ","r");line = line.replaceAll("β","b");line = line.replaceAll("×","x");line = line.replaceAll("¹","1");line = line.replaceAll("²","2");line = line.replaceAll("°","o");line = line.replaceAll("ö","o");line = line.replaceAll("é","e");line = line.replaceAll("à","a");line = line.replaceAll("Á","A");line = line.replaceAll("ε","e");line = line.replaceAll("θ","O");line = line.replaceAll("•",".");line = line.replaceAll("µ","u");line = line.replaceAll("λ","r");line = line.replaceAll("⁺","+");line = line.replaceAll("ν","v");line = line.replaceAll("ï","i");line = line.replaceAll("ã","a");line = line.replaceAll("≡","=");line = line.replaceAll("ó","o");line = line.replaceAll("³","3");line = line.replaceAll("〖","[");line = line.replaceAll("〗","]");line = line.replaceAll("Å","A");line = line.replaceAll("ρ","p");line = line.replaceAll("ü","u");line = line.replaceAll("ɛ","e");line = line.replaceAll("č","c");line = line.replaceAll("š","s");line = line.replaceAll("ß","b");line = line.replaceAll("═","=");line = line.replaceAll("£","L");line = line.replaceAll("Ł","L");line = line.replaceAll("ƒ","f");line = line.replaceAll("ä","a");line = line.replaceAll("–","-");line = line.replaceAll("⁻","-");line = line.replaceAll("〈","<");line = line.replaceAll("〉",">");line = line.replaceAll("χ","X");line = line.replaceAll("Đ","D");line = line.replaceAll("‰","%");line = line.replaceAll("·",".");line = line.replaceAll("→",">");line = line.replaceAll("←","<");line = line.replaceAll("ζ","z");line = line.replaceAll("π","p");line = line.replaceAll("τ","t");line = line.replaceAll("ξ","X");line = line.replaceAll("η","h");line = line.replaceAll("ø","0");line = line.replaceAll("Δ","D");line = line.replaceAll("∆","D");line = line.replaceAll("∑","S");line = line.replaceAll("Ω","O");line = line.replaceAll("δ","d");line = line.replaceAll("σ","s"); String Column[]=line.split("\t"); if(Column.length>2) { String ConceptType=Column[0]; String ConceptID=Column[1]; String ConceptNames=Column[2]; /* * Specific usage for Species */ if( ConceptType.equals("Species")) { ConceptID=ConceptID.replace("species:ncbi:",""); ConceptNames=ConceptNames.replaceAll(" strain=", " "); ConceptNames=ConceptNames.replaceAll("[\\W\\-\\_](str.|strain|substr.|substrain|var.|variant|subsp.|subspecies|pv.|pathovars|pathovar|br.|biovar)[\\W\\-\\_]", " "); ConceptNames=ConceptNames.replaceAll("[\\(\\)]", " "); } String NameColumn[]=ConceptNames.split("\\|"); for(int i=0;i<NameColumn.length;i++) { String tmp = NameColumn[i]; tmp=tmp.replaceAll("[\\W\\-\\_0-9]", ""); /* * Specific usage for Species */ if( ConceptType.equals("Species") ) { if ((!NameColumn[i].substring(0, 1).matches("[\\W\\-\\_]")) && (!NameColumn[i].matches("a[\\W\\-\\_].*")) && tmp.length()>=3 ) { String tmp_mention=NameColumn[i].toLowerCase(); if(!StopWord_hash.containsKey(tmp_mention)) { if(Prefix.equals("")) { Tr.insertMention(NameColumn[i],ConceptType+"\t"+ConceptID); } else if(Prefix.equals("Num") && NameColumn[i].toLowerCase().matches("[0-9].*")) { Tr.insertMention(NameColumn[i],ConceptType+"\t"+ConceptID); } else if(NameColumn[i].length()>=2 && NameColumn[i].toLowerCase().substring(0,2).equals(Prefix)) { Tr.insertMention(NameColumn[i],ConceptType+"\t"+ConceptID); } else if(Prefix.equals("Other") && (!NameColumn[i].toLowerCase().matches("[0-9].*")) && (!NameColumn[i].toLowerCase().matches("[a-z][a-z].*")) ) { Tr.insertMention(NameColumn[i],ConceptType+"\t"+ConceptID); } } } } /* * Specific usage for Gene & Cell */ else if ((ConceptType.equals("Gene") || ConceptType.equals("Cell"))) { if( (!NameColumn[i].substring(0, 1).matches("[\\W\\-\\_]")) && tmp.length()>=3 ) { String tmp_mention=NameColumn[i].toLowerCase(); if(!StopWord_hash.containsKey(tmp_mention)) { if(Prefix.equals("")) { Tr.insertMention(NameColumn[i],ConceptType+"\t"+ConceptID); } else if(Prefix.equals("Num") && NameColumn[i].toLowerCase().matches("[0-9].*")) { Tr.insertMention(NameColumn[i],ConceptType+"\t"+ConceptID); } else if(NameColumn[i].length()>=2 && NameColumn[i].toLowerCase().substring(0,2).equals(Prefix)) { Tr.insertMention(NameColumn[i],ConceptType+"\t"+ConceptID); } else if(Prefix.equals("Other") && (!NameColumn[i].toLowerCase().matches("[0-9].*")) && (!NameColumn[i].toLowerCase().matches("[a-z][a-z].*")) ) { Tr.insertMention(NameColumn[i],ConceptType+"\t"+ConceptID); } } } } /* * Other Concepts */ else { if ( (!NameColumn[i].equals("")) && (!NameColumn[i].substring(0, 1).matches("[\\W\\-\\_]")) ) { String tmp_mention=NameColumn[i].toLowerCase(); if(!StopWord_hash.containsKey(tmp_mention)) { if(Prefix.equals("")) { Tr.insertMention(NameColumn[i],ConceptType+"\t"+ConceptID); } else if(Prefix.equals("Num") && NameColumn[i].toLowerCase().matches("[0-9].*")) { Tr.insertMention(NameColumn[i],ConceptType+"\t"+ConceptID); } else if(NameColumn[i].length()>2 && NameColumn[i].toLowerCase().substring(0,2).equals(Prefix)) { Tr.insertMention(NameColumn[i],ConceptType+"\t"+ConceptID); } else if(Prefix.equals("Other") && (!NameColumn[i].toLowerCase().matches("[0-9].*")) && (!NameColumn[i].toLowerCase().matches("[a-z][a-z].*")) ) { Tr.insertMention(NameColumn[i],ConceptType+"\t"+ConceptID); } } } } } } else { System.out.println("[Dictionary2Tree_Combine]: Lexicon format error! Please follow : Type | Identifier | Names (Identifier can be NULL)"); } } inputfile.close(); } catch(IOException e1){ System.out.println("[Dictionary2Tree_Combine]: Input file is not exist.");} } public void TreeFile2Tree(String Filename) { try { BufferedReader inputfile = new BufferedReader(new InputStreamReader(new FileInputStream(Filename), "UTF-8")); String line=""; int count=0; while ((line = inputfile.readLine()) != null) { line = line.replaceAll("ω","w");line = line.replaceAll("μ","u");line = line.replaceAll("κ","k");line = line.replaceAll("α","a");line = line.replaceAll("γ","r");line = line.replaceAll("β","b");line = line.replaceAll("×","x");line = line.replaceAll("¹","1");line = line.replaceAll("²","2");line = line.replaceAll("°","o");line = line.replaceAll("ö","o");line = line.replaceAll("é","e");line = line.replaceAll("à","a");line = line.replaceAll("Á","A");line = line.replaceAll("ε","e");line = line.replaceAll("θ","O");line = line.replaceAll("•",".");line = line.replaceAll("µ","u");line = line.replaceAll("λ","r");line = line.replaceAll("⁺","+");line = line.replaceAll("ν","v");line = line.replaceAll("ï","i");line = line.replaceAll("ã","a");line = line.replaceAll("≡","=");line = line.replaceAll("ó","o");line = line.replaceAll("³","3");line = line.replaceAll("〖","[");line = line.replaceAll("〗","]");line = line.replaceAll("Å","A");line = line.replaceAll("ρ","p");line = line.replaceAll("ü","u");line = line.replaceAll("ɛ","e");line = line.replaceAll("č","c");line = line.replaceAll("š","s");line = line.replaceAll("ß","b");line = line.replaceAll("═","=");line = line.replaceAll("£","L");line = line.replaceAll("Ł","L");line = line.replaceAll("ƒ","f");line = line.replaceAll("ä","a");line = line.replaceAll("–","-");line = line.replaceAll("⁻","-");line = line.replaceAll("〈","<");line = line.replaceAll("〉",">");line = line.replaceAll("χ","X");line = line.replaceAll("Đ","D");line = line.replaceAll("‰","%");line = line.replaceAll("·",".");line = line.replaceAll("→",">");line = line.replaceAll("←","<");line = line.replaceAll("ζ","z");line = line.replaceAll("π","p");line = line.replaceAll("τ","t");line = line.replaceAll("ξ","X");line = line.replaceAll("η","h");line = line.replaceAll("ø","0");line = line.replaceAll("Δ","D");line = line.replaceAll("∆","D");line = line.replaceAll("∑","S");line = line.replaceAll("Ω","O");line = line.replaceAll("δ","d");line = line.replaceAll("σ","s"); String Anno[]=line.split("\t"); String LocationInTree = Anno[0]; String token = Anno[1]; String type=""; String identifier=""; if(Anno.length>2) { type = Anno[2]; } if(Anno.length>3) { identifier = Anno[3]; } String LocationsInTree[]=LocationInTree.split("-"); TreeNode tmp = Tr.root; for(int i=0;i<LocationsInTree.length-1;i++) { tmp=tmp.links.get(Integer.parseInt(LocationsInTree[i])-1); } if(type.equals("") && identifier.equals("")) { tmp.InsertToken(token,""); } else if(identifier.equals("")) { tmp.InsertToken(token,type); } else { tmp.InsertToken(token,type+"\t"+identifier); } count++; } inputfile.close(); } catch(IOException e1){ System.out.println("[TreeFile2Tee]: Input file is not exist.");} } /* * Search target mention in the Prefix Tree */ public String MentionMatch(String Mentions,Integer PrefixTranslation, Integer Tok_NumCharPartialMatch) { ArrayList<String> location = new ArrayList<String>(); String Menlist[]=Mentions.split("\\|"); for(int m=0;m<Menlist.length;m++) { String Mention=Menlist[m]; String Mention_lc=Mention.toLowerCase(); Mention_lc = Mention_lc.replaceAll("[\\W\\-\\_]+", ""); Mention_lc = Mention_lc.replaceAll("([0-9])([a-z])", "$1 $2"); Mention_lc = Mention_lc.replaceAll("([a-z])([0-9])", "$1 $2"); String Tkns[]=Mention_lc.split(" "); int i=0; boolean find=false; TreeNode tmp = Tr.root; String Concept=""; while( i<Tkns.length && tmp.CheckChild(Tkns[i],i,Tok_NumCharPartialMatch,PrefixTranslation)>=0) //Find Tokens in the links { int CheckChild_Num=tmp.CheckChild(Tkns[i],i,Tok_NumCharPartialMatch,PrefixTranslation); int CheckChild_Num_tmp=CheckChild_Num; if(CheckChild_Num>=10000000){CheckChild_Num_tmp=CheckChild_Num-10000000;} tmp=tmp.links.get(CheckChild_Num_tmp); //move point to the link Concept = tmp.Concept; if(CheckChild_Num>=10000000){Concept="Species _PartialMatch_";} find=true; i++; } if(find == true) { if(i==Tkns.length) { if(!Concept.equals("")) { return Concept; } else { return "-1"; //gene id is not found. } } else { return "-2"; //the gene mention matched a substring in PrefixTree. } } else { return "-3"; //mention is not found } } return "-3"; //mention is not found } /* * Search target mention in the Prefix Tree * ConceptType: Species|Genus|Cell|CTDGene */ public ArrayList<String> SearchMentionLocation(String Doc,String Doc_org,String ConceptType, Integer PrefixTranslation, Integer Tok_NumCharPartialMatch) { ArrayList<String> location = new ArrayList<String>(); Doc=Doc.toLowerCase(); String Doc_lc=Doc; Doc = Doc.replaceAll("([0-9])([A-Za-z])", "$1 $2"); Doc = Doc.replaceAll("([A-Za-z])([0-9])", "$1 $2"); Doc = Doc.replaceAll("[\\W^;:,]+", " "); String DocTkns[]=Doc.split(" "); int Offset=0; int Start=0; int Last=0; int FirstTime=0; while(Doc_lc.length()>0 && Doc_lc.substring(0,1).matches("[\\W]")) //clean the forward whitespace { Doc_lc=Doc_lc.substring(1); Offset++; } for(int i=0;i<DocTkns.length;i++) { TreeNode tmp = Tr.root; boolean find=false; int ConceptFound=i; //Keep found concept String ConceptFound_STR="";//Keep found concept int Tokn_num=0; String Concept=""; while( tmp.CheckChild(DocTkns[i],Tokn_num,Tok_NumCharPartialMatch,PrefixTranslation)>=0 ) //Find Tokens in the links { int CheckChild_Num=tmp.CheckChild(DocTkns[i],Tokn_num,Tok_NumCharPartialMatch,PrefixTranslation); int CheckChild_Num_tmp=CheckChild_Num; if(CheckChild_Num>=10000000){CheckChild_Num_tmp=CheckChild_Num-10000000;} tmp=tmp.links.get(CheckChild_Num_tmp); //move point to the link Concept = tmp.Concept; if(CheckChild_Num>=10000000){Concept="Species _PartialMatch_";} if(Start==0 && FirstTime>0){Start = Offset;} //Start <- Offset if(Doc_lc.length()>=DocTkns[i].length() && Doc_lc.substring(0,DocTkns[i].length()).equals(DocTkns[i])) { if(DocTkns[i].length()>0) { Doc_lc=Doc_lc.substring(DocTkns[i].length()); Offset=Offset+DocTkns[i].length(); } } Last = Offset; while(Doc_lc.length()>0 && Doc_lc.substring(0,1).matches("[\\W]")) //clean the forward whitespace { Doc_lc=Doc_lc.substring(1); Offset++; } i++; Tokn_num++; if(ConceptType.equals("Species")) { if(i<DocTkns.length-2 && DocTkns[i].matches("(str|strain|substr|substrain|subspecies|subsp|var|variant|pathovars|pv|biovar|bv)")) { Doc_lc=Doc_lc.substring(DocTkns[i].length()); Offset=Offset+DocTkns[i].length(); Last = Offset; while(Doc_lc.length()>0 && Doc_lc.substring(0,1).matches("[\\W]")) //clean the forward whitespace { Doc_lc=Doc_lc.substring(1); Offset++; } i++; } } if(!Concept.equals("") && (Last-Start>0)) //Keep found concept { ConceptFound=i; ConceptFound_STR=Start+"\t"+Last+"\t"+Doc_org.substring(Start, Last)+"\t"+Concept; } find=true; if(i>=DocTkns.length){break;} //else if(i==DocTkns.length-1){PrefixTranslation=2;} } if(find == true) { if(!Concept.equals("") && (Last-Start>0)) //the last matched token has concept id { location.add(Start+"\t"+Last+"\t"+Doc_org.substring(Start, Last)+"\t"+Concept); } else if(!ConceptFound_STR.equals("")) //Keep found concept { location.add(ConceptFound_STR); i = ConceptFound + 1; } Start=0; Last=0; if(i>0){i--;} ConceptFound=i; //Keep found concept ConceptFound_STR="";//Keep found concept } else //if(find == false) { if(Doc_lc.length()>=DocTkns[i].length() && Doc_lc.substring(0,DocTkns[i].length()).equals(DocTkns[i])) { if(DocTkns[i].length()>0) { Doc_lc=Doc_lc.substring(DocTkns[i].length()); Offset=Offset+DocTkns[i].length(); } } } while(Doc_lc.length()>0 && Doc_lc.substring(0,1).matches("[\\W]")) //clean the forward whitespace { Doc_lc=Doc_lc.substring(1); Offset++; } FirstTime++; } return location; } /* * Print out the Prefix Tree */ public String PrintTree() { return Tr.PrintTree_preorder(Tr.root,""); } } class Tree { /* * Prefix Tree - root node */ public TreeNode root; public Tree() { root = new TreeNode("-ROOT-"); } /* * Insert mention into the tree */ public void insertMention(String Mention, String Identifier) { Mention=Mention.toLowerCase(); Identifier = Identifier.replaceAll("\t$", ""); Mention = Mention.replaceAll("([0-9])([A-Za-z])", "$1 $2"); Mention = Mention.replaceAll("([A-Za-z])([0-9])", "$1 $2"); Mention = Mention.replaceAll("[\\W\\-\\_]+", " "); String Tokens[]=Mention.split(" "); TreeNode tmp = root; for(int i=0;i<Tokens.length;i++) { if(tmp.CheckChild(Tokens[i],i,0,0)>=0) { tmp=tmp.links.get( tmp.CheckChild(Tokens[i],i,0,0) ); //go through next generation (exist node) if(i == Tokens.length-1) { tmp.Concept=Identifier; } } else //not exist { if(i == Tokens.length-1) { tmp.InsertToken(Tokens[i],Identifier); } else { tmp.InsertToken(Tokens[i]); } tmp=tmp.links.get(tmp.NumOflinks-1); //go to the next generation (new node) } } } /* * Print the tree by pre-order */ public String PrintTree_preorder(TreeNode node, String LocationInTree) { String opt=""; if(!node.token.equals("-ROOT-"))//Ignore root { if(node.Concept.equals("")) { opt=opt+LocationInTree+"\t"+node.token+"\n"; } else { opt=opt+LocationInTree+"\t"+node.token+"\t"+node.Concept+"\n"; } } if(!LocationInTree.equals("")){LocationInTree=LocationInTree+"-";} for(int i=0;i<node.NumOflinks;i++) { opt=opt+PrintTree_preorder(node.links.get(i),LocationInTree+(i+1)); } return opt; } } class TreeNode { String token; //token of the node int NumOflinks; //Number of links public String Concept; ArrayList<TreeNode> links; public TreeNode(String Tok,String ID) { token = Tok; NumOflinks = 0; Concept = ID; links = new ArrayList<TreeNode>(); } public TreeNode(String Tok) { token = Tok; NumOflinks = 0; Concept = ""; links = new ArrayList<TreeNode>(); } public TreeNode() { token = ""; NumOflinks = 0; Concept = ""; links = new ArrayList<TreeNode>(); } /* * Insert an new node under the target node */ public void InsertToken(String Tok) { TreeNode NewNode = new TreeNode(Tok); links.add(NewNode); NumOflinks++; } public void InsertToken(String Tok,String ID) { TreeNode NewNode = new TreeNode(Tok,ID); links.add(NewNode); NumOflinks++; } /* * Check the tokens of children * PrefixTranslation = 1 (SuffixTranslationMap) * PrefixTranslation = 2 (CTDGene; partial match for numbers) * PrefixTranslation = 3 (NCBI Taxonomy usage (IEB) : suffix partial match) */ public int CheckChild(String Tok,Integer Tok_num,Integer Tok_NumCharPartialMatch, Integer PrefixTranslation) { /** Suffix Translation */ ArrayList<String> SuffixTranslationMap = new ArrayList<String>(); SuffixTranslationMap.add("alpha-a"); SuffixTranslationMap.add("alpha-1"); SuffixTranslationMap.add("a-alpha"); //SuffixTranslationMap.add("a-1"); SuffixTranslationMap.add("1-alpha"); //SuffixTranslationMap.add("1-a"); SuffixTranslationMap.add("beta-b"); SuffixTranslationMap.add("beta-2"); SuffixTranslationMap.add("b-beta"); //SuffixTranslationMap.add("b-2"); SuffixTranslationMap.add("2-beta"); //SuffixTranslationMap.add("2-b"); SuffixTranslationMap.add("gamma-g"); SuffixTranslationMap.add("gamma-y"); SuffixTranslationMap.add("g-gamma"); SuffixTranslationMap.add("y-gamma"); SuffixTranslationMap.add("1-i"); SuffixTranslationMap.add("i-1"); SuffixTranslationMap.add("2-ii"); SuffixTranslationMap.add("ii-2"); SuffixTranslationMap.add("3-iii"); SuffixTranslationMap.add("iii-3"); SuffixTranslationMap.add("4-vi"); SuffixTranslationMap.add("vi-4"); SuffixTranslationMap.add("5-v"); SuffixTranslationMap.add("v-5"); for(int i=0;i<links.size();i++) { if(Tok.equals(links.get(i).token)) { return (i); } } if(PrefixTranslation == 1 && Tok.matches("(alpha|beta|gamam|[abg]|[12])")) // SuffixTranslationMap { for(int i=0;i<links.size();i++) { if(SuffixTranslationMap.contains(Tok+"-"+links.get(i).token)) { return(i); } } } else if(PrefixTranslation == 2 && Tok.matches("[1-5]")) // for CTDGene feature { for(int i=0;i<links.size();i++) { if(links.get(i).token.matches("[1-5]")) { return(i); } } } else if(PrefixTranslation == 3 && Tok.length()>=Tok_NumCharPartialMatch && Tok_num>=1) // for NCBI Taxonomy usage (IEB) : suffix partial match { for(int i=0;i<links.size();i++) { if(links.get(i).token.length()>=Tok_NumCharPartialMatch) { String Tok_Prefix=Tok.substring(0,Tok_NumCharPartialMatch); if((!links.get(i).Concept.equals("")) && links.get(i).token.substring(0,Tok_NumCharPartialMatch).equals(Tok_Prefix)) { return(i+10000000); } } } } return(-1); } }
26,828
35.353659
1,988
java
null
tmVar3-main/src/tmVarlib/tmVar.java
package tmVarlib; // // tmVar - Java version // import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.sql.SQLException; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.xml.stream.XMLStreamException; import org.tartarus.snowball.SnowballStemmer; import org.tartarus.snowball.ext.englishStemmer; import edu.stanford.nlp.tagger.maxent.MaxentTagger; public class tmVar { public static MaxentTagger tagger = new MaxentTagger(); public static SnowballStemmer stemmer = new englishStemmer(); public static ArrayList<String> RegEx_DNAMutation_STR=new ArrayList<String>(); public static ArrayList<String> RegEx_ProteinMutation_STR=new ArrayList<String>(); public static ArrayList<String> RegEx_SNP_STR=new ArrayList<String>(); public static ArrayList<String> PAM_lowerScorePair = new ArrayList<String>(); public static HashMap<String,String> GeneVariantMention = new HashMap<String,String>(); public static HashMap<String,Integer> VariantFrequency = new HashMap<String,Integer>(); public static Pattern Pattern_Component_1; public static Pattern Pattern_Component_2; public static Pattern Pattern_Component_3; public static Pattern Pattern_Component_4; public static Pattern Pattern_Component_5; public static Pattern Pattern_Component_6; public static boolean GeneMention = false; // will be turn to true if "ExtractFeature" can find gene mention public static HashMap<String,String> nametothree = new HashMap<String,String>(); public static HashMap<String,String> threetone = new HashMap<String,String>(); public static HashMap<String,String> threetone_nu = new HashMap<String,String>(); public static HashMap<String,String> NTtoATCG = new HashMap<String,String>(); public static ArrayList<String> MF_Pattern = new ArrayList<String>(); public static ArrayList<String> MF_Type = new ArrayList<String>(); public static HashMap<String,String> filteringStr_hash = new HashMap<String,String>(); public static HashMap<String,String> Mutation_RS_Geneid_hash = new HashMap<String,String>(); public static ArrayList<String> RS_DNA_Protein = new ArrayList<String>(); public static HashMap<String,String> one2three = new HashMap<String,String>(); public static PrefixTree PT_GeneVariantMention = new PrefixTree(); public static HashMap<String,String> VariantType_hash = new HashMap<String,String>(); public static HashMap<String,String> Number_word2digit = new HashMap<String,String>(); public static HashMap<String,String> grouped_variants = new HashMap<String,String>(); public static HashMap<String,String> nu2aa_hash = new HashMap<String,String>(); public static HashMap<String,Integer> RS2Frequency_hash = new HashMap<String,Integer>(); public static HashMap<String,HashMap<Integer,String>> variant_mention_to_filter_overlap_gene = new HashMap<String,HashMap<Integer,String>>(); // gene mention: GCC public static HashMap<String,String> Gene2HumanGene_hash = new HashMap<String,String>(); public static HashMap<String,String> Variant2MostCorrespondingGene_hash = new HashMap<String,String>(); public static HashMap<String,String> RSandPosition2Seq_hash = new HashMap<String,String>(); public static void main(String [] args) throws IOException, InterruptedException, XMLStreamException, SQLException { /* * Parameters */ String InputFolder="input"; String OutputFolder="output"; String TrainTest="Test"; //Train|Train_Mention|Test|Test_FullText String DeleteTmp="True"; String DisplayRSnumOnly="True"; // hide the types of the methods String DisplayChromosome="True"; // hide the chromosome mentions String DisplayRefSeq="True"; // hide the RefSeq mentions String DisplayGenomicRegion="True"; String HideMultipleResult="True"; //L858R: 121434568|1057519847|1057519848 --> 121434568 if(args.length<2) { System.out.println("\n$ java -Xmx5G -Xms5G -jar tmVar.jar [InputFolder] [OutputFolder]"); System.out.println("[InputFolder] Default : input"); System.out.println("[OutputFolder] Default : output\n\n"); } else { InputFolder=args [0]; OutputFolder=args [1]; if(args.length>2 && args[2].toLowerCase().matches("(train|train_mention|test|test_fulltext)")) { TrainTest=args [2]; if(args[2].toLowerCase().matches("(train|train_mention)")) { DeleteTmp="False"; } } if(args.length>3 && args[3].toLowerCase().matches("(True|False)")) { DeleteTmp=args [3]; } if(args.length>4 && args[4].toLowerCase().matches("(True|False)")) { DisplayRSnumOnly=args [4]; } if(args.length>5 && args[5].toLowerCase().matches("(True|False)")) { HideMultipleResult=args [4]; } } double startTime,endTime,totTime; startTime = System.currentTimeMillis();//start time BioCConverter BC= new BioCConverter(); /** * Import models and resource */ { /* * POSTagging: loading model */ tagger = new MaxentTagger("lib/taggers/english-left3words-distsim.tagger"); /* * Stemming : using Snowball */ stemmer = new englishStemmer(); /* * PAM 140 : <=-6 pairs */ BufferedReader PAM = new BufferedReader(new InputStreamReader(new FileInputStream("lib/PAM140-6.txt"), "UTF-8")); String line=""; while ((line = PAM.readLine()) != null) { String nt[]=line.split("\t"); PAM_lowerScorePair.add(nt[0]+"\t"+nt[1]); PAM_lowerScorePair.add(nt[1]+"\t"+nt[0]); } PAM.close(); /* * Variant frequency */ BufferedReader frequency = new BufferedReader(new InputStreamReader(new FileInputStream("Database/rs.rank.txt"), "UTF-8")); line=""; while ((line = frequency.readLine()) != null) { String nt[]=line.split("\t"); VariantFrequency.put(nt[1],Integer.parseInt(nt[0])); } frequency.close(); /* * HGVs nomenclature lookup - RegEx : DNAMutation */ BufferedReader RegEx_DNAMutation = new BufferedReader(new InputStreamReader(new FileInputStream("lib/RegEx/DNAMutation.RegEx.txt"), "UTF-8")); line=""; while ((line = RegEx_DNAMutation.readLine()) != null) { RegEx_DNAMutation_STR.add(line); } RegEx_DNAMutation.close(); /* * HGVs nomenclature lookup - RegEx : ProteinMutation */ BufferedReader RegEx_ProteinMutation = new BufferedReader(new InputStreamReader(new FileInputStream("lib/RegEx/ProteinMutation.RegEx.txt"), "UTF-8")); line=""; while ((line = RegEx_ProteinMutation.readLine()) != null) { RegEx_ProteinMutation_STR.add(line); } RegEx_ProteinMutation.close(); /* * HGVs nomenclature lookup - RegEx : SNP */ BufferedReader RegEx_SNP = new BufferedReader(new InputStreamReader(new FileInputStream("lib/RegEx/SNP.RegEx.txt"), "UTF-8")); line=""; while ((line = RegEx_SNP.readLine()) != null) { RegEx_SNP_STR.add(line); } RegEx_SNP.close(); /* * Append-pattern */ BufferedReader RegEx_NL = new BufferedReader(new InputStreamReader(new FileInputStream("lib/RegEx/MF.RegEx.2.txt"), "UTF-8")); while ((line = RegEx_NL.readLine()) != null) { String RegEx[]=line.split("\t"); MF_Pattern.add(RegEx[0]); MF_Type.add(RegEx[1]); } RegEx_NL.close(); /* * Append-pattern */ BufferedReader VariantType = new BufferedReader(new InputStreamReader(new FileInputStream("lib/RegEx/VariantType.txt"), "UTF-8")); while ((line = VariantType.readLine()) != null) { String split[]=line.split("\t"); VariantType_hash.put(split[0],split[1]); } VariantType.close(); /* * nu2aa */ BufferedReader nu2aa = new BufferedReader(new InputStreamReader(new FileInputStream("lib/RegEx/nu2aa.mapping.txt"), "UTF-8")); while ((line = nu2aa.readLine()) != null) { nu2aa_hash.put(line,""); } nu2aa.close(); //RegEx of component recognition Pattern_Component_1 = Pattern.compile("^([^|]*)\\|([^|]*)\\|([^|]*)\\|([^|]*)\\|(fs[^|]*)\\|([^|]*)$"); Pattern_Component_2 = Pattern.compile("^([^|]*)\\|([^|]*)\\|([^|]*)\\|([^|]*)\\|(fs[^|]*)$"); Pattern_Component_3 = Pattern.compile("^([^|]*)\\|([^|]*(ins|del|Del|dup|-)[^|]*)\\|([^|]*)\\|([^|]*)$"); Pattern_Component_4 = Pattern.compile("^([^|]*)\\|([^|]*)\\|([^|]*)\\|([^|]*)$"); Pattern_Component_5 = Pattern.compile("^([^|]*)\\|([^|]*)\\|([^|]*)\\|([^|]*)\\|([^|]*)$"); Pattern_Component_6 = Pattern.compile("^((\\[rs\\]|rs|RS|Rs|reference SNP no[.] )[0-9]+)$"); nametothree.put("GLUTAMIC","GLU");nametothree.put("ASPARTIC","ASP");nametothree.put("THYMINE", "THY");nametothree.put("ALANINE", "ALA");nametothree.put("ARGININE", "ARG");nametothree.put("ASPARAGINE", "ASN");nametothree.put("ASPARTICACID", "ASP");nametothree.put("ASPARTATE", "ASP");nametothree.put("CYSTEINE", "CYS");nametothree.put("GLUTAMINE", "GLN");nametothree.put("GLUTAMICACID", "GLU");nametothree.put("GLUTAMATE", "GLU");nametothree.put("GLYCINE", "GLY");nametothree.put("HISTIDINE", "HIS");nametothree.put("ISOLEUCINE", "ILE");nametothree.put("LEUCINE", "LEU");nametothree.put("LYSINE", "LYS");nametothree.put("METHIONINE", "MET");nametothree.put("PHENYLALANINE", "PHE");nametothree.put("PROLINE", "PRO");nametothree.put("SERINE", "SER");nametothree.put("THREONINE", "THR");nametothree.put("TRYPTOPHAN", "TRP");nametothree.put("TYROSINE", "TYR");nametothree.put("VALINE", "VAL");nametothree.put("STOP", "XAA");nametothree.put("TERM", "XAA");nametothree.put("TERMINATION", "XAA");nametothree.put("STOP", "XAA");nametothree.put("TERM", "XAA");nametothree.put("TERMINATION", "XAA");nametothree.put("GLUTAMICCODON","GLU");nametothree.put("ASPARTICCODON","ASP");nametothree.put("THYMINECODON","THY");nametothree.put("ALANINECODON","ALA");nametothree.put("ARGININECODON","ARG");nametothree.put("ASPARAGINECODON","ASN");nametothree.put("ASPARTICACIDCODON","ASP");nametothree.put("ASPARTATECODON","ASP");nametothree.put("CYSTEINECODON","CYS");nametothree.put("GLUTAMINECODON","GLN");nametothree.put("GLUTAMICACIDCODON","GLU");nametothree.put("GLUTAMATECODON","GLU");nametothree.put("GLYCINECODON","GLY");nametothree.put("HISTIDINECODON","HIS");nametothree.put("ISOLEUCINECODON","ILE");nametothree.put("LEUCINECODON","LEU");nametothree.put("LYSINECODON","LYS");nametothree.put("METHIONINECODON","MET");nametothree.put("PHENYLALANINECODON","PHE");nametothree.put("PROLINECODON","PRO");nametothree.put("SERINECODON","SER");nametothree.put("THREONINECODON","THR");nametothree.put("TRYPTOPHANCODON","TRP");nametothree.put("TYROSINECODON","TYR");nametothree.put("VALINECODON","VAL");nametothree.put("STOPCODON","XAA");nametothree.put("TERMCODON","XAA");nametothree.put("TERMINATIONCODON","XAA");nametothree.put("STOPCODON","XAA");nametothree.put("TERMCODON","XAA");nametothree.put("TERMINATIONCODON","XAA");nametothree.put("TAG","XAA");nametothree.put("TAA","XAA");nametothree.put("UAG","XAA");nametothree.put("UAA","XAA"); threetone.put("ALA", "A");threetone.put("ARG", "R");threetone.put("ASN", "N");threetone.put("ASP", "D");threetone.put("CYS", "C");threetone.put("GLN", "Q");threetone.put("GLU", "E");threetone.put("GLY", "G");threetone.put("HIS", "H");threetone.put("ILE", "I");threetone.put("LEU", "L");threetone.put("LYS", "K");threetone.put("MET", "M");threetone.put("PHE", "F");threetone.put("PRO", "P");threetone.put("SER", "S");threetone.put("THR", "T");threetone.put("TRP", "W");threetone.put("TYR", "Y");threetone.put("VAL", "V");threetone.put("ASX", "B");threetone.put("GLX", "Z");threetone.put("XAA", "X");threetone.put("TER", "X"); threetone_nu.put("GCU","A");threetone_nu.put("GCC","A");threetone_nu.put("GCA","A");threetone_nu.put("GCG","A");threetone_nu.put("CGU","R");threetone_nu.put("CGC","R");threetone_nu.put("CGA","R");threetone_nu.put("CGG","R");threetone_nu.put("AGA","R");threetone_nu.put("AGG","R");threetone_nu.put("AAU","N");threetone_nu.put("AAC","N");threetone_nu.put("GAU","D");threetone_nu.put("GAC","D");threetone_nu.put("UGU","C");threetone_nu.put("UGC","C");threetone_nu.put("GAA","E");threetone_nu.put("GAG","E");threetone_nu.put("CAA","Q");threetone_nu.put("CAG","Q");threetone_nu.put("GGU","G");threetone_nu.put("GGC","G");threetone_nu.put("GGA","G");threetone_nu.put("GGG","G");threetone_nu.put("CAU","H");threetone_nu.put("CAC","H");threetone_nu.put("AUU","I");threetone_nu.put("AUC","I");threetone_nu.put("AUA","I");threetone_nu.put("CUU","L");threetone_nu.put("CUC","L");threetone_nu.put("CUA","L");threetone_nu.put("CUG","L");threetone_nu.put("UUA","L");threetone_nu.put("UUG","L");threetone_nu.put("AAA","K");threetone_nu.put("AAG","K");threetone_nu.put("AUG","M");threetone_nu.put("UUU","F");threetone_nu.put("UUC","F");threetone_nu.put("CCU","P");threetone_nu.put("CCC","P");threetone_nu.put("CCA","P");threetone_nu.put("CCG","P");threetone_nu.put("UCU","S");threetone_nu.put("UCC","S");threetone_nu.put("UCA","S");threetone_nu.put("UCG","S");threetone_nu.put("AGU","S");threetone_nu.put("AGC","S");threetone_nu.put("ACU","T");threetone_nu.put("ACC","T");threetone_nu.put("ACA","T");threetone_nu.put("ACG","T");threetone_nu.put("UGG","W");threetone_nu.put("UAU","Y");threetone_nu.put("UAC","Y");threetone_nu.put("GUU","V");threetone_nu.put("GUC","V");threetone_nu.put("GUA","V");threetone_nu.put("GUG","V");threetone_nu.put("UAA","X");threetone_nu.put("UGA","X");threetone_nu.put("UAG","X");threetone_nu.put("GCT","A");threetone_nu.put("GCC","A");threetone_nu.put("GCA","A");threetone_nu.put("GCG","A");threetone_nu.put("CGT","R");threetone_nu.put("CGC","R");threetone_nu.put("CGA","R");threetone_nu.put("CGG","R");threetone_nu.put("AGA","R");threetone_nu.put("AGG","R");threetone_nu.put("AAT","N");threetone_nu.put("AAC","N");threetone_nu.put("GAT","D");threetone_nu.put("GAC","D");threetone_nu.put("TGT","C");threetone_nu.put("TGC","C");threetone_nu.put("GAA","E");threetone_nu.put("GAG","E");threetone_nu.put("CAA","Q");threetone_nu.put("CAG","Q");threetone_nu.put("GGT","G");threetone_nu.put("GGC","G");threetone_nu.put("GGA","G");threetone_nu.put("GGG","G");threetone_nu.put("CAT","H");threetone_nu.put("CAC","H");threetone_nu.put("ATT","I");threetone_nu.put("ATC","I");threetone_nu.put("ATA","I");threetone_nu.put("CTT","L");threetone_nu.put("CTC","L");threetone_nu.put("CTA","L");threetone_nu.put("CTG","L");threetone_nu.put("TTA","L");threetone_nu.put("TTG","L");threetone_nu.put("AAA","K");threetone_nu.put("AAG","K");threetone_nu.put("ATG","M");threetone_nu.put("TTT","F");threetone_nu.put("TTC","F");threetone_nu.put("CCT","P");threetone_nu.put("CCC","P");threetone_nu.put("CCA","P");threetone_nu.put("CCG","P");threetone_nu.put("TCT","S");threetone_nu.put("TCC","S");threetone_nu.put("TCA","S");threetone_nu.put("TCG","S");threetone_nu.put("AGT","S");threetone_nu.put("AGC","S");threetone_nu.put("ACT","T");threetone_nu.put("ACC","T");threetone_nu.put("ACA","T");threetone_nu.put("ACG","T");threetone_nu.put("TGG","W");threetone_nu.put("TAT","Y");threetone_nu.put("TAC","Y");threetone_nu.put("GTT","V");threetone_nu.put("GTC","V");threetone_nu.put("GTA","V");threetone_nu.put("GTG","V");threetone_nu.put("TAA","X");threetone_nu.put("TGA","X");threetone_nu.put("TAG","X"); NTtoATCG.put("ADENINE", "A");NTtoATCG.put("CYTOSINE", "C");NTtoATCG.put("GUANINE", "G");NTtoATCG.put("URACIL", "U");NTtoATCG.put("THYMINE", "T");NTtoATCG.put("ADENOSINE", "A");NTtoATCG.put("CYTIDINE", "C");NTtoATCG.put("THYMIDINE", "T");NTtoATCG.put("GUANOSINE", "G");NTtoATCG.put("URIDINE", "U"); Number_word2digit.put("ZERO","0");Number_word2digit.put("SINGLE","1");Number_word2digit.put("ONE","1");Number_word2digit.put("TWO","2");Number_word2digit.put("THREE","3");Number_word2digit.put("FOUR","4");Number_word2digit.put("FIVE","5");Number_word2digit.put("SIX","6");Number_word2digit.put("SEVEN","7");Number_word2digit.put("EIGHT","8");Number_word2digit.put("NINE","9");Number_word2digit.put("TWN","10"); //Filtering BufferedReader filterfile = new BufferedReader(new InputStreamReader(new FileInputStream("lib/filtering.txt"), "UTF-8")); while ((line = filterfile.readLine()) != null) { filteringStr_hash.put(line, ""); } filterfile.close(); /*one2three*/ one2three.put("A", "Ala"); one2three.put("R", "Arg"); one2three.put("N", "Asn"); one2three.put("D", "Asp"); one2three.put("C", "Cys"); one2three.put("Q", "Gln"); one2three.put("E", "Glu"); one2three.put("G", "Gly"); one2three.put("H", "His"); one2three.put("I", "Ile"); one2three.put("L", "Leu"); one2three.put("K", "Lys"); one2three.put("M", "Met"); one2three.put("F", "Phe"); one2three.put("P", "Pro"); one2three.put("S", "Ser"); one2three.put("T", "Thr"); one2three.put("W", "Trp"); one2three.put("Y", "Tyr"); one2three.put("V", "Val"); one2three.put("B", "Asx"); one2three.put("Z", "Glx"); one2three.put("X", "Xaa"); one2three.put("X", "Ter"); /*RS_DNA_Protein.txt - Pattern : PP[P]+[ ]*[\(\[][ ]*DD[D]+[ ]*[\)\]][ ]*[\(\[][ ]*SS[S]+[ ]*[\)\]]*/ BufferedReader inputfile = new BufferedReader(new InputStreamReader(new FileInputStream("lib/RegEx/RS_DNA_Protein.txt"), "UTF-8")); while ((line = inputfile.readLine()) != null) { if(!line.equals("")) { RS_DNA_Protein.add(line); } } inputfile.close(); /*PT_GeneVariantMention - BRAFV600E*/ PT_GeneVariantMention.TreeFile2Tree("lib/PT_GeneVariantMention.txt"); /*Mutation_RS_Geneid.txt - the patterns retrieved from PubMed result*/ inputfile = new BufferedReader(new InputStreamReader(new FileInputStream("lib/RegEx/Mutation_RS_Geneid.txt"), "UTF-8")); while ((line = inputfile.readLine()) != null) { //Pattern c|SUB|C|1749|T 2071558 269 Pattern pat = Pattern.compile("^(Pattern|Recognized|ManuallyAdded) ([^\t]+) ([0-9]+) ([0-9,]+)$"); Matcher mat = pat.matcher(line); if (mat.find()) { String geneids[]=mat.group(4).split(","); for(int i=0;i<geneids.length;i++) { //mutation id | geneid --> rs# Mutation_RS_Geneid_hash.put(mat.group(2)+"\t"+geneids[i], mat.group(3)); } } } inputfile.close(); /** tmVarForm2RSID2Freq - together with Mutation_RS_Geneid.txt (the patterns retrieved from PubMed result) */ BufferedReader tmVarForm2RSID2Freq = new BufferedReader(new InputStreamReader(new FileInputStream("lib/tmVarForm2RSID2Freq.txt"), "UTF-8")); line=""; while ((line = tmVarForm2RSID2Freq.readLine()) != null) { String nt[]=line.split("\t"); String tmVarForm=nt[0]; String rs_gene_freq=nt[1]; //RS:rs121913377|Gene:673|Freq:3 Pattern pat = Pattern.compile("^RS:rs([0-9]+)\\|Gene:([0-9,]+)\\|Freq:([0-9]+)$"); Matcher mat = pat.matcher(rs_gene_freq); if (mat.find()) { String rs=mat.group(1); String gene=mat.group(2); Mutation_RS_Geneid_hash.put(tmVarForm+"\t"+gene,rs); } } tmVarForm2RSID2Freq.close(); /** RS2Frequency - rs# to its frequency in PTC) */ BufferedReader RS2Frequency = new BufferedReader(new InputStreamReader(new FileInputStream("lib/RS2Frequency.txt"), "UTF-8")); line=""; while ((line = RS2Frequency.readLine()) != null) { String nt[]=line.split("\t"); String rs=nt[0]; int freq=Integer.parseInt(nt[1]); RS2Frequency_hash.put(rs,freq); } RS2Frequency.close(); /** Homoid2HumanGene_hash **/ HashMap<String,String> Homoid2HumanGene_hash = new HashMap<String,String>(); BufferedReader Homoid2HumanGene = new BufferedReader(new InputStreamReader(new FileInputStream("Database/Homoid2HumanGene.txt"), "UTF-8")); line=""; while ((line = Homoid2HumanGene.readLine()) != null) { String nt[]=line.split("\t"); String homoid=nt[0]; String humangeneid=nt[1]; Homoid2HumanGene_hash.put(homoid,humangeneid); } Homoid2HumanGene.close(); /** Gene2Homoid.txt **/ BufferedReader Gene2Homoid = new BufferedReader(new InputStreamReader(new FileInputStream("Database/Gene2Homoid.txt"), "UTF-8")); line=""; while ((line = Gene2Homoid.readLine()) != null) { String nt[]=line.split("\t"); String geneid=nt[0]; String homoid=nt[1]; if(Homoid2HumanGene_hash.containsKey(homoid)) { if(!geneid.equals(Homoid2HumanGene_hash.get(homoid))) { Gene2HumanGene_hash.put(geneid,Homoid2HumanGene_hash.get(homoid)); } } } Gene2Homoid.close(); /** Variant2MostCorrespondingGene **/ BufferedReader Variant2MostCorrespondingGene = new BufferedReader(new InputStreamReader(new FileInputStream("Database/var2gene.txt"), "UTF-8")); line=""; while ((line = Variant2MostCorrespondingGene.readLine()) != null) { String nt[]=line.split("\t"); //4524 1801133 C677T String geneid=nt[0]; String rsid=nt[1]; String var=nt[2].toLowerCase(); Variant2MostCorrespondingGene_hash.put(var,geneid+"\t"+rsid); } Variant2MostCorrespondingGene.close(); BufferedReader RSandPosition2Seq = new BufferedReader(new InputStreamReader(new FileInputStream("lib/RS2tmVarForm.txt"), "UTF-8")); line=""; while ((line = RSandPosition2Seq.readLine()) != null) { String nt[]=line.split("\t"); //121908752 c SUB T 617 G if(nt.length>3) { String rs=nt[0]; String seq=nt[1]; String P=nt[4]; RSandPosition2Seq_hash.put(rs+"\t"+P,seq); } } RSandPosition2Seq.close(); } File folder = new File(InputFolder); File[] listOfFiles = folder.listFiles(); for (int i = 0; i < listOfFiles.length; i++) { if (listOfFiles[i].isFile()) { String InputFile = listOfFiles[i].getName(); File f = new File(OutputFolder+"/"+InputFile+".PubTator"); File f_BioC = new File(OutputFolder+"/"+InputFile+".BioC.XML"); if(f.exists() && !f.isDirectory()) { System.out.println(InputFolder+"/"+InputFile+" - Done. (The output file (PubTator) exists in output folder)"); } else if(f_BioC.exists() && !f_BioC.isDirectory()) { System.out.println(InputFolder+"/"+InputFile+" - Done. (The output file (BioC) exists in output folder)"); } else { /* * Mention recognition by CRF++ */ if(TrainTest.equals("Test") || TrainTest.equals("Test_FullText") || TrainTest.equals("Test_FullText") || TrainTest.equals("Train")) { /* * Format Check */ String Format = ""; String checkR=BC.BioCFormatCheck(InputFolder+"/"+InputFile); if(checkR.equals("BioC")) { Format = "BioC"; } else if(checkR.equals("PubTator")) { Format = "PubTator"; } else { System.out.println(checkR); System.exit(0); } System.out.print(InputFolder+"/"+InputFile+" - ("+Format+" format) : Processing ... \r"); /* * Pre-processing */ MentionRecognition MR= new MentionRecognition(); if(Format.equals("BioC")) { BC.BioC2PubTator(InputFolder+"/"+InputFile,"tmp/"+InputFile); MR.FeatureExtraction("tmp/"+InputFile,"tmp/"+InputFile+".data","tmp/"+InputFile+".location",TrainTest); } else if(Format.equals("PubTator")) { MR.FeatureExtraction(InputFolder+"/"+InputFile,"tmp/"+InputFile+".data","tmp/"+InputFile+".location",TrainTest); } if(TrainTest.equals("Test") || TrainTest.equals("Test_FullText")) { MR.CRF_test("tmp/"+InputFile+".data","tmp/"+InputFile+".output",TrainTest); } /* * CRF++ output --> PubTator */ PostProcessing PP = new PostProcessing(); { if(Format.equals("BioC")) { PP.toME("tmp/"+InputFile,"tmp/"+InputFile+".output","tmp/"+InputFile+".location","tmp/"+InputFile+".ME"); PP.toPostME("tmp/"+InputFile+".ME","tmp/"+InputFile+".PostME"); PP.toPostMEData("tmp/"+InputFile,"tmp/"+InputFile+".PostME","tmp/"+InputFile+".PostME.ml","tmp/"+InputFile+".PostME.data",TrainTest); } else if(Format.equals("PubTator")) { PP.toME(InputFolder+"/"+InputFile,"tmp/"+InputFile+".output","tmp/"+InputFile+".location","tmp/"+InputFile+".ME"); PP.toPostME("tmp/"+InputFile+".ME","tmp/"+InputFile+".PostME"); PP.toPostMEData(InputFolder+"/"+InputFile,"tmp/"+InputFile+".PostME","tmp/"+InputFile+".PostME.ml","tmp/"+InputFile+".PostME.data",TrainTest); } if(TrainTest.equals("Test") || TrainTest.equals("Test_FullText")) { PP.toPostMEoutput("tmp/"+InputFile+".PostME.data","tmp/"+InputFile+".PostME.output"); } else if(TrainTest.equals("Train")) { PP.toPostMEModel("tmp/"+InputFile+".PostME.data"); } /* * Post-processing */ if(TrainTest.equals("Test") || TrainTest.equals("Test_FullText")) { GeneMention = true; if(GeneMention == true) // MentionRecognition detect Gene mentions { PP.output2PubTator("tmp/"+InputFile+".PostME.ml","tmp/"+InputFile+".PostME.output","tmp/"+InputFile+".PostME","tmp/"+InputFile+".PubTator"); if(Format.equals("BioC")) { PP.Normalization("tmp/"+InputFile,"tmp/"+InputFile+".PubTator",OutputFolder+"/"+InputFile+".PubTator",DisplayRSnumOnly,HideMultipleResult,DisplayChromosome,DisplayRefSeq,DisplayGenomicRegion); } else if(Format.equals("PubTator")) { PP.Normalization(InputFolder+"/"+InputFile,"tmp/"+InputFile+".PubTator",OutputFolder+"/"+InputFile+".PubTator",DisplayRSnumOnly,HideMultipleResult,DisplayChromosome,DisplayRefSeq,DisplayGenomicRegion); } } else { PP.output2PubTator("tmp/"+InputFile+".PostME.ml","tmp/"+InputFile+".PostME.output","tmp/"+InputFile+".PostME",OutputFolder+"/"+InputFile+".PubTator"); } if(Format.equals("BioC")) { BC.PubTator2BioC_AppendAnnotation(OutputFolder+"/"+InputFile+".PubTator",InputFolder+"/"+InputFile,OutputFolder+"/"+InputFile+".BioC.XML"); } } } /* * Time stamp - last */ endTime = System.currentTimeMillis();//ending time totTime = endTime - startTime; System.out.println(InputFolder+"/"+InputFile+" - ("+Format+" format) : Processing Time:"+totTime/1000+"sec"); /* * remove tmp files */ if(DeleteTmp.toLowerCase().equals("true")) { String path="tmp"; File file = new File(path); File[] files = file.listFiles(); for (File ftmp:files) { if (ftmp.isFile() && ftmp.exists()) { if(ftmp.toString().matches("tmp."+InputFile+".*")) { ftmp.delete(); } } } } } else if(TrainTest.equals("Train_Mention")) { System.out.print(InputFolder+"/"+InputFile+" - Processing ... \r"); PostProcessing PP = new PostProcessing(); PP.toPostMEData(InputFolder+"/"+InputFile,"tmp/"+InputFile+".PostME","tmp/"+InputFile+".PostME.ml","tmp/"+InputFile+".PostME.data","Train"); /* * Time stamp - last */ endTime = System.currentTimeMillis();//ending time totTime = endTime - startTime; System.out.println(InputFolder+"/"+InputFile+" - Processing Time:"+totTime/1000+"sec"); } } } } } }
27,677
47.728873
3,587
java
null
tmVar3-main/src/tmVarlib/BioCConverter.java
// // tmVar - Java version // BioC Format Converter // package tmVarlib; import bioc.BioCAnnotation; import bioc.BioCCollection; import bioc.BioCDocument; import bioc.BioCLocation; import bioc.BioCPassage; import bioc.io.BioCDocumentWriter; import bioc.io.BioCFactory; import bioc.io.woodstox.ConnectorWoodstox; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import java.time.LocalDate; import java.time.ZoneId; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.xml.stream.XMLStreamException; import java.util.ArrayList; import java.util.HashMap; public class BioCConverter { /* * Contexts in BioC file */ public ArrayList<String> PMIDs=new ArrayList<String>(); // Type: PMIDs public ArrayList<ArrayList<String>> PassageNames = new ArrayList(); // PassageName public ArrayList<ArrayList<Integer>> PassageOffsets = new ArrayList(); // PassageOffset public ArrayList<ArrayList<String>> PassageContexts = new ArrayList(); // PassageContext public ArrayList<ArrayList<ArrayList<String>>> Annotations = new ArrayList(); // Annotation - GNormPlus public String BioCFormatCheck(String InputFile) throws IOException { ConnectorWoodstox connector = new ConnectorWoodstox(); BioCCollection collection = new BioCCollection(); try { collection = connector.startRead(new InputStreamReader(new FileInputStream(InputFile), "UTF-8")); } catch (UnsupportedEncodingException | FileNotFoundException | XMLStreamException e) { BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(InputFile), "UTF-8")); String line=""; String status=""; String Pmid = ""; boolean tiabs=false; Pattern patt = Pattern.compile("^([^\\|\\t]+)\\|([^\\|\\t]+)\\|(.*)$"); while ((line = br.readLine()) != null) { Matcher mat = patt.matcher(line); if(mat.find()) //Title|Abstract { if(Pmid.equals("")) { Pmid = mat.group(1); } else if(!Pmid.equals(mat.group(1))) { return "[Error]: "+InputFile+" - A blank is needed between "+Pmid+" and "+mat.group(1)+"."; } status = "tiabs"; tiabs = true; } else if (line.contains("\t")) //Annotation { } else if(line.length()==0) //Processing { if(status.equals("")) { if(Pmid.equals("")) { return "[Error]: "+InputFile+" - It's not either BioC or PubTator format."; } else { return "[Error]: "+InputFile+" - A redundant blank is after "+Pmid+"."; } } Pmid=""; status=""; } } br.close(); if(tiabs == false) { return "[Error]: "+InputFile+" - It's not either BioC or PubTator format."; } if(status.equals("")) { return "PubTator"; } else { return "[Error]: "+InputFile+" - The last column missed a blank."; } } return "BioC"; } public void BioC2PubTator(String input,String output) throws IOException, XMLStreamException { /* * BioC2PubTator */ HashMap<String, String> pmidlist = new HashMap<String, String>(); // check if appear duplicate pmids boolean duplicate = false; BufferedWriter PubTatorOutputFormat = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(output), "UTF-8")); ConnectorWoodstox connector = new ConnectorWoodstox(); BioCCollection collection = new BioCCollection(); collection = connector.startRead(new InputStreamReader(new FileInputStream(input), "UTF-8")); while (connector.hasNext()) { BioCDocument document = connector.next(); String PMID = document.getID(); if(pmidlist.containsKey(PMID)){System.out.println("\nError: duplicate pmid-"+PMID);duplicate = true;} else{pmidlist.put(PMID,"");} String Anno=""; int realpassage_offset=0; for (BioCPassage passage : document.getPassages()) { if(passage.getInfon("type").toLowerCase().equals("table")) { String temp=passage.getText().replaceAll(" ", ";"); temp=temp.replaceAll(";>;", " > "); PubTatorOutputFormat.write(PMID+"|"+passage.getInfon("type")+"|"+temp+"\n"); } else { String temp=passage.getText(); if(passage.getText().equals("")) { PubTatorOutputFormat.write(PMID+"|"+passage.getInfon("type")+"|"+"\n");//- No text - } else { PubTatorOutputFormat.write(PMID+"|"+passage.getInfon("type")+"|"+temp+"\n"); } } for (BioCAnnotation annotation : passage.getAnnotations()) { String Annoid = annotation.getInfon("identifier"); if(Annoid == null) { Annoid=annotation.getInfon("NCBI Gene"); } if(Annoid == null) { Annoid = annotation.getInfon("Identifier"); } String Annotype = annotation.getInfon("type"); int start = annotation.getLocations().get(0).getOffset(); start=start-(passage.getOffset()-realpassage_offset); int last = start + annotation.getLocations().get(0).getLength(); String AnnoMention=annotation.getText(); Anno=Anno+PMID+"\t"+start+"\t"+last+"\t"+AnnoMention+"\t"+Annotype+"\t"+Annoid+"\n"; } realpassage_offset=realpassage_offset+passage.getText().length()+1; } PubTatorOutputFormat.write(Anno+"\n"); } PubTatorOutputFormat.close(); if(duplicate == true){System.exit(0);} } public void PubTator2BioC(String input,String output) throws IOException, XMLStreamException { /* * PubTator2BioC */ String parser = BioCFactory.WOODSTOX; BioCFactory factory = BioCFactory.newFactory(parser); BioCDocumentWriter BioCOutputFormat = factory.createBioCDocumentWriter(new OutputStreamWriter(new FileOutputStream(output), "UTF-8")); BioCCollection biocCollection = new BioCCollection(); //time ZoneId zonedId = ZoneId.of( "America/Montreal" ); LocalDate today = LocalDate.now( zonedId ); biocCollection.setDate(today.toString()); biocCollection.setKey("BioC.key");//key biocCollection.setSource("tmVar");//source BioCOutputFormat.writeCollectionInfo(biocCollection); BufferedReader inputfile = new BufferedReader(new InputStreamReader(new FileInputStream(input), "UTF-8")); ArrayList<String> ParagraphType=new ArrayList<String>(); // Type: Title|Abstract ArrayList<String> ParagraphContent = new ArrayList<String>(); // Text ArrayList<String> annotations = new ArrayList<String>(); // Annotation String line; String Pmid=""; while ((line = inputfile.readLine()) != null) { Pattern patt = Pattern.compile("^([^\\|\\t]+)\\|([^\\|\\t]+)\\|(.*)$"); Matcher mat = patt.matcher(line); if(mat.find()) //Title|Abstract { ParagraphType.add(mat.group(2)); ParagraphContent.add(mat.group(3)); } else if (line.contains("\t")) //Annotation { String anno[]=line.split("\t"); annotations.add(anno[1]+"\t"+anno[2]+"\t"+anno[3]+"\t"+anno[4]+"\t"+anno[5]); } else if(line.length()==0) //Processing { BioCDocument biocDocument = new BioCDocument(); biocDocument.setID(Pmid); int startoffset=0; for(int i=0;i<ParagraphType.size();i++) { BioCPassage biocPassage = new BioCPassage(); Map<String, String> Infons = new HashMap<String, String>(); Infons.put("type", ParagraphType.get(i)); biocPassage.setInfons(Infons); biocPassage.setText(ParagraphContent.get(i)); biocPassage.setOffset(startoffset); startoffset=startoffset+ParagraphContent.get(i).length()+1; for(int j=0;j<annotations.size();j++) { String anno[]=annotations.get(j).split("\t"); if(Integer.parseInt(anno[0])<startoffset && Integer.parseInt(anno[0])>=startoffset-ParagraphContent.get(i).length()-1) { BioCAnnotation biocAnnotation = new BioCAnnotation(); Map<String, String> AnnoInfons = new HashMap<String, String>(); AnnoInfons.put("Identifier", anno[4]); AnnoInfons.put("type", anno[3]); biocAnnotation.setInfons(AnnoInfons); BioCLocation location = new BioCLocation(); location.setOffset(Integer.parseInt(anno[0])); location.setLength(Integer.parseInt(anno[1])-Integer.parseInt(anno[0])); biocAnnotation.setLocation(location); biocAnnotation.setText(anno[2]); biocPassage.addAnnotation(biocAnnotation); } } biocDocument.addPassage(biocPassage); } biocCollection.addDocument(biocDocument); ParagraphType.clear(); ParagraphContent.clear(); annotations.clear(); BioCOutputFormat.writeDocument(biocDocument); } } BioCOutputFormat.close(); inputfile.close(); } public void PubTator2BioC_AppendAnnotation(String inputPubTator,String inputBioc,String output) throws IOException, XMLStreamException { /* * PubTator2BioC */ //input: PubTator BufferedReader inputfile = new BufferedReader(new InputStreamReader(new FileInputStream(inputPubTator), "UTF-8")); HashMap<String, String> ParagraphType_hash = new HashMap<String, String>(); // Type: Title|Abstract HashMap<String, String> ParagraphContent_hash = new HashMap<String, String>(); // Text HashMap<String, String> annotations_hash = new HashMap<String, String>(); // Annotation String Annotation=""; String Pmid=""; String line=""; while ((line = inputfile.readLine()) != null) { Pattern patt = Pattern.compile("^([^\\|\\t]+)\\|([^\\|\\t]+)\\|(.*)$"); Matcher mat = patt.matcher(line); if(mat.find()) //Title|Abstract { Pmid=mat.group(1); ParagraphType_hash.put(Pmid,mat.group(2)); ParagraphContent_hash.put(Pmid,mat.group(3)); } else if (line.contains("\t")) //Annotation { if(Annotation.equals("")) { Annotation=line; } else { Annotation=Annotation+"\n"+line; } } else if(line.length()==0) //Processing { annotations_hash.put(Pmid,Annotation); Annotation=""; } } inputfile.close(); //output BioCDocumentWriter BioCOutputFormat = BioCFactory.newFactory(BioCFactory.WOODSTOX).createBioCDocumentWriter(new OutputStreamWriter(new FileOutputStream(output), "UTF-8")); BioCCollection biocCollection_input = new BioCCollection(); BioCCollection biocCollection_output = new BioCCollection(); //input: BioC ConnectorWoodstox connector = new ConnectorWoodstox(); biocCollection_input = connector.startRead(new InputStreamReader(new FileInputStream(inputBioc), "UTF-8")); BioCOutputFormat.writeCollectionInfo(biocCollection_input); while (connector.hasNext()) { int real_start_passage=0; BioCDocument document_output = new BioCDocument(); BioCDocument document_input = connector.next(); String PMID=document_input.getID(); document_output.setID(PMID); int annotation_count=0; for (BioCPassage passage_input : document_input.getPassages()) { String passage_input_Text = passage_input.getText(); BioCPassage passage_output = passage_input; //passage_output.clearAnnotations(); //clean the previous annotation for (BioCAnnotation annotation : passage_output.getAnnotations()) { annotation.setID(""+annotation_count); annotation_count++; } int start_passage=passage_input.getOffset(); int last_passage=passage_input.getOffset()+passage_input.getText().length(); if(annotations_hash.containsKey(PMID) && !annotations_hash.get(PMID).equals("")) { String Anno[]=annotations_hash.get(PMID).split("\\n"); for(int i=0;i<Anno.length;i++) { String An[]=Anno[i].split("\\t"); int start=Integer.parseInt(An[1]); int last=Integer.parseInt(An[2]); start = start + start_passage - real_start_passage; last = last + start_passage - real_start_passage; String mention=An[3]; String type=An[4]; String id=""; if(An.length>5) { id=An[5]; } if((start>=start_passage && start<last_passage)||(last>=start_passage && last<last_passage)) { BioCAnnotation biocAnnotation = new BioCAnnotation(); Map<String, String> AnnoInfons = new HashMap<String, String>(); AnnoInfons.put("Identifier", id); AnnoInfons.put("type", type); biocAnnotation.setInfons(AnnoInfons); /*redirect the offset*/ //location.setOffset(start); //location.setLength(last-start); String mention_tmp = mention.replaceAll("([^A-Za-z0-9@ ])", "\\\\$1"); Pattern patt = Pattern.compile("^(.*)("+mention_tmp+")(.*)$"); Matcher mat = patt.matcher(passage_input_Text); if(mat.find()) { String pre=mat.group(1); String men=mat.group(2); String post=mat.group(3); start=pre.length()+start_passage; BioCLocation location = new BioCLocation(); location.setOffset(start); location.setLength(men.length()); biocAnnotation.setLocation(location); biocAnnotation.setText(mention); biocAnnotation.setID(""+annotation_count); annotation_count++; passage_output.addAnnotation(biocAnnotation); men=men.replaceAll(".", "@"); passage_input_Text=pre+men+post; } } } } real_start_passage = real_start_passage + passage_input.getText().length() + 1; document_output.addPassage(passage_output); } biocCollection_output.addDocument(document_output); BioCOutputFormat.writeDocument(document_output); } BioCOutputFormat.close(); } public void BioCReaderWithAnnotation(String input) throws IOException, XMLStreamException { ConnectorWoodstox connector = new ConnectorWoodstox(); BioCCollection collection = new BioCCollection(); collection = connector.startRead(new InputStreamReader(new FileInputStream(input), "UTF-8")); /* * Per document */ while (connector.hasNext()) { BioCDocument document = connector.next(); PMIDs.add(document.getID()); ArrayList<String> PassageName= new ArrayList<String>(); // array of Passage name ArrayList<Integer> PassageOffset= new ArrayList<Integer>(); // array of Passage offset ArrayList<String> PassageContext= new ArrayList<String>(); // array of Passage context ArrayList<ArrayList<String>> AnnotationInPMID= new ArrayList(); // array of Annotations in the PassageName /* * Per Passage */ for (BioCPassage passage : document.getPassages()) { PassageName.add(passage.getInfon("type")); //Paragraph String txt = passage.getText(); if(txt.matches("[\t ]+")) { txt = txt.replaceAll(".","@"); } else { //if(passage.getInfon("type").toLowerCase().equals("table")) //{ // txt=txt.replaceAll(" ", "|"); //} txt = txt.replaceAll("ω","w"); txt = txt.replaceAll("μ","u"); txt = txt.replaceAll("κ","k"); txt = txt.replaceAll("α","a"); txt = txt.replaceAll("γ","g"); txt = txt.replaceAll("β","b"); txt = txt.replaceAll("×","x"); txt = txt.replaceAll("¹","1"); txt = txt.replaceAll("²","2"); txt = txt.replaceAll("°","o"); txt = txt.replaceAll("ö","o"); txt = txt.replaceAll("é","e"); txt = txt.replaceAll("à","a"); txt = txt.replaceAll("Á","A"); txt = txt.replaceAll("ε","e"); txt = txt.replaceAll("θ","O"); txt = txt.replaceAll("•","."); txt = txt.replaceAll("µ","u"); txt = txt.replaceAll("λ","r"); txt = txt.replaceAll("⁺","+"); txt = txt.replaceAll("ν","v"); txt = txt.replaceAll("ï","i"); txt = txt.replaceAll("ã","a"); txt = txt.replaceAll("≡","="); txt = txt.replaceAll("ó","o"); txt = txt.replaceAll("³","3"); txt = txt.replaceAll("〖","["); txt = txt.replaceAll("〗","]"); txt = txt.replaceAll("Å","A"); txt = txt.replaceAll("ρ","p"); txt = txt.replaceAll("ü","u"); txt = txt.replaceAll("ɛ","e"); txt = txt.replaceAll("č","c"); txt = txt.replaceAll("š","s"); txt = txt.replaceAll("ß","b"); txt = txt.replaceAll("═","="); txt = txt.replaceAll("£","L"); txt = txt.replaceAll("Ł","L"); txt = txt.replaceAll("ƒ","f"); txt = txt.replaceAll("ä","a"); txt = txt.replaceAll("–","-"); txt = txt.replaceAll("⁻","-"); txt = txt.replaceAll("〈","<"); txt = txt.replaceAll("〉",">"); txt = txt.replaceAll("χ","X"); txt = txt.replaceAll("Đ","D"); txt = txt.replaceAll("‰","%"); txt = txt.replaceAll("·","."); txt = txt.replaceAll("→",">"); txt = txt.replaceAll("←","<"); txt = txt.replaceAll("ζ","z"); txt = txt.replaceAll("π","p"); txt = txt.replaceAll("τ","t"); txt = txt.replaceAll("ξ","X"); txt = txt.replaceAll("η","h"); txt = txt.replaceAll("ø","0"); txt = txt.replaceAll("Δ","D"); txt = txt.replaceAll("∆","D"); txt = txt.replaceAll("∑","S"); txt = txt.replaceAll("Ω","O"); txt = txt.replaceAll("δ","d"); txt = txt.replaceAll("σ","s"); txt = txt.replaceAll("Φ","F"); //txt = txt.replaceAll("[^\\~\\!\\@\\#\\$\\%\\^\\&\\*\\(\\)\\_\\+\\{\\}\\|\\:\"\\<\\>\\?\\`\\-\\=\\[\\]\\;\\'\\,\\.\\/\\r\\n0-9a-zA-Z ]"," "); } if(passage.getText().equals("") || passage.getText().matches("[ ]+")) { PassageContext.add("-notext-"); //Context } else { PassageContext.add(txt); //Context } PassageOffset.add(passage.getOffset()); //Offset ArrayList<String> AnnotationInPassage= new ArrayList<String>(); // array of Annotations in the PassageName /* * Per Annotation : * start * last * mention * type * id */ for (BioCAnnotation Anno : passage.getAnnotations()) { int start = Anno.getLocations().get(0).getOffset()-passage.getOffset(); // start int last = start + Anno.getLocations().get(0).getLength(); // last String AnnoMention=Anno.getText(); // mention String Annotype = Anno.getInfon("type"); // type String Annoid=""; Map<String,String> Infons=Anno.getInfons(); for(String Infon :Infons.keySet()) { if(!Infon.toLowerCase().equals("type")) { if(Annoid.equals("")) { Annoid=Infons.get(Infon); } else { Annoid=Annoid+";"+Infons.get(Infon); } } } if(Annoid == "") { AnnotationInPassage.add(start+"\t"+last+"\t"+AnnoMention+"\t"+Annotype); //paragraph } else { AnnotationInPassage.add(start+"\t"+last+"\t"+AnnoMention+"\t"+Annotype+"\t"+Annoid); //paragraph } } AnnotationInPMID.add(AnnotationInPassage); } PassageNames.add(PassageName); PassageContexts.add(PassageContext); PassageOffsets.add(PassageOffset); Annotations.add(AnnotationInPMID); } } public void BioCOutput(String input,String output) throws IOException, XMLStreamException { BioCDocumentWriter BioCOutputFormat = BioCFactory.newFactory(BioCFactory.WOODSTOX).createBioCDocumentWriter(new OutputStreamWriter(new FileOutputStream(output), "UTF-8")); BioCCollection biocCollection_input = new BioCCollection(); BioCCollection biocCollection_output = new BioCCollection(); //input: BioC ConnectorWoodstox connector = new ConnectorWoodstox(); biocCollection_input = connector.startRead(new InputStreamReader(new FileInputStream(input), "UTF-8")); BioCOutputFormat.writeCollectionInfo(biocCollection_input); int i=0; //count for pmid while (connector.hasNext()) { BioCDocument document_output = new BioCDocument(); BioCDocument document_input = connector.next(); document_output.setID(document_input.getID()); int annotation_count=0; int j=0; //count for paragraph for (BioCPassage passage_input : document_input.getPassages()) { BioCPassage passage_output = passage_input; passage_output.clearAnnotations(); //clean the previous annotation int passage_Offset = passage_input.getOffset(); String passage_Text = passage_input.getText(); ArrayList<String> AnnotationInPassage = Annotations.get(i).get(j); for(int a=0;a<AnnotationInPassage.size();a++) { String Anno[]=AnnotationInPassage.get(a).split("\\t",-1); int start = Integer.parseInt(Anno[0]); int last = Integer.parseInt(Anno[1]); String mention = Anno[2]; String type = Anno[3]; BioCAnnotation biocAnnotation = new BioCAnnotation(); Map<String, String> AnnoInfons = new HashMap<String, String>(); AnnoInfons.put("type", type); String identifier=""; if(Anno.length==5){identifier=Anno[4];} if(type.equals("Gene")) { AnnoInfons.put("NCBI Gene", identifier); } else if(type.equals("Species")) { AnnoInfons.put("NCBI Taxonomy", identifier); } else { AnnoInfons.put("Identifier", identifier); } biocAnnotation.setInfons(AnnoInfons); BioCLocation location = new BioCLocation(); location.setOffset(start+passage_Offset); location.setLength(last-start); biocAnnotation.setLocation(location); biocAnnotation.setText(mention); biocAnnotation.setID(""+annotation_count); annotation_count++; passage_output.addAnnotation(biocAnnotation); } document_output.addPassage(passage_output); j++; } biocCollection_output.addDocument(document_output); BioCOutputFormat.writeDocument(document_output); i++; } BioCOutputFormat.close(); } }
21,618
33.370429
173
java
savina
savina-master/src/main/java/edu/rice/habanero/benchmarks/Benchmark.java
package edu.rice.habanero.benchmarks; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * @author <a href="http://shams.web.rice.edu/">Shams Imam</a> (shams@rice.edu) */ public abstract class Benchmark { //final Map<String, List<Double>> customAttrs = new HashMap<>(); protected void track(final String attrName, final double attrValue) { //if (!customAttrs.containsKey(attrName)) { //customAttrs.put(attrName, new ArrayList<>()); //} //customAttrs.get(attrName).add(attrValue); } public final String name() { return getClass().getSimpleName(); } //public final String runtimeInfo() { //final String javaVersion = System.getProperty("java.version"); //return "Java:" + javaVersion + "::Scala:2.11.0"; //} public abstract void initialize(String[] args) throws IOException; public abstract void printArgInfo(); public abstract void runIteration(); public abstract void cleanupIteration(boolean lastIteration, double execTimeMillis); }
1,131
26.609756
88
java
savina
savina-master/src/main/java/edu/rice/habanero/benchmarks/PseudoRandom.java
package edu.rice.habanero.benchmarks; /* * A simple random generator * which generates numbers in the range of 0-65535 and 0.0-1.0 * Added to improves comparability between programming languages. */ public class PseudoRandom { private long value; public PseudoRandom(long value) { this.value = value; } public PseudoRandom() { this.value = 74755; } public long nextLong() { value = ((value * 1309) + 13849) & 65535; return value; } public int nextInt() { return ((int) nextLong()); } public double nextDouble() { return 1.0 / (nextLong() + 1); } public int nextInt(int exclusive_max) { return nextInt() % exclusive_max; } }
742
20.228571
65
java
savina
savina-master/src/main/java/edu/rice/habanero/benchmarks/BenchmarkRunner.java
package edu.rice.habanero.benchmarks; import edu.rice.habanero.actors.AkkaActorState; import edu.rice.hj.runtime.config.HjSystemProperty; import java.util.*; /** * @author <a href="http://shams.web.rice.edu/">Shams Imam</a> (shams@rice.edu) */ public class BenchmarkRunner { //public static final String statDataOutputFormat = "%20s %20s: %9.3f \n"; //public static final String execTimeOutputFormat = "%20s %20s: %9.3f ms \n"; public static final String argOutputFormat = "%25s = %-10s \n"; //protected static final double tolerance = 0.20; //protected static int iterations = 12; //private static void parseArgs(final String[] args) throws Exception { //final String numWorkers = HjSystemProperty.numWorkers.getPropertyValue(); //if (numWorkers != null) { //System.setProperty("actors.corePoolSize", numWorkers); //System.setProperty("actors.maxPoolSize", numWorkers); //} //final int argLimit = args.length - 1; //for (int i = 0; i < argLimit; i++) { //final String argName = args[i]; //final String argValue = args[i + 1]; //if (argName.equalsIgnoreCase("-iter")) { //iterations = Integer.parseInt(argValue); //} //} //} public static void runBenchmark(final String[] args, final Benchmark benchmark) { try { //parseArgs(args); benchmark.initialize(args); } catch (final Exception e) { e.printStackTrace(System.err); System.exit(1); } final String benchmarkName = benchmark.name(); if (benchmarkName.contains("Akka")) { AkkaActorState.initialize(); } //System.out.println("Runtime: " + benchmark.runtimeInfo()); //System.out.println("Benchmark: " + benchmarkName); //System.out.println("Args: "); //benchmark.printArgInfo(); //System.out.println(); //System.out.printf(argOutputFormat, "Java Version", System.getProperty("java.version")); //System.out.printf(argOutputFormat, "O/S Version", System.getProperty("os.version")); //System.out.printf(argOutputFormat, "O/S Name", System.getProperty("os.name")); //System.out.printf(argOutputFormat, "O/S Arch", System.getProperty("os.arch")); //final List<Double> rawExecTimes = new ArrayList<>(iterations); { //System.out.println("Execution - Iterations: "); //for (int i = 0; i < iterations; i++) { //final long startTime = System.nanoTime(); benchmark.runIteration(); //final long endTime = System.nanoTime(); //final double execTimeMillis = (endTime - startTime) / 1e6; //rawExecTimes.add(execTimeMillis); //System.out.printf(execTimeOutputFormat, benchmark.name(), " Iteration-" + i, execTimeMillis); //benchmark.cleanupIteration(i + 1 == iterations, execTimeMillis); //} //System.out.println(); } //System.out.println(); //final Map<String, List<Double>> customAttrs = benchmark.customAttrs; //if (!customAttrs.isEmpty()) { //System.out.println("Attributes - Summary: "); //for (final Map.Entry<String, List<Double>> loopEntry : customAttrs.entrySet()) { //final String attrName = loopEntry.getKey(); //final List<Double> attrValues = loopEntry.getValue(); //final List<Double> sanitizedAttrValue = sanitize(attrValues, 0.30); //System.out.printf(statDataOutputFormat.trim(), benchmark.name(), " " + attrName, arithmeticMean(sanitizedAttrValue)); //System.out.printf(" [%3d of %3d values] \n", sanitizedAttrValue.size(), attrValues.size()); //} //} //Collections.sort(rawExecTimes); //final List<Double> execTimes = sanitize(rawExecTimes, tolerance); //System.out.println("Execution - Summary: "); //System.out.printf(argOutputFormat, "Total executions", rawExecTimes.size()); //System.out.printf(argOutputFormat, "Filtered executions", execTimes.size()); //System.out.printf(execTimeOutputFormat, benchmark.name(), " Best Time", execTimes.get(0)); //System.out.printf(execTimeOutputFormat, benchmark.name(), " Worst Time", execTimes.get(execTimes.size() - 1)); //System.out.printf(execTimeOutputFormat, benchmark.name(), " Median", median(execTimes)); //System.out.printf(execTimeOutputFormat, benchmark.name(), " Arith. Mean Time", arithmeticMean(execTimes)); //System.out.printf(execTimeOutputFormat, benchmark.name(), " Geo. Mean Time", geometricMean(execTimes)); //System.out.printf(execTimeOutputFormat, benchmark.name(), " Harmonic Mean Time", harmonicMean(execTimes)); //System.out.printf(execTimeOutputFormat, benchmark.name(), " Std. Dev Time", standardDeviation(execTimes)); //System.out.printf(execTimeOutputFormat, benchmark.name(), " Lower Confidence", confidenceLow(execTimes)); //System.out.printf(execTimeOutputFormat, benchmark.name(), " Higher Confidence", confidenceHigh(execTimes)); //System.out.printf(execTimeOutputFormat.trim() + " (%4.3f percent) \n", benchmark.name(), " Error Window", //confidenceHigh(execTimes) - arithmeticMean(execTimes), //100 * (confidenceHigh(execTimes) - arithmeticMean(execTimes)) / arithmeticMean(execTimes)); //System.out.printf(statDataOutputFormat, benchmark.name(), " Coeff. of Variation", coefficientOfVariation(execTimes)); //System.out.printf(statDataOutputFormat, benchmark.name(), " Skewness", skewness(execTimes)); //System.out.println(); } //public static List<Double> sanitize(final List<Double> rawList, final double tolerance) { //if (rawList.isEmpty()) { //return new ArrayList<>(0); //} //Collections.sort(rawList); //final int rawListSize = rawList.size(); //final List<Double> resultList = new ArrayList<>(); //final double median = rawList.get(rawListSize / 2); //final double allowedMin = (1 - tolerance) * median; //final double allowedMax = (1 + tolerance) * median; //for (final double loopVal : rawList) { //if (loopVal >= allowedMin && loopVal <= allowedMax) { //resultList.add(loopVal); //} //} //return resultList; //} //public static double arithmeticMean(final Collection<Double> execTimes) { //double sum = 0; //for (final double execTime : execTimes) { //sum += execTime; //} //return (sum / execTimes.size()); //} //public static double median(final List<Double> execTimes) { //if (execTimes.isEmpty()) { //return 0; //} //final int size = execTimes.size(); //final int middle = size / 2; //if (size % 2 == 1) { //return execTimes.get(middle); //} else { //return (execTimes.get(middle - 1) + execTimes.get(middle)) / 2.0; //} //} //public static double geometricMean(final Collection<Double> execTimes) { //double lgProd = 0; //for (final double execTime : execTimes) { //lgProd += Math.log10(execTime); //} //return Math.pow(10, lgProd / execTimes.size()); //} //public static double harmonicMean(final Collection<Double> execTimes) { //double denom = 0; //for (final double execTime : execTimes) { //denom += (1 / execTime); //} //return (execTimes.size() / denom); //} //public static double standardDeviation(final Collection<Double> execTimes) { //final double mean = arithmeticMean(execTimes); //double temp = 0; //for (final double execTime : execTimes) { //temp += ((mean - execTime) * (mean - execTime)); //} //return Math.sqrt(temp / execTimes.size()); //} //public static double coefficientOfVariation(final Collection<Double> execTimes) { //final double mean = arithmeticMean(execTimes); //final double sd = standardDeviation(execTimes); //return (sd / mean); //} //public static double confidenceLow(final Collection<Double> execTimes) { //final double mean = arithmeticMean(execTimes); //final double sd = standardDeviation(execTimes); //return mean - (1.96d * sd / Math.sqrt(execTimes.size())); //} //public static double confidenceHigh(final Collection<Double> execTimes) { //final double mean = arithmeticMean(execTimes); //final double sd = standardDeviation(execTimes); //return mean + (1.96d * sd / Math.sqrt(execTimes.size())); //} /** * Returns the sample Skewness measure of asymmetry of an array of numbers. Source: * http://socr.googlecode.com/svn/trunk/SOCR2.0/src/org/jfree/data/statistics/Statistics.java * * @return the sample Skewness measure of asymmetry of an array of numbers. */ //public static double skewness(final List<Double> execTimes) { //final double mean = arithmeticMean(execTimes); //final double sd = standardDeviation(execTimes); //double sum = 0.0; //int count = 0; //if (execTimes.size() > 1) { //for (final Double execTime : execTimes) { //final double current = execTime; //final double diff = current - mean; //sum = sum + diff * diff * diff; //count++; //} //return sum / ((count - 1) * sd * sd * sd); //} else { //return 0.0; //} //} }
9,927
39.688525
135
java
savina
savina-master/src/main/java/edu/rice/habanero/benchmarks/concdict/DictionaryConfig.java
package edu.rice.habanero.benchmarks.concdict; import edu.rice.habanero.benchmarks.BenchmarkRunner; import java.util.HashMap; import java.util.Map; /** * @author <a href="http://shams.web.rice.edu/">Shams Imam</a> (shams@rice.edu) */ public final class DictionaryConfig { protected static int NUM_ENTITIES = 20; protected static int NUM_MSGS_PER_WORKER = 10_000; protected static int WRITE_PERCENTAGE = 10; protected static int DATA_LIMIT = Integer.MAX_VALUE / 4_096; protected static Map<Integer, Integer> DATA_MAP = new HashMap<>(DATA_LIMIT); protected static boolean debug = false; protected static void parseArgs(final String[] args) { int i = 0; while (i < args.length) { final String loopOptionKey = args[i]; switch (loopOptionKey) { case "-e": i += 1; NUM_ENTITIES = Integer.parseInt(args[i]); break; case "-m": i += 1; NUM_MSGS_PER_WORKER = Integer.parseInt(args[i]); break; case "-w": i += 1; WRITE_PERCENTAGE = Integer.parseInt(args[i]); break; case "debug": case "verbose": debug = true; break; } i += 1; } for (int k = 0; k < DATA_LIMIT; k++) { DATA_MAP.put(k, k); } } protected static void printArgs() { System.out.printf(BenchmarkRunner.argOutputFormat, "Num Entities", NUM_ENTITIES); System.out.printf(BenchmarkRunner.argOutputFormat, "Message/Worker", NUM_MSGS_PER_WORKER); System.out.printf(BenchmarkRunner.argOutputFormat, "Write Percent", WRITE_PERCENTAGE); System.out.printf(BenchmarkRunner.argOutputFormat, "debug", debug); } protected static class WriteMessage { protected final Object sender; protected final int key; protected final int value; protected WriteMessage(final Object sender, final int key, final int value) { this.sender = sender; this.key = Math.abs(key) % DATA_LIMIT; this.value = value; } } protected static class ReadMessage { protected final Object sender; protected final int key; protected ReadMessage(final Object sender, final int key) { this.sender = sender; this.key = Math.abs(key) % DATA_LIMIT; } } protected static class ResultMessage { protected final Object sender; protected final int key; protected ResultMessage(final Object sender, final int key) { this.sender = sender; this.key = key; } } protected static class DoWorkMessage { protected static final DoWorkMessage ONLY = new DoWorkMessage(); private DoWorkMessage() { super(); } } protected static class EndWorkMessage { protected static final EndWorkMessage ONLY = new EndWorkMessage(); private EndWorkMessage() { super(); } } }
3,238
27.919643
98
java
savina
savina-master/src/main/java/edu/rice/habanero/benchmarks/fjcreate/ForkJoinConfig.java
package edu.rice.habanero.benchmarks.fjcreate; import edu.rice.habanero.benchmarks.BenchmarkRunner; /** * @author <a href="http://shams.web.rice.edu/">Shams Imam</a> (shams@rice.edu) */ public final class ForkJoinConfig { protected static int N = 40000; protected static int C = 1; protected static boolean debug = false; protected static void parseArgs(final String[] args) { int i = 0; while (i < args.length) { final String loopOptionKey = args[i]; switch (loopOptionKey) { case "-n": i += 1; N = Integer.parseInt(args[i]); break; case "-c": i += 1; C = Integer.parseInt(args[i]); break; case "-debug": case "-verbose": debug = true; break; } i += 1; } } protected static void printArgs() { System.out.printf(BenchmarkRunner.argOutputFormat, "N (num workers)", N); System.out.printf(BenchmarkRunner.argOutputFormat, "C (num channels)", C); System.out.printf(BenchmarkRunner.argOutputFormat, "debug", debug); } protected static void performComputation(final double theta) { final double sint = Math.sin(theta); final double res = sint * sint; //defeat dead code elimination if (res <= 0) { throw new IllegalStateException("Benchmark exited with unrealistic res value " + res); } } }
1,601
30.411765
98
java
savina
savina-master/src/main/java/edu/rice/habanero/benchmarks/facloc/FacilityLocationConfig.java
package edu.rice.habanero.benchmarks.facloc; import edu.rice.habanero.benchmarks.BenchmarkRunner; import edu.rice.habanero.benchmarks.PseudoRandom; import java.util.*; /** * @author <a href="http://shams.web.rice.edu/">Shams Imam</a> (shams@rice.edu) */ public final class FacilityLocationConfig { protected static int NUM_POINTS = 100_000; protected static double GRID_SIZE = 500.0; protected static double F = Math.sqrt(2) * GRID_SIZE; protected static double ALPHA = 2.0; protected static int CUTOFF_DEPTH = 3; protected static long SEED = 123456L; protected static int N = 40000; protected static int C = 1; protected static boolean debug = false; protected static void parseArgs(final String[] args) { int i = 0; while (i < args.length) { final String loopOptionKey = args[i]; if ("-n".equals(loopOptionKey)) { i += 1; NUM_POINTS = Integer.parseInt(args[i]); } else if ("-g".equals(loopOptionKey)) { i += 1; GRID_SIZE = java.lang.Double.parseDouble(args[i]); } else if ("-a".equals(loopOptionKey)) { i += 1; ALPHA = java.lang.Double.parseDouble(args[i]); } else if ("-s".equals(loopOptionKey)) { i += 1; SEED = java.lang.Long.parseLong(args[i]); } else if ("-c".equals(loopOptionKey)) { i += 1; CUTOFF_DEPTH = Integer.parseInt(args[i]); } else if ("-debug".equals(loopOptionKey) || "-verbose".equals(loopOptionKey)) { debug = true; } i += 1; } F = Math.sqrt(2) * GRID_SIZE; } protected static void printArgs() { System.out.printf(BenchmarkRunner.argOutputFormat, "Num points", NUM_POINTS); System.out.printf(BenchmarkRunner.argOutputFormat, "Grid size", GRID_SIZE); System.out.printf(BenchmarkRunner.argOutputFormat, "F", F); System.out.printf(BenchmarkRunner.argOutputFormat, "Alpha", ALPHA); System.out.printf(BenchmarkRunner.argOutputFormat, "Cut-off depth", CUTOFF_DEPTH); System.out.printf(BenchmarkRunner.argOutputFormat, "Seed", SEED); System.out.printf(BenchmarkRunner.argOutputFormat, "debug", debug); } protected static class Point { private static PseudoRandom r = new PseudoRandom(); protected static void setSeed(final long seed) { r = new PseudoRandom(seed); } protected static Point random(final double gridSize) { final double x = r.nextDouble() * gridSize; final double y = r.nextDouble() * gridSize; return new Point(x, y); } protected static Point findCenter(final Collection<Point> points) { double sumX = 0, sumY = 0; for (final Point point : points) { sumX += point.x; sumY += point.y; } final int numPoints = points.size(); final double avgX = sumX / numPoints; final double avgY = sumY / numPoints; return new Point(avgX, avgY); } protected final double x; protected final double y; public Point(final double x, final double y) { this.x = x; this.y = y; } public double getDistance(final Point p) { final double xDiff = p.x - x; final double yDiff = p.y - y; final double distance = Math.sqrt((xDiff * xDiff) + (yDiff * yDiff)); return distance; } @Override public String toString() { return String.format("(%5.2f, %5.2f)", x, y); } } protected static class Facility { public static List<Facility> split(final Facility f) { // split points into four categories @SuppressWarnings("unchecked") final Set<Point>[] pointSplit = new Set[]{ new HashSet<Point>(), new HashSet<Point>(), new HashSet<Point>(), new HashSet<Point>() }; final Point tempCenter = Point.findCenter(f.points); for (final Point loopPoint : f.points) { final double xDiff = loopPoint.x - tempCenter.x; final double yDiff = loopPoint.y - tempCenter.y; if (xDiff > 0 && yDiff > 0) { pointSplit[0].add(loopPoint); } else if (xDiff < 0 && yDiff > 0) { pointSplit[1].add(loopPoint); } else if (xDiff < 0 && yDiff < 0) { pointSplit[2].add(loopPoint); } else { pointSplit[3].add(loopPoint); } } if (debug) { System.out.println( "split: " + f.points.size() + " into " + pointSplit[0].size() + ", " + pointSplit[1].size() + ", " + pointSplit[2].size() + " and " + pointSplit[3].size()); } // create new facilities final Facility f1 = makeFacility(pointSplit[0]); final Facility f2 = makeFacility(pointSplit[1]); final Facility f3 = makeFacility(pointSplit[2]); final Facility f4 = makeFacility(pointSplit[3]); return Arrays.asList(f1, f2, f3, f4); } private static Facility makeFacility(final Collection<Point> points) { final Point newCenter = Point.findCenter(points); final Facility newFacility = new Facility(newCenter); for (final Point loopPoint : points) { newFacility.addPoint(loopPoint); } return newFacility; } public final Point center; private double distance = 0.0; private double maxDistance = 0.0; private Set<Point> points = new HashSet<Point>(); protected Facility(final Point center) { this.center = center; } public void addPoint(final Point p) { final double d = center.getDistance(p); if (d > maxDistance) { maxDistance = d; } distance += d; points.add(p); } public int numPoints() { return points.size(); } public double getTotalDistance() { return distance; } @Override public String toString() { return "Facility{center: " + center + ", distance: " + distance + ", num-pts: " + points.size() + "}"; } } protected static class Box { final double x1; final double y1; final double x2; final double y2; protected Box(final double x1, final double y1, final double x2, final double y2) { this.x1 = x1; this.y1 = y1; this.x2 = x2; this.y2 = y2; } public boolean contains(final Point p) { return (x1 <= p.x && y1 <= p.y && p.x <= x2 && p.y <= y2); } public Point midPoint() { return new Point((x1 + x2) / 2, (y1 + y2) / 2); } } protected static interface Position { int UNKNOWN = -2; int ROOT = -1; int TOP_LEFT = 0; int TOP_RIGHT = 1; int BOT_LEFT = 2; int BOT_RIGHT = 3; } }
7,529
32.318584
117
java
savina
savina-master/src/main/java/edu/rice/habanero/benchmarks/bitonicsort/BitonicSortConfig.java
package edu.rice.habanero.benchmarks.bitonicsort; import edu.rice.habanero.benchmarks.BenchmarkRunner; /** * @author <a href="http://shams.web.rice.edu/">Shams Imam</a> (shams@rice.edu) */ public final class BitonicSortConfig { protected static int N = 4_096; // data size, must be power of 2 protected static long M = 1L << 60; // max value protected static long S = 2_048; // seed for random number generator protected static boolean debug = false; protected static void parseArgs(final String[] args) { int i = 0; while (i < args.length) { final String loopOptionKey = args[i]; switch (loopOptionKey) { case "-n": i += 1; N = Integer.parseInt(args[i]); break; case "-m": i += 1; M = Long.parseLong(args[i]); break; case "-s": i += 1; S = Long.parseLong(args[i]); break; case "-debug": case "-verbose": debug = true; break; } i += 1; } } protected static void printArgs() { System.out.printf(BenchmarkRunner.argOutputFormat, "N (num values)", N); System.out.printf(BenchmarkRunner.argOutputFormat, "M (max value)", M); System.out.printf(BenchmarkRunner.argOutputFormat, "S (seed)", S); System.out.printf(BenchmarkRunner.argOutputFormat, "debug", debug); } }
1,603
32.416667
80
java
savina
savina-master/src/main/java/edu/rice/habanero/benchmarks/nqueenk/NQueensConfig.java
package edu.rice.habanero.benchmarks.nqueenk; import edu.rice.habanero.benchmarks.BenchmarkRunner; /** * @author <a href="http://shams.web.rice.edu/">Shams Imam</a> (shams@rice.edu) */ public final class NQueensConfig { protected static final long[] SOLUTIONS = { 1, 0, 0, 2, 10, /* 5 */ 4, 40, 92, 352, 724, /* 10 */ 2680, 14200, 73712, 365596, 2279184, /* 15 */ 14772512, 95815104, 666090624, 4968057848L, 39029188884L, /* 20 */ }; private static final int MAX_SOLUTIONS = SOLUTIONS.length; protected static int NUM_WORKERS = 20; protected static int SIZE = 12; protected static int THRESHOLD = 4; protected static int PRIORITIES = 10; protected static int SOLUTIONS_LIMIT = 1_500_000; protected static boolean debug = false; protected static void parseArgs(final String[] args) { int i = 0; while (i < args.length) { final String loopOptionKey = args[i]; switch (loopOptionKey) { case "-n": i += 1; SIZE = Math.max(1, Math.min(Integer.parseInt(args[i]), MAX_SOLUTIONS)); break; case "-t": i += 1; THRESHOLD = Math.max(1, Math.min(Integer.parseInt(args[i]), MAX_SOLUTIONS)); break; case "-w": i += 1; NUM_WORKERS = Integer.parseInt(args[i]); break; case "-s": i += 1; SOLUTIONS_LIMIT = Integer.parseInt(args[i]); break; case "-p": i += 1; final int priority = Integer.parseInt(args[i]); final int maxPriority = MessagePriority.values().length - 1; PRIORITIES = Math.max(1, Math.min(priority, maxPriority)); break; case "-debug": case "-verbose": debug = true; break; } i += 1; } } protected static void printArgs() { System.out.printf(BenchmarkRunner.argOutputFormat, "Num Workers", NUM_WORKERS); System.out.printf(BenchmarkRunner.argOutputFormat, "Size", SIZE); System.out.printf(BenchmarkRunner.argOutputFormat, "Max Solutions", SOLUTIONS_LIMIT); System.out.printf(BenchmarkRunner.argOutputFormat, "Threshold", THRESHOLD); System.out.printf(BenchmarkRunner.argOutputFormat, "Priorities", PRIORITIES); System.out.printf(BenchmarkRunner.argOutputFormat, "debug", debug); } /* * <a> contains array of <n> queen positions. Returns 1 * if none of the queens conflict, and returns 0 otherwise. */ protected static boolean boardValid(final int n, final int[] a) { int i, j; int p, q; for (i = 0; i < n; i++) { p = a[i]; for (j = (i + 1); j < n; j++) { q = a[j]; if (q == p || q == p - (j - i) || q == p + (j - i)) { return false; } } } return true; } public enum MessagePriority { P00, P01, P02, P03, P04, P05, P06, P07, P08, P09, P10, P11, P12, P13, P14, P15, P16, P17, P18, P19, P20, P21, P22, P23, P24, P25, P26, P27, P28, P29, P_LOWEST } protected static class WorkMessage { public final int priority; public final int[] data; public final int depth; public WorkMessage(final int priority, final int[] data, final int depth) { this.priority = Math.min(PRIORITIES - 1, Math.max(0, priority)); this.data = data; this.depth = depth; } } protected static final class DoneMessage { protected static DoneMessage ONLY = new DoneMessage(); private DoneMessage() { super(); } } protected static final class ResultMessage { static ResultMessage ONLY = new ResultMessage(); protected ResultMessage() { super(); } } protected static final class StopMessage { protected static StopMessage ONLY = new StopMessage(); private StopMessage() { super(); } } }
4,818
26.073034
96
java
savina
savina-master/src/main/java/edu/rice/habanero/benchmarks/trapezoid/TrapezoidalConfig.java
package edu.rice.habanero.benchmarks.trapezoid; import edu.rice.habanero.benchmarks.BenchmarkRunner; /** * @author <a href="http://shams.web.rice.edu/">Shams Imam</a> (shams@rice.edu) */ public final class TrapezoidalConfig { protected static int N = 10_000_000; // num pieces protected static int W = 100; // num workers protected static double L = 1; // left end-point protected static double R = 5; // right end-point protected static boolean debug = false; protected static void parseArgs(final String[] args) { int i = 0; while (i < args.length) { final String loopOptionKey = args[i]; switch (loopOptionKey) { case "-n": i += 1; N = Integer.parseInt(args[i]); break; case "-w": i += 1; W = Integer.parseInt(args[i]); break; case "-l": i += 1; L = Double.parseDouble(args[i]); break; case "-r": i += 1; R = Double.parseDouble(args[i]); break; case "-debug": case "-verbose": debug = true; break; } i += 1; } } protected static void printArgs() { System.out.printf(BenchmarkRunner.argOutputFormat, "N (num trapezoids)", N); System.out.printf(BenchmarkRunner.argOutputFormat, "W (num workers)", W); System.out.printf(BenchmarkRunner.argOutputFormat, "L (left end-point)", L); System.out.printf(BenchmarkRunner.argOutputFormat, "R (right end-point)", R); System.out.printf(BenchmarkRunner.argOutputFormat, "debug", debug); } protected static double fx(final double x) { final double a = Math.sin(Math.pow(x, 3) - 1); final double b = x + 1; final double c = a / b; final double d = Math.sqrt(1 + Math.exp(Math.sqrt(2 * x))); final double r = c * d; return r; } protected static final class WorkMessage { final double l; final double r; final double h; public WorkMessage(final double l, final double r, final double h) { this.l = l; this.r = r; this.h = h; } } protected static final class ResultMessage { public final double result; public final int workerId; public ResultMessage(final double result, final int workerId) { this.result = result; this.workerId = workerId; } } }
2,722
30.662791
85
java
savina
savina-master/src/main/java/edu/rice/habanero/benchmarks/radixsort/RadixSortConfig.java
package edu.rice.habanero.benchmarks.radixsort; import edu.rice.habanero.benchmarks.BenchmarkRunner; /** * @author <a href="http://shams.web.rice.edu/">Shams Imam</a> (shams@rice.edu) */ public final class RadixSortConfig { protected static int N = 100_000; // data size protected static long M = 1L << 60; // max value protected static long S = 2_048; // seed for random number generator protected static boolean debug = false; protected static void parseArgs(final String[] args) { int i = 0; while (i < args.length) { final String loopOptionKey = args[i]; switch (loopOptionKey) { case "-n": i += 1; N = Integer.parseInt(args[i]); break; case "-m": i += 1; M = Long.parseLong(args[i]); break; case "-s": i += 1; S = Long.parseLong(args[i]); break; case "-debug": case "-verbose": debug = true; break; } i += 1; } } protected static void printArgs() { System.out.printf(BenchmarkRunner.argOutputFormat, "N (num values)", N); System.out.printf(BenchmarkRunner.argOutputFormat, "M (max value)", M); System.out.printf(BenchmarkRunner.argOutputFormat, "S (seed)", S); System.out.printf(BenchmarkRunner.argOutputFormat, "debug", debug); } }
1,581
31.958333
80
java
savina
savina-master/src/main/java/edu/rice/habanero/benchmarks/astar/GuidedSearchConfig.java
package edu.rice.habanero.benchmarks.astar; import edu.rice.habanero.benchmarks.BenchmarkRunner; import java.util.*; import java.util.concurrent.atomic.AtomicReference; /** * @author <a href="http://shams.web.rice.edu/">Shams Imam</a> (shams@rice.edu) */ public final class GuidedSearchConfig { protected static final int PRIORITY_GRANULARITY = 8; protected static int NUM_WORKERS = 20; protected static int GRID_SIZE = 30; protected static int PRIORITIES = 30; protected static int THRESHOLD = 1_024; protected static boolean debug = false; private static Map<Integer, GridNode> allNodes = null; protected static void parseArgs(final String[] args) { int i = 0; while (i < args.length) { final String loopOptionKey = args[i]; switch (loopOptionKey) { case "-w": i += 1; NUM_WORKERS = Integer.parseInt(args[i]); break; case "-t": i += 1; THRESHOLD = Integer.parseInt(args[i]); break; case "-g": i += 1; final int userInput = Integer.parseInt(args[i]); final int allowedMax = (MessagePriority.values().length - 1) * PRIORITY_GRANULARITY; GRID_SIZE = Math.min(userInput, allowedMax); break; case "-p": i += 1; final int priority = Integer.parseInt(args[i]); final int maxPriority = MessagePriority.values().length - 1; PRIORITIES = Math.max(1, Math.min(priority, maxPriority)); break; case "-debug": case "-verbose": debug = true; break; } i += 1; } initializeData(); } protected static void printArgs() { System.out.printf(BenchmarkRunner.argOutputFormat, "Num Workers", NUM_WORKERS); System.out.printf(BenchmarkRunner.argOutputFormat, "Grid Size", GRID_SIZE); System.out.printf(BenchmarkRunner.argOutputFormat, "Priorities", PRIORITIES); System.out.printf(BenchmarkRunner.argOutputFormat, "Threshold", THRESHOLD); System.out.printf(BenchmarkRunner.argOutputFormat, "Granularity", PRIORITY_GRANULARITY); System.out.printf(BenchmarkRunner.argOutputFormat, "debug", debug); } protected static void initializeData() { if (allNodes == null) { allNodes = new HashMap<>(GRID_SIZE * GRID_SIZE * GRID_SIZE); int id = 0; for (int i = 0; i < GRID_SIZE; i++) { for (int j = 0; j < GRID_SIZE; j++) { for (int k = 0; k < GRID_SIZE; k++) { final GridNode gridNode = new GridNode(id, i, j, k); allNodes.put(gridNode.id, gridNode); id++; } } } final Random random = new Random(123456L); for (final GridNode gridNode : allNodes.values()) { int iterCount = 0; int neighborCount = 0; for (int i = 0; i < 2; i++) { for (int j = 0; j < 2; j++) { for (int k = 0; k < 2; k++) { iterCount++; if (iterCount == 1 || iterCount == 8) { continue; } final boolean addNeighbor = (iterCount == 7 && neighborCount == 0) || random.nextBoolean(); if (addNeighbor) { final int newI = Math.min(GRID_SIZE - 1, gridNode.i + i); final int newJ = Math.min(GRID_SIZE - 1, gridNode.j + j); final int newK = Math.min(GRID_SIZE - 1, gridNode.k + k); final int newId = (GRID_SIZE * GRID_SIZE * newI) + (GRID_SIZE * newJ) + newK; final GridNode newNode = allNodes.get(newId); if (gridNode.addNeighbor(newNode)) { neighborCount++; } } } } } } } // clear distance and parent values for (final GridNode gridNode : allNodes.values()) { gridNode.distanceFromRoot = gridNode.id == 0 ? 0 : -1; gridNode.parentInPath.set(null); } } protected static int nodesProcessed() { int nodesProcessed = 1; for (final GridNode gridNode : allNodes.values()) { if (gridNode.parentInPath.get() != null) { nodesProcessed++; } } return nodesProcessed; } protected static boolean validate() { GridNode parentNode = targetNode(); while (parentNode.parentInPath.get() != null) { parentNode = parentNode.parentInPath.get(); } final GridNode rootNode = allNodes.get(0); return (parentNode == rootNode); } protected static int priority(final GridNode gridNode) { final int availablePriorities = PRIORITIES; final int distDiff = Math.max(GRID_SIZE - gridNode.i, Math.max(GRID_SIZE - gridNode.j, GRID_SIZE - gridNode.k)); final int priorityUnit = distDiff / PRIORITY_GRANULARITY; final int resultPriority = Math.abs(availablePriorities - priorityUnit); return resultPriority; } protected static GridNode originNode() { return allNodes.get(0); } protected static GridNode targetNode() { final int axisVal = (int) (0.80 * GRID_SIZE); final int targetId = (axisVal * GRID_SIZE * GRID_SIZE) + (axisVal * GRID_SIZE) + axisVal; final GridNode gridNode = allNodes.get(targetId); return gridNode; } protected static void busyWait() { for (int i = 0; i < 100; i++) { Math.random(); } } public enum MessagePriority { P00, P01, P02, P03, P04, P05, P06, P07, P08, P09, P10, P11, P12, P13, P14, P15, P16, P17, P18, P19, P20, P21, P22, P23, P24, P25, P26, P27, P28, P29, P30, P31, } protected static final class GridNode { public final int id; public final int i; public final int j; public final int k; private final List<GridNode> neighbors; private final AtomicReference<GridNode> parentInPath; // fields used in computing distance private int distanceFromRoot; public GridNode(final int id, final int i, final int j, final int k) { this.id = id; this.i = i; this.j = j; this.k = k; this.neighbors = new ArrayList<>(); distanceFromRoot = id == 0 ? 0 : -1; parentInPath = new AtomicReference<>(null); } private boolean addNeighbor(final GridNode node) { if (node == this) { return false; } if (!neighbors.contains(node)) { neighbors.add(node); return true; } return false; } protected int numNeighbors() { return neighbors.size(); } protected GridNode neighbor(final int n) { return neighbors.get(n); } protected boolean setParent(final GridNode node) { final boolean success = this.parentInPath.compareAndSet(null, node); if (success) { this.distanceFromRoot = node.distanceFromRoot + (int) distanceFrom(node); } return success; } protected double distanceFrom(final GridNode node) { final int iDiff = i - node.i; final int jDiff = j - node.j; final int kDiff = k - node.k; return Math.sqrt((iDiff * iDiff) + (jDiff * jDiff) + (kDiff * kDiff)); } } protected static class WorkMessage { public final GridNode node; public final GridNode target; public final int priority; public WorkMessage(final GridNode node, final GridNode target) { this.node = node; this.target = target; this.priority = priority(node); } } protected static class ReceivedMessage { protected static ReceivedMessage ONLY = new ReceivedMessage(); private ReceivedMessage() { super(); } } protected static class DoneMessage { protected static DoneMessage ONLY = new DoneMessage(); private DoneMessage() { super(); } } protected static class StopMessage { protected static StopMessage ONLY = new StopMessage(); private StopMessage() { super(); } } }
9,372
30.139535
120
java
savina
savina-master/src/main/java/edu/rice/habanero/benchmarks/sor/SucOverRelaxConfig.java
package edu.rice.habanero.benchmarks.sor; import edu.rice.habanero.benchmarks.BenchmarkRunner; import edu.rice.habanero.benchmarks.PseudoRandom; /** * @author <a href="http://shams.web.rice.edu/">Shams Imam</a> (shams@rice.edu) */ public final class SucOverRelaxConfig { // ORIGINAL val REF_VAL = Array[Double](0.498574406322512, 1.1234778980135105, 1.9954895063582696) protected static final double[] REF_VAL = { 0.000003189420084871275, 0.001846644602759566, 0.0032099996270638005, 0.0050869220175413146, 0.008496328291240363, 0.016479973604143234, 0.026575660248076397, 1.026575660248076397, 2.026575660248076397, 3.026575660248076397}; protected static final int[] DATA_SIZES = {20, 80, 100, 120, 150, 200, 250, 300, 350, 400}; protected static final int JACOBI_NUM_ITER = 100; protected static final double OMEGA = 1.25; protected static final long RANDOM_SEED = 10101010; protected static int N = 0; protected static boolean debug = false; protected static void parseArgs(final String[] args) { int i = 0; while (i < args.length) { final String loopOptionKey = args[i]; switch (loopOptionKey) { case "-n": i += 1; N = Integer.parseInt(args[i]); break; case "-debug": case "-verbose": debug = true; break; } i += 1; } } protected static void printArgs() { System.out.printf(BenchmarkRunner.argOutputFormat, "N (input size)", N); System.out.printf(BenchmarkRunner.argOutputFormat, "Data size", DATA_SIZES[N]); System.out.printf(BenchmarkRunner.argOutputFormat, "debug", debug); } protected static void performComputation(final double theta) { final double sint = Math.sin(theta); final double res = sint * sint; //defeat dead code elimination if (res <= 0) { throw new IllegalStateException("Benchmark exited with unrealistic res value " + res); } } protected static PseudoRandom R = null; protected static double[][] A = null; protected static void initialize() { R = resetRandomGenerator(); final int dataSize = SucOverRelaxConfig.DATA_SIZES[SucOverRelaxConfig.N]; A = randomMatrix(dataSize, dataSize); } protected static PseudoRandom resetRandomGenerator() { return new PseudoRandom(RANDOM_SEED); } protected static double[][] randomMatrix(final int M, final int N) { final double[][] A = new double[M][N]; for (int i = 0; i < M; i++) { for (int j = 0; j < N; j++) { A[i][j] = R.nextDouble() * 1e-6; } } return A; } protected static void jgfValidate(final double gTotal, final int size) { final double dev = Math.abs(gTotal - REF_VAL[size]); if (dev > 1.0e-12) { System.out.println("Validation failed"); System.out.println("Gtotal = " + gTotal + " " + REF_VAL[size] + " " + dev + " " + size); } else { System.out.println("Validation OK!"); } } }
3,356
32.909091
103
java
savina
savina-master/src/main/java/edu/rice/habanero/benchmarks/recmatmul/MatMulConfig.java
package edu.rice.habanero.benchmarks.recmatmul; import edu.rice.habanero.benchmarks.BenchmarkRunner; /** * @author <a href="http://shams.web.rice.edu/">Shams Imam</a> (shams@rice.edu) */ public final class MatMulConfig { protected static int NUM_WORKERS = 20; protected static int DATA_LENGTH = 1_024; protected static int BLOCK_THRESHOLD = 16_384; protected static int PRIORITIES = 10; protected static boolean debug = false; protected static double[][] A = null; protected static double[][] B = null; protected static double[][] C = null; protected static void parseArgs(final String[] args) { int i = 0; while (i < args.length) { final String loopOptionKey = args[i]; switch (loopOptionKey) { case "-n": i += 1; DATA_LENGTH = Integer.parseInt(args[i]); break; case "-t": i += 1; BLOCK_THRESHOLD = Integer.parseInt(args[i]); break; case "-w": i += 1; NUM_WORKERS = Integer.parseInt(args[i]); break; case "-p": i += 1; final int priority = Integer.parseInt(args[i]); final int maxPriority = MessagePriority.values().length - 1; PRIORITIES = Math.max(1, Math.min(priority, maxPriority)); break; case "-debug": case "-verbose": debug = true; break; } i += 1; } initializeData(); } protected static void printArgs() { System.out.printf(BenchmarkRunner.argOutputFormat, "Num Workers", NUM_WORKERS); System.out.printf(BenchmarkRunner.argOutputFormat, "Data length", DATA_LENGTH); System.out.printf(BenchmarkRunner.argOutputFormat, "Threshold", BLOCK_THRESHOLD); System.out.printf(BenchmarkRunner.argOutputFormat, "Priorities", PRIORITIES); System.out.printf(BenchmarkRunner.argOutputFormat, "debug", debug); } protected static void initializeData() { A = null; B = null; C = null; System.gc(); System.gc(); System.gc(); A = new double[DATA_LENGTH][DATA_LENGTH]; B = new double[DATA_LENGTH][DATA_LENGTH]; C = new double[DATA_LENGTH][DATA_LENGTH]; for (int i = 0; i < DATA_LENGTH; i++) { for (int j = 0; j < DATA_LENGTH; j++) { A[i][j] = i; B[i][j] = j; } } } protected static boolean valid() { for (int i = 0; i < DATA_LENGTH; i++) { for (int j = 0; j < DATA_LENGTH; j++) { final double actual = C[i][j]; final double expected = 1.0 * DATA_LENGTH * i * j; if (Double.compare(actual, expected) != 0) { return false; } } } return true; } public enum MessagePriority { P00, P01, P02, P03, P04, P05, P06, P07, P08, P09, P10, P11, P12, P13, P14, P15, P16, P17, P18, P19, P20, P21, P22, P23, P24, P25, P26, P27, P28, P29, P_LOWEST } protected static class WorkMessage { public final int priority; public final int srA; public final int scA; public final int srB; public final int scB; public final int srC; public final int scC; public final int numBlocks; public final int dim; public WorkMessage( final int priority, final int srA, final int scA, final int srB, final int scB, final int srC, final int scC, final int numBlocks, final int dim) { this.priority = priority; this.srA = srA; this.scA = scA; this.srB = srB; this.scB = scB; this.srC = srC; this.scC = scC; this.numBlocks = numBlocks; this.dim = dim; } } protected static class DoneMessage { protected static DoneMessage ONLY = new DoneMessage(); private DoneMessage() { super(); } } protected static class StopMessage { protected static StopMessage ONLY = new StopMessage(); private StopMessage() { super(); } } }
4,792
26.232955
89
java
savina
savina-master/src/main/java/edu/rice/habanero/benchmarks/quicksort/QuickSortConfig.java
package edu.rice.habanero.benchmarks.quicksort; import edu.rice.habanero.benchmarks.BenchmarkRunner; import edu.rice.habanero.benchmarks.PseudoRandom; import java.util.ArrayList; import java.util.List; /** * @author <a href="http://shams.web.rice.edu/">Shams Imam</a> (shams@rice.edu) */ public final class QuickSortConfig { protected static int N = 1_000_000; // data size protected static long M = 1L << 60; // max value protected static long T = 2_048; // threshold to perform sort sequentially protected static long S = 1_024; // seed for random number generator protected static boolean debug = false; protected static void parseArgs(final String[] args) { int i = 0; while (i < args.length) { final String loopOptionKey = args[i]; switch (loopOptionKey) { case "-n": i += 1; N = Integer.parseInt(args[i]); break; case "-m": i += 1; M = Long.parseLong(args[i]); break; case "-t": i += 1; T = Long.parseLong(args[i]); break; case "-s": i += 1; S = Long.parseLong(args[i]); break; case "-debug": case "-verbose": debug = true; break; } i += 1; } } protected static void printArgs() { System.out.printf(BenchmarkRunner.argOutputFormat, "N (num values)", N); System.out.printf(BenchmarkRunner.argOutputFormat, "M (max value)", M); System.out.printf(BenchmarkRunner.argOutputFormat, "T (sequential cutoff)", S); System.out.printf(BenchmarkRunner.argOutputFormat, "S (seed)", S); System.out.printf(BenchmarkRunner.argOutputFormat, "debug", debug); } protected static List<Long> quicksortSeq(final List<Long> data) { final int dataLength = data.size(); if (dataLength < 2) { return data; } final long pivot = data.get(dataLength / 2); final List<Long> leftUnsorted = filterLessThan(data, pivot); final List<Long> leftSorted = quicksortSeq(leftUnsorted); final List<Long> equalElements = filterEqualsTo(data, pivot); final List<Long> rightUnsorted = filterGreaterThan(data, pivot); final List<Long> rightSorted = quicksortSeq(rightUnsorted); final List<Long> sortedArray = new ArrayList<>(dataLength); sortedArray.addAll(leftSorted); sortedArray.addAll(equalElements); sortedArray.addAll(rightSorted); return sortedArray; } protected static List<Long> filterLessThan(final List<Long> data, final long pivot) { final int dataLength = data.size(); final List<Long> result = new ArrayList<>(dataLength); for (final Long loopItem : data) { if (loopItem < pivot) { result.add(loopItem); } } return result; } protected static List<Long> filterEqualsTo(final List<Long> data, final long pivot) { final int dataLength = data.size(); final List<Long> result = new ArrayList<>(dataLength); for (final Long loopItem : data) { if (loopItem == pivot) { result.add(loopItem); } } return result; } protected static List<Long> filterBetween(final List<Long> data, final long leftPivot, final long rightPivot) { final int dataLength = data.size(); final List<Long> result = new ArrayList<>(dataLength); for (final Long loopItem : data) { if ((loopItem >= leftPivot) && (loopItem <= rightPivot)) { result.add(loopItem); } } return result; } protected static List<Long> filterGreaterThan(final List<Long> data, final long pivot) { final int dataLength = data.size(); final List<Long> result = new ArrayList<>(dataLength); for (final Long loopItem : data) { if (loopItem > pivot) { result.add(loopItem); } } return result; } protected static void checkSorted(final List<Long> data) { final int length = data.size(); if (length != N) { throw new RuntimeException("result is not correct length, expected: " + N + ", found: " + length); } long loopValue = data.get(0); int nextIndex = 1; while (nextIndex < length) { final long temp = data.get(nextIndex); if (temp < loopValue) { throw new RuntimeException("result is not sorted, cur index: " + nextIndex + ", cur value: " + temp + ", prev value: " + loopValue); } loopValue = temp; nextIndex += 1; } } protected static List<Long> randomlyInitArray() { final List<Long> result = new ArrayList<>(N); final PseudoRandom random = new PseudoRandom(S); for (int i = 0; i < N; i++) { result.add(Math.abs(random.nextLong() % M)); } return result; } }
5,323
31.072289
148
java
savina
savina-master/src/main/java/edu/rice/habanero/benchmarks/bndbuffer/ProdConsBoundedBufferConfig.java
package edu.rice.habanero.benchmarks.bndbuffer; import edu.rice.habanero.benchmarks.BenchmarkRunner; import edu.rice.habanero.benchmarks.PseudoRandom; /** * Computes Logistic Map source: http://en.wikipedia.org/wiki/Logistic_map * * @author <a href="http://shams.web.rice.edu/">Shams Imam</a> (shams@rice.edu) */ public final class ProdConsBoundedBufferConfig { protected static int bufferSize = 50; protected static int numProducers = 40; protected static int numConsumers = 40; protected static int numItemsPerProducer = 1_000; protected static int prodCost = 25; protected static int consCost = 25; protected static int numMailboxes = 1; protected static boolean debug = false; protected static void parseArgs(final String[] args) { int i = 0; while (i < args.length) { final String loopOptionKey = args[i]; System.out.printf(loopOptionKey); switch (loopOptionKey) { case "-b": i += 1; bufferSize = Integer.parseInt(args[i]); break; case "-p": i += 1; numProducers = Integer.parseInt(args[i]); break; case "-c": i += 1; numConsumers = Integer.parseInt(args[i]); break; case "-x": i += 1; prodCost = Integer.parseInt(args[i]); break; case "-y": i += 1; consCost = Integer.parseInt(args[i]); break; case "-i": i += 1; numItemsPerProducer = Integer.parseInt(args[i]); break; case "-numChannels": case "-numMailboxes": case "-nm": i += 1; numMailboxes = Integer.parseInt(args[i]); break; case "-debug": case "-verbose": debug = true; break; } i += 1; } } protected static void printArgs() { System.out.printf(BenchmarkRunner.argOutputFormat, "Buffer size", bufferSize); System.out.printf(BenchmarkRunner.argOutputFormat, "num producers", numProducers); System.out.printf(BenchmarkRunner.argOutputFormat, "num consumers", numConsumers); System.out.printf(BenchmarkRunner.argOutputFormat, "prod cost", prodCost); System.out.printf(BenchmarkRunner.argOutputFormat, "cons cost", consCost); System.out.printf(BenchmarkRunner.argOutputFormat, "items per producer", numItemsPerProducer); System.out.printf(BenchmarkRunner.argOutputFormat, "num mailboxes", numMailboxes); System.out.printf(BenchmarkRunner.argOutputFormat, "debug", debug); } protected static double processItem(final double curTerm, final int cost) { double res = curTerm; final PseudoRandom random = new PseudoRandom(cost); if (cost > 0) { for (int i = 0; i < cost; i++) { for (int j = 0; j < 100; j++) { res += Math.log(Math.abs(random.nextDouble()) + 0.01); } } } else { res += Math.log(Math.abs(random.nextDouble()) + 0.01); } return res; } protected enum MessageSource { PRODUCER, CONSUMER } protected static class DataItemMessage { public final double data; public final Object producer; DataItemMessage(final double data, final Object producer) { this.data = data; this.producer = producer; } } protected static class ProduceDataMessage { protected static ProduceDataMessage ONLY = new ProduceDataMessage(); } protected static class ProducerExitMessage { protected static ProducerExitMessage ONLY = new ProducerExitMessage(); } protected static class ConsumerAvailableMessage { public final Object consumer; ConsumerAvailableMessage(final Object consumer) { this.consumer = consumer; } } protected static class ConsumerExitMessage { protected static ConsumerExitMessage ONLY = new ConsumerExitMessage(); } }
4,450
32.977099
102
java
savina
savina-master/src/main/java/edu/rice/habanero/benchmarks/philosopher/PhilosopherConfig.java
package edu.rice.habanero.benchmarks.philosopher; import edu.rice.habanero.benchmarks.BenchmarkRunner; /** * @author <a href="http://shams.web.rice.edu/">Shams Imam</a> (shams@rice.edu) */ public final class PhilosopherConfig { protected static int N = 20; // num philosophers protected static int M = 10_000; // num eating rounds protected static int C = 1; // num channels protected static boolean debug = false; protected static void parseArgs(final String[] args) { int i = 0; while (i < args.length) { final String loopOptionKey = args[i]; switch (loopOptionKey) { case "-n": i += 1; N = Integer.parseInt(args[i]); break; case "-m": i += 1; M = Integer.parseInt(args[i]); break; case "-c": i += 1; C = Integer.parseInt(args[i]); break; case "-debug": case "-verbose": debug = true; break; } i += 1; } } protected static void printArgs() { System.out.printf(BenchmarkRunner.argOutputFormat, "N (num philosophers)", N); System.out.printf(BenchmarkRunner.argOutputFormat, "M (num eating rounds)", M); System.out.printf(BenchmarkRunner.argOutputFormat, "C (num channels)", C); System.out.printf(BenchmarkRunner.argOutputFormat, "debug", debug); } }
1,593
32.208333
87
java
savina
savina-master/src/main/java/edu/rice/habanero/benchmarks/sieve/SieveConfig.java
package edu.rice.habanero.benchmarks.sieve; import edu.rice.habanero.benchmarks.BenchmarkRunner; /** * @author <a href="http://shams.web.rice.edu/">Shams Imam</a> (shams@rice.edu) */ public final class SieveConfig { protected static long N = 100_000; protected static int M = 1_000; protected static boolean debug = false; protected static void parseArgs(final String[] args) { int i = 0; while (i < args.length) { final String loopOptionKey = args[i]; switch (loopOptionKey) { case "-n": i += 1; N = Long.parseLong(args[i]); break; case "-m": i += 1; M = Integer.parseInt(args[i]); break; case "-debug": case "-verbose": debug = true; break; } i += 1; } } protected static void printArgs() { System.out.printf(BenchmarkRunner.argOutputFormat, "N (input size)", N); System.out.printf(BenchmarkRunner.argOutputFormat, "debug", debug); } protected static boolean isLocallyPrime( final long candidate, final long[] localPrimes, final int startInc, final int endExc) { for (int i = startInc; i < endExc; i++) { final long remainder = candidate % localPrimes[i]; if (remainder == 0) { return false; } } return true; } }
1,596
27.517857
80
java
savina
savina-master/src/main/java/edu/rice/habanero/benchmarks/cigsmok/CigaretteSmokerConfig.java
package edu.rice.habanero.benchmarks.cigsmok; import edu.rice.habanero.benchmarks.BenchmarkRunner; /** * @author <a href="http://shams.web.rice.edu/">Shams Imam</a> (shams@rice.edu) */ public final class CigaretteSmokerConfig { protected static int R = 1_000; // num rounds protected static int S = 200; // num smokers / ingredients protected static boolean debug = false; protected static void parseArgs(final String[] args) { int i = 0; while (i < args.length) { final String loopOptionKey = args[i]; if ("-r".equals(loopOptionKey)) { i += 1; R = Integer.parseInt(args[i]); } else if ("-s".equals(loopOptionKey)) { i += 1; S = Integer.parseInt(args[i]); } else if ("-debug".equals(loopOptionKey) || "-verbose".equals(loopOptionKey)) { debug = true; } i += 1; } } protected static void printArgs() { System.out.printf(BenchmarkRunner.argOutputFormat, "R (num rounds)", R); System.out.printf(BenchmarkRunner.argOutputFormat, "S (num smokers)", S); System.out.printf(BenchmarkRunner.argOutputFormat, "debug", debug); } protected static int busyWait(final int limit) { int test = 0; for (int k = 0; k < limit; k++) { Math.random(); test++; } return test; } protected static class StartSmoking { public final int busyWaitPeriod; public StartSmoking(final int busyWaitPeriod) { this.busyWaitPeriod = busyWaitPeriod; } } protected static class StartedSmoking { public static StartedSmoking ONLY = new StartedSmoking(); } protected static class StartMessage { public static StartMessage ONLY = new StartMessage(); } protected static class ExitMessage { public static ExitMessage ONLY = new ExitMessage(); } }
2,002
28.455882
92
java
savina
savina-master/src/main/java/edu/rice/habanero/benchmarks/pingpong/PingPongConfig.java
package edu.rice.habanero.benchmarks.pingpong; import edu.rice.habanero.benchmarks.BenchmarkRunner; /** * @author <a href="http://shams.web.rice.edu/">Shams Imam</a> (shams@rice.edu) */ public final class PingPongConfig { protected static int N = 40000; protected static boolean debug = false; protected static void parseArgs(final String[] args) { int i = 0; while (i < args.length) { final String loopOptionKey = args[i]; if ("-n".equals(loopOptionKey)) { i += 1; N = Integer.parseInt(args[i]); } else if ("-debug".equals(loopOptionKey) || "-verbose".equals(loopOptionKey)) { debug = true; } i += 1; } } protected static void printArgs() { System.out.printf(BenchmarkRunner.argOutputFormat, "N (num pings)", N); System.out.printf(BenchmarkRunner.argOutputFormat, "debug", debug); } protected static abstract class Message { } protected static class StartMessage extends Message { static StartMessage ONLY = new StartMessage(); protected StartMessage() { } } protected static class PingMessage extends Message { static PingMessage ONLY = new PingMessage(); protected PingMessage() { } } protected static class SendPongMessage extends Message { public final Object sender; protected SendPongMessage(final Object sender) { this.sender = sender; } } protected static class SendPingMessage extends Message { public final Object sender; protected SendPingMessage(final Object sender) { this.sender = sender; } } protected static class StopMessage extends Message { protected static StopMessage ONLY = new StopMessage(); private StopMessage() { } } }
1,928
25.791667
92
java
savina
savina-master/src/main/java/edu/rice/habanero/benchmarks/fib/FibonacciConfig.java
package edu.rice.habanero.benchmarks.fib; import edu.rice.habanero.benchmarks.BenchmarkRunner; /** * @author <a href="http://shams.web.rice.edu/">Shams Imam</a> (shams@rice.edu) */ public final class FibonacciConfig { protected static int N = 25; protected static boolean debug = false; protected static void parseArgs(final String[] args) { int i = 0; while (i < args.length) { final String loopOptionKey = args[i]; switch (loopOptionKey) { case "-n": i += 1; N = Integer.parseInt(args[i]); break; case "-debug": case "-verbose": debug = true; break; } i += 1; } } protected static void printArgs() { System.out.printf(BenchmarkRunner.argOutputFormat, "N (index)", N); System.out.printf(BenchmarkRunner.argOutputFormat, "debug", debug); } }
1,009
27.055556
79
java
savina
savina-master/src/main/java/edu/rice/habanero/benchmarks/concsll/SortedLinkedList.java
package edu.rice.habanero.benchmarks.concsll; /** * Source: http://www.cs.ucsb.edu/~franklin/20/assigns/prog2files/MySortedLinkedList.java * <p/> * Stores a sorted list of items that implement the interface Comparable. Provides an iterator to allow stepping through * the list in a loop * * @author <a href="http://shams.web.rice.edu/">Shams Imam</a> (shams@rice.edu) */ public final class SortedLinkedList<T extends Comparable<T>> { /** * stores a single item in the linked list */ private static class Node<T extends Comparable<T>> { public T item; public Node<T> next; public Node(final T i) { item = i; next = null; } } // a reference to the first node in the list private Node<T> head; // a reference to the node to return when next() is called private Node<T> iterator; /** * constructor creates a linked list with no items in it */ protected SortedLinkedList() { head = null; iterator = null; } /** * isEmpty inputs: none return value: returns true if there are no items in linked list */ public boolean isEmpty() { return (head == null); } /** * add inputs: Comparable item return value: none adds an item into the list in sorted order */ public void add(final T item) { // make the new node to insert into list final Node<T> newNode = new Node<>(item); // first see if the list is empty if (head == null) { // System.out.println("add "+item +" to front"); head = newNode; } else if (item.compareTo(head.item) < 0) { // there is something in the list // now check to see if it belongs in front // System.out.println("add "+item +"before"+head.item); newNode.next = head; head = newNode; } else { // otherwise, step down the list. n will stop // at the node after the new node, and trailer will // stop at the node before the new node Node<T> after = head.next; Node<T> before = head; while (after != null) { if (item.compareTo(after.item) < 0) { break; } before = after; after = after.next; } // insert between before & after newNode.next = before.next; before.next = newNode; // System.out.println("add " + item + "after" + before.item); } } /* contains * inputs: Comparable item * return value: true if equal item is in list, false otherwise */ public boolean contains(final T item) { Node<T> n = head; // for each node in the linked list while (n != null) { // if it is equal, return true // note that I used compareTo here, not equals // because I am only guaranteed that the // compareTo method is implemented, not equals if (item.compareTo(n.item) == 0) { return true; } n = n.next; } // if it is not found in list, return false return false; } /** * toString inputs: none return value: string representation of the linked list items Format must match assignment */ public String toString() { final StringBuilder s = new StringBuilder(100); Node<T> n = head; // for each node in the linked list while (n != null) { s.append(n.item.toString()); n = n.next; } // if it is not found in list, return false return s.toString(); } /** * next inputs: none return value: one element from the linked list This method returns each element in the linked * list in order. It is to be used in a loop to access every item in the list. */ public Comparable<T> next() { if (iterator != null) { final Node<T> n = iterator; iterator = iterator.next; return n.item; } else { return null; } } /** * reset inputs: none return value: none resets the iterator so that the next call to next() will return the first * element in the list */ public void reset() { iterator = head; } /** * size inputs: none return value: the number of elements in linked list */ public int size() { int r = 0; Node<T> n = head; // for each node in the linked list while (n != null) { r++; n = n.next; } // if it is not found in list, return false return r; } }
4,808
30.025806
120
java
savina
savina-master/src/main/java/edu/rice/habanero/benchmarks/concsll/SortedListConfig.java
package edu.rice.habanero.benchmarks.concsll; import edu.rice.habanero.benchmarks.BenchmarkRunner; /** * @author <a href="http://shams.web.rice.edu/">Shams Imam</a> (shams@rice.edu) */ public final class SortedListConfig { protected static int NUM_ENTITIES = 20; protected static int NUM_MSGS_PER_WORKER = 8_000; protected static int WRITE_PERCENTAGE = 10; protected static int SIZE_PERCENTAGE = 1; protected static boolean debug = false; protected static void parseArgs(final String[] args) { int i = 0; while (i < args.length) { final String loopOptionKey = args[i]; switch (loopOptionKey) { case "-e": i += 1; NUM_ENTITIES = Integer.parseInt(args[i]); break; case "-m": i += 1; NUM_MSGS_PER_WORKER = Integer.parseInt(args[i]); break; case "-w": i += 1; WRITE_PERCENTAGE = Integer.parseInt(args[i]); break; case "-s": i += 1; SIZE_PERCENTAGE = Integer.parseInt(args[i]); break; case "debug": case "verbose": debug = true; break; } i += 1; } if (WRITE_PERCENTAGE >= 50) { throw new IllegalArgumentException("Write rate must be less than 50!"); } if ((2 * WRITE_PERCENTAGE + SIZE_PERCENTAGE) >= 100) { throw new IllegalArgumentException("(2 * write-rate) + sum-rate must be less than 100!"); } } protected static void printArgs() { System.out.printf(BenchmarkRunner.argOutputFormat, "Num Entities", NUM_ENTITIES); System.out.printf(BenchmarkRunner.argOutputFormat, "Message/Worker", NUM_MSGS_PER_WORKER); System.out.printf(BenchmarkRunner.argOutputFormat, "Insert Percent", WRITE_PERCENTAGE); System.out.printf(BenchmarkRunner.argOutputFormat, "Size Percent", SIZE_PERCENTAGE); System.out.printf(BenchmarkRunner.argOutputFormat, "debug", debug); } protected static class WriteMessage { protected final Object sender; protected final int value; protected WriteMessage(final Object sender, final int value) { this.sender = sender; this.value = value; } } protected static class ContainsMessage { protected final Object sender; protected final int value; protected ContainsMessage(final Object sender, final int value) { this.sender = sender; this.value = value; } } protected static class SizeMessage { protected final Object sender; protected SizeMessage(final Object sender) { this.sender = sender; } } protected static class ResultMessage { protected final Object sender; protected final int value; protected ResultMessage(final Object sender, final int value) { this.sender = sender; this.value = value; } } protected static class DoWorkMessage { protected static final DoWorkMessage ONLY = new DoWorkMessage(); private DoWorkMessage() { super(); } } protected static class EndWorkMessage { protected static final EndWorkMessage ONLY = new EndWorkMessage(); private EndWorkMessage() { super(); } } }
3,633
28.786885
101
java
savina
savina-master/src/main/java/edu/rice/habanero/benchmarks/logmap/LogisticMapConfig.java
package edu.rice.habanero.benchmarks.logmap; import edu.rice.habanero.benchmarks.BenchmarkRunner; /** * Computes Logistic Map source: http://en.wikipedia.org/wiki/Logistic_map * * @author <a href="http://shams.web.rice.edu/">Shams Imam</a> (shams@rice.edu) */ public final class LogisticMapConfig { protected static int numTerms = 25_000; protected static int numSeries = 10; protected static double startRate = 3.46; protected static double increment = 0.0025; protected static boolean debug = false; protected static void parseArgs(final String[] args) { int i = 0; while (i < args.length) { final String loopOptionKey = args[i]; switch (loopOptionKey) { case "-t": i += 1; numTerms = Integer.parseInt(args[i]); break; case "-s": i += 1; numSeries = Integer.parseInt(args[i]); break; case "-r": i += 1; startRate = Double.parseDouble(args[i]); break; case "-debug": case "-verbose": debug = true; break; } i += 1; } } protected static void printArgs() { System.out.printf(BenchmarkRunner.argOutputFormat, "num terms", numTerms); System.out.printf(BenchmarkRunner.argOutputFormat, "num series", numSeries); System.out.printf(BenchmarkRunner.argOutputFormat, "start rate", startRate); System.out.printf(BenchmarkRunner.argOutputFormat, "debug", debug); } protected static double computeNextTerm(final double curTerm, final double rate) { return rate * curTerm * (1 - curTerm); } protected static final class StartMessage { protected static StartMessage ONLY = new StartMessage(); } protected static final class StopMessage { protected static StopMessage ONLY = new StopMessage(); } protected static final class NextTermMessage { protected static NextTermMessage ONLY = new NextTermMessage(); } protected static final class GetTermMessage { protected static GetTermMessage ONLY = new GetTermMessage(); } protected static class ComputeMessage { public final Object sender; public final double term; public ComputeMessage(final Object sender, final double term) { this.sender = sender; this.term = term; } } protected static class ResultMessage { public final double term; public ResultMessage(final double term) { this.term = term; } } }
2,784
29.604396
86
java
savina
savina-master/src/main/java/edu/rice/habanero/benchmarks/uct/UctConfig.java
package edu.rice.habanero.benchmarks.uct; import edu.rice.habanero.benchmarks.BenchmarkRunner; /** * Unbalanced Cobwebbed Tree benchmark. * * @author <a href="http://shams.web.rice.edu/">Shams Imam</a> (shams@rice.edu) */ public final class UctConfig { protected static int MAX_NODES = 200_000; //_000; // maximum nodes protected static int AVG_COMP_SIZE = 500; // average computation size protected static int STDEV_COMP_SIZE = 100; // standard deviation of the computation size protected static int BINOMIAL_PARAM = 10; // binomial parameter: each node may have either 0 or binomial children protected static int URGENT_NODE_PERCENT = 50; // percentage of urgent nodes protected static boolean debug = false; protected static void parseArgs(final String[] args) { int i = 0; while (i < args.length) { final String loopOptionKey = args[i]; switch (loopOptionKey) { case "-n": i += 1; MAX_NODES = Integer.parseInt(args[i]); break; case "-a": i += 1; AVG_COMP_SIZE = Integer.parseInt(args[i]); break; case "-s": i += 1; STDEV_COMP_SIZE = Integer.parseInt(args[i]); break; case "-b": i += 1; BINOMIAL_PARAM = Integer.parseInt(args[i]); break; case "-u": i += 1; URGENT_NODE_PERCENT = Integer.parseInt(args[i]); break; case "-d": case "-verbose": debug = true; break; } i += 1; } } protected static void printArgs() { System.out.printf(BenchmarkRunner.argOutputFormat, "Max. nodes", MAX_NODES); System.out.printf(BenchmarkRunner.argOutputFormat, "Avg. comp size", AVG_COMP_SIZE); System.out.printf(BenchmarkRunner.argOutputFormat, "Std. dev. comp size", STDEV_COMP_SIZE); System.out.printf(BenchmarkRunner.argOutputFormat, "Binomial Param", BINOMIAL_PARAM); System.out.printf(BenchmarkRunner.argOutputFormat, "Urgent node percent", URGENT_NODE_PERCENT); System.out.printf(BenchmarkRunner.argOutputFormat, "debug", debug); } protected static int loop(int busywait, int dummy) { int test = 0; //long current = System.currentTimeMillis(); for (int k = 0; k < dummy * busywait; k++) { test++; } return test; } protected static class GetIdMessage { protected static GetIdMessage ONLY = new GetIdMessage(); } protected static class PrintInfoMessage { protected static PrintInfoMessage ONLY = new PrintInfoMessage(); } protected static class GenerateTreeMessage { protected static GenerateTreeMessage ONLY = new GenerateTreeMessage(); } protected static class TryGenerateChildrenMessage { protected static TryGenerateChildrenMessage ONLY = new TryGenerateChildrenMessage(); } protected static class GenerateChildrenMessage { public final int currentId; public final int compSize; public GenerateChildrenMessage(final int currentId, final int compSize) { this.currentId = currentId; this.compSize = compSize; } } protected static class UrgentGenerateChildrenMessage { public final int urgentChildId; public final int currentId; public final int compSize; public UrgentGenerateChildrenMessage(final int urgentChildId, final int currentId, final int compSize) { this.urgentChildId = urgentChildId; this.currentId = currentId; this.compSize = compSize; } } protected static class TraverseMessage { protected static TraverseMessage ONLY = new TraverseMessage(); } protected static class UrgentTraverseMessage { protected static UrgentTraverseMessage ONLY = new UrgentTraverseMessage(); } protected static class ShouldGenerateChildrenMessage { public final Object sender; public final int childHeight; public ShouldGenerateChildrenMessage(final Object sender, final int childHeight) { this.sender = sender; this.childHeight = childHeight; } } protected static class UpdateGrantMessage { public final int childId; public UpdateGrantMessage(final int childId) { this.childId = childId; } } protected static class TerminateMessage { protected static TerminateMessage ONLY = new TerminateMessage(); } }
4,852
32.937063
117
java
savina
savina-master/src/main/java/edu/rice/habanero/benchmarks/count/CountingConfig.java
package edu.rice.habanero.benchmarks.count; import edu.rice.habanero.benchmarks.BenchmarkRunner; /** * @author <a href="http://shams.web.rice.edu/">Shams Imam</a> (shams@rice.edu) */ public final class CountingConfig { protected static int N = 1_000_000; protected static boolean debug = false; protected static void parseArgs(final String[] args) { int i = 0; while (i < args.length) { final String loopOptionKey = args[i]; switch (loopOptionKey) { case "-n": i += 1; N = Integer.parseInt(args[i]); break; case "-debug": case "-verbose": debug = true; break; } i += 1; } } protected static void printArgs() { System.out.printf(BenchmarkRunner.argOutputFormat, "N (num messages)", N); System.out.printf(BenchmarkRunner.argOutputFormat, "debug", debug); } }
1,024
27.472222
82
java
savina
savina-master/src/main/java/edu/rice/habanero/benchmarks/barber/SleepingBarberConfig.java
package edu.rice.habanero.benchmarks.barber; import edu.rice.habanero.benchmarks.BenchmarkRunner; /** * @author <a href="http://shams.web.rice.edu/">Shams Imam</a> (shams@rice.edu) */ public final class SleepingBarberConfig { protected static int N = 5_000; // num haircuts protected static int W = 1_000; // waiting room size protected static int APR = 1_000; // average production rate protected static int AHR = 1_000; // avergae haircut rate protected static boolean debug = false; protected static void parseArgs(final String[] args) { int i = 0; while (i < args.length) { final String loopOptionKey = args[i]; if ("-n".equals(loopOptionKey)) { i += 1; N = Integer.parseInt(args[i]); } else if ("-w".equals(loopOptionKey)) { i += 1; W = Integer.parseInt(args[i]); } else if ("-p".equals(loopOptionKey)) { i += 1; APR = Integer.parseInt(args[i]); } else if ("-c".equals(loopOptionKey)) { i += 1; AHR = Integer.parseInt(args[i]); } else if ("-debug".equals(loopOptionKey) || "-verbose".equals(loopOptionKey)) { debug = true; } i += 1; } } protected static void printArgs() { System.out.printf(BenchmarkRunner.argOutputFormat, "N (num haircuts)", N); System.out.printf(BenchmarkRunner.argOutputFormat, "W (waiting room size)", W); System.out.printf(BenchmarkRunner.argOutputFormat, "APR (production rate)", APR); System.out.printf(BenchmarkRunner.argOutputFormat, "AHR (haircut rate)", AHR); System.out.printf(BenchmarkRunner.argOutputFormat, "debug", debug); } protected static int busyWait(final int limit) { int test = 0; for (int k = 0; k < limit; k++) { Math.random(); test++; } return test; } protected static class Full { public static Full ONLY = new Full(); } protected static class Wait { public static Wait ONLY = new Wait(); } protected static class Next { public static Next ONLY = new Next(); } protected static class Start { public static Start ONLY = new Start(); } protected static class Done { public static Done ONLY = new Done(); } protected static class Exit { public static Exit ONLY = new Exit(); } }
2,543
29.650602
92
java
savina
savina-master/src/main/java/edu/rice/habanero/benchmarks/filterbank/FilterBankConfig.java
package edu.rice.habanero.benchmarks.filterbank; import edu.rice.habanero.benchmarks.BenchmarkRunner; import java.util.Collection; /** * @author <a href="http://shams.web.rice.edu/">Shams Imam</a> (shams@rice.edu) */ public final class FilterBankConfig { protected static int NUM_COLUMNS = 8192 * 2; protected static int NUM_SIMULATIONS = 2048 + (Math.max(2048, NUM_COLUMNS) * 2); protected static int NUM_CHANNELS = 8; protected static int SINK_PRINT_RATE = 100; protected static boolean debug = false; protected static double[][] H = null; protected static double[][] F = null; protected static void parseArgs(final String[] args) { int i = 0; while (i < args.length) { final String loopOptionKey = args[i]; switch (loopOptionKey) { case "-s": case "-simulation": i += 1; NUM_SIMULATIONS = Integer.parseInt(args[i]); break; case "-c": case "-columns": i += 1; NUM_COLUMNS = Integer.parseInt(args[i]); break; case "-a": case "-channels": i += 1; final int argInt = Integer.parseInt(args[i]); final int maxChannels = MessageChannel.values().length - 1; NUM_CHANNELS = Math.max(2, Math.min(argInt, maxChannels)); break; case "-d": case "-verbose": debug = true; break; } i += 1; } H = new double[NUM_CHANNELS][NUM_COLUMNS]; F = new double[NUM_CHANNELS][NUM_COLUMNS]; for (int j = 0; j < NUM_CHANNELS; j++) { for (i = 0; i < NUM_COLUMNS; i++) { H[j][i] = (1.0 * i * NUM_COLUMNS) + (1.0 * j * NUM_CHANNELS) + j + i + j + 1; F[j][i] = (1.0 * i * j) + (1.0 * j * j) + j + i; } } } protected static void printArgs() { System.out.printf(BenchmarkRunner.argOutputFormat, "numSimulations", NUM_SIMULATIONS); System.out.printf(BenchmarkRunner.argOutputFormat, "numColumns", NUM_COLUMNS); System.out.printf(BenchmarkRunner.argOutputFormat, "numChannels", NUM_CHANNELS); System.out.printf(BenchmarkRunner.argOutputFormat, "debug", debug); } protected enum MessageChannel { C00, C01, C02, C03, C04, C05, C06, C07, C08, C09, C10, C11, C12, C13, C14, C15, C16, C17, C18, C19, C20, C21, C22, C23, C24, C25, C26, C27, C28, C29, C30, C31, C32, C33, C_LOWEST } protected static abstract class Message { } protected static class NextMessage extends Message { public final Object source; protected NextMessage(final Object source) { this.source = source; } } protected static class BootMessage extends Message { protected static final BootMessage ONLY = new BootMessage(); private BootMessage() { super(); } } protected static class ExitMessage extends Message { protected static final ExitMessage ONLY = new ExitMessage(); private ExitMessage() { super(); } } protected static class ValueMessage extends Message { public final double value; protected ValueMessage(final double value) { this.value = value; } } protected static class SourcedValueMessage extends Message { public final int sourceId; public final double value; protected SourcedValueMessage(final int sourceId, final double value) { this.sourceId = sourceId; this.value = value; } } protected static class CollectionMessage<T> extends Message { public final Collection<T> values; protected CollectionMessage(final Collection<T> values) { this.values = values; } } }
4,341
25.802469
94
java
savina
savina-master/src/main/java/edu/rice/habanero/benchmarks/fjthrput/ThroughputConfig.java
package edu.rice.habanero.benchmarks.fjthrput; import edu.rice.habanero.benchmarks.BenchmarkRunner; /** * @author <a href="http://shams.web.rice.edu/">Shams Imam</a> (shams@rice.edu) */ public final class ThroughputConfig { protected static int N = 10_000; protected static int A = 60; protected static int C = 1; protected static boolean usePriorities = true; protected static boolean debug = false; protected static void parseArgs(final String[] args) { int i = 0; while (i < args.length) { final String loopOptionKey = args[i]; switch (loopOptionKey) { case "-n": i += 1; N = Integer.parseInt(args[i]); break; case "-a": i += 1; A = Integer.parseInt(args[i]); break; case "-c": i += 1; C = Integer.parseInt(args[i]); break; case "-p": i += 1; usePriorities = Boolean.parseBoolean(args[i]); break; case "-debug": case "-verbose": debug = true; break; } i += 1; } } protected static void printArgs() { System.out.printf(BenchmarkRunner.argOutputFormat, "N (messages per actor)", N); System.out.printf(BenchmarkRunner.argOutputFormat, "A (num actors)", A); System.out.printf(BenchmarkRunner.argOutputFormat, "C (num channels)", C); System.out.printf(BenchmarkRunner.argOutputFormat, "P (use priorities)", usePriorities); System.out.printf(BenchmarkRunner.argOutputFormat, "debug", debug); } protected static void performComputation(final double theta) { final double sint = Math.sin(theta); final double res = sint * sint; //defeat dead code elimination if (res <= 0) { throw new IllegalStateException("Benchmark exited with unrealistic res value " + res); } } }
2,155
33.222222
98
java
savina
savina-master/src/main/java/edu/rice/habanero/benchmarks/banking/BankingConfig.java
package edu.rice.habanero.benchmarks.banking; import edu.rice.habanero.benchmarks.BenchmarkRunner; /** * @author <a href="http://shams.web.rice.edu/">Shams Imam</a> (shams@rice.edu) */ public final class BankingConfig { protected static int A = 1_000; // num accounts protected static int N = 50_000; // num transactions protected static double INITIAL_BALANCE = Double.MAX_VALUE / (A * N); protected static boolean debug = false; protected static void parseArgs(final String[] args) { int i = 0; while (i < args.length) { final String loopOptionKey = args[i]; switch (loopOptionKey) { case "-a": i += 1; A = Integer.parseInt(args[i]); break; case "-n": i += 1; N = Integer.parseInt(args[i]); break; case "-debug": case "-verbose": debug = true; break; } i += 1; } INITIAL_BALANCE = ((Double.MAX_VALUE / (A * N)) / 1_000) * 1_000; } protected static void printArgs() { System.out.printf(BenchmarkRunner.argOutputFormat, "A (num accounts)", A); System.out.printf(BenchmarkRunner.argOutputFormat, "N (num transactions)", N); System.out.printf(BenchmarkRunner.argOutputFormat, "Initial Balance", INITIAL_BALANCE); System.out.printf(BenchmarkRunner.argOutputFormat, "debug", debug); } protected static final class StartMessage { protected static StartMessage ONLY = new StartMessage(); } protected static final class StopMessage { protected static StopMessage ONLY = new StopMessage(); } protected static final class ReplyMessage { protected static ReplyMessage ONLY = new ReplyMessage(); } protected static class DebitMessage { public final Object sender; public final double amount; public DebitMessage(final Object sender, final double amount) { this.sender = sender; this.amount = amount; } } protected static class CreditMessage { public final Object sender; public final double amount; public final Object recipient; public CreditMessage(final Object sender, final double amount, final Object recipient) { this.sender = sender; this.amount = amount; this.recipient = recipient; } } }
2,565
31.075
96
java
savina
savina-master/src/main/java/edu/rice/habanero/benchmarks/piprecision/PiPrecisionConfig.java
package edu.rice.habanero.benchmarks.piprecision; import edu.rice.habanero.benchmarks.BenchmarkRunner; import java.math.BigDecimal; import java.math.RoundingMode; /** * @author <a href="http://shams.web.rice.edu/">Shams Imam</a> (shams@rice.edu) */ public final class PiPrecisionConfig { private static final BigDecimal one = BigDecimal.ONE; private static final BigDecimal two = new BigDecimal(2); private static final BigDecimal four = new BigDecimal(4); private static final BigDecimal sixteen = new BigDecimal(16); protected static int NUM_WORKERS = 20; protected static int PRECISION = 5_000; protected static boolean debug = false; protected static void parseArgs(final String[] args) { int i = 0; while (i < args.length) { final String loopOptionKey = args[i]; switch (loopOptionKey) { case "-w": i += 1; NUM_WORKERS = Integer.parseInt(args[i]); break; case "-p": i += 1; PRECISION = Integer.parseInt(args[i]); break; case "debug": case "verbose": debug = true; break; } i += 1; } } protected static void printArgs() { System.out.printf(BenchmarkRunner.argOutputFormat, "Num Workers", NUM_WORKERS); System.out.printf(BenchmarkRunner.argOutputFormat, "Precision", PRECISION); System.out.printf(BenchmarkRunner.argOutputFormat, "debug", debug); } /** * Original Source Code: http://research.cs.queensu.ca/home/cmpe212/Fall2011/Lab6/Lab6.java Formula: * http://mathworld.wolfram.com/BBPFormula.html */ protected static BigDecimal calculateBbpTerm(final int scale, final int k) { final RoundingMode roundMode = RoundingMode.HALF_EVEN; final int eightK = 8 * k; BigDecimal term = four.divide(new BigDecimal(eightK + 1), scale, roundMode); term = term.subtract(two.divide(new BigDecimal(eightK + 4), scale, roundMode)); term = term.subtract(one.divide(new BigDecimal(eightK + 5), scale, roundMode)); term = term.subtract(one.divide(new BigDecimal(eightK + 6), scale, roundMode)); term = term.divide(sixteen.pow(k), scale, roundMode); return term; } // Message classes protected static class StartMessage { protected static StartMessage ONLY = new StartMessage(); } protected static class StopMessage { protected static StopMessage ONLY = new StopMessage(); } protected static class WorkMessage { public final int scale; public final int term; public WorkMessage(final int scale, final int term) { this.scale = scale; this.term = term; } } protected static class ResultMessage { public final BigDecimal result; public final int workerId; public ResultMessage(final BigDecimal result, final int workerId) { this.result = result; this.workerId = workerId; } } }
3,195
33
104
java
savina
savina-master/src/main/java/edu/rice/habanero/benchmarks/chameneos/ChameneosHelper.java
package edu.rice.habanero.benchmarks.chameneos; /** * @author <a href="http://shams.web.rice.edu/">Shams Imam</a> (shams@rice.edu) */ public class ChameneosHelper { protected static Color complement(final Color color, final Color otherColor) { switch (color) { case RED: switch (otherColor) { case RED: return Color.RED; case YELLOW: return Color.BLUE; case BLUE: return Color.YELLOW; case FADED: return Color.FADED; } break; case YELLOW: switch (otherColor) { case RED: return Color.BLUE; case YELLOW: return Color.YELLOW; case BLUE: return Color.RED; case FADED: return Color.FADED; } break; case BLUE: switch (otherColor) { case RED: return Color.YELLOW; case YELLOW: return Color.RED; case BLUE: return Color.BLUE; case FADED: return Color.FADED; } break; case FADED: return Color.FADED; } throw new IllegalArgumentException("Unknown color: " + color); } protected static Color fadedColor() { return Color.FADED; } enum Color { RED, YELLOW, BLUE, FADED } protected static interface Message { } protected static class MeetMsg implements Message { public final Color color; public final Object sender; protected MeetMsg(final Color color, final Object sender) { this.color = color; this.sender = sender; } } protected static class ChangeMsg implements Message { public final Color color; public final Object sender; protected ChangeMsg(final Color color, final Object sender) { this.color = color; this.sender = sender; } } protected static class MeetingCountMsg implements Message { public final int count; public final Object sender; protected MeetingCountMsg(final int count, final Object sender) { this.count = count; this.sender = sender; } } protected static class ExitMsg implements Message { public final Object sender; protected ExitMsg(final Object sender) { this.sender = sender; } } }
2,884
26.216981
82
java
savina
savina-master/src/main/java/edu/rice/habanero/benchmarks/chameneos/ChameneosConfig.java
package edu.rice.habanero.benchmarks.chameneos; import edu.rice.habanero.benchmarks.BenchmarkRunner; /** * @author <a href="http://shams.web.rice.edu/">Shams Imam</a> (shams@rice.edu) */ public final class ChameneosConfig { protected static int numChameneos = 100; protected static int numMeetings = 200_000; protected static int numMailboxes = 1; protected static boolean usePriorities = true; protected static boolean debug = false; protected static void parseArgs(final String[] args) { int i = 0; while (i < args.length) { final String loopOptionKey = args[i]; switch (loopOptionKey) { case "-numChameneos": case "-c": i += 1; numChameneos = Integer.parseInt(args[i]); break; case "-numMeetings": case "-m": i += 1; numMeetings = Integer.parseInt(args[i]); break; case "-numChannels": case "-numMailboxes": case "-nm": i += 1; numMailboxes = Integer.parseInt(args[i]); break; case "-p": i += 1; usePriorities = Boolean.parseBoolean(args[i]); break; case "-debug": case "-verbose": debug = true; break; } i += 1; } } protected static void printArgs() { System.out.printf(BenchmarkRunner.argOutputFormat, "num chameneos", numChameneos); System.out.printf(BenchmarkRunner.argOutputFormat, "num meetings", numMeetings); System.out.printf(BenchmarkRunner.argOutputFormat, "num mailboxes", numMailboxes); System.out.printf(BenchmarkRunner.argOutputFormat, "use priorities", usePriorities); System.out.printf(BenchmarkRunner.argOutputFormat, "debug", debug); } }
2,057
33.3
92
java
savina
savina-master/src/main/java/edu/rice/habanero/benchmarks/big/BigConfig.java
package edu.rice.habanero.benchmarks.big; import edu.rice.habanero.benchmarks.BenchmarkRunner; /** * @author <a href="http://shams.web.rice.edu/">Shams Imam</a> (shams@rice.edu) */ public final class BigConfig { protected static int N = 20_000; // num pings protected static int W = 120; // num actors protected static boolean debug = false; protected static void parseArgs(final String[] args) { int i = 0; while (i < args.length) { final String loopOptionKey = args[i]; if ("-n".equals(loopOptionKey)) { i += 1; N = Integer.parseInt(args[i]); } else if ("-w".equals(loopOptionKey)) { i += 1; W = Integer.parseInt(args[i]); } else if ("-debug".equals(loopOptionKey) || "-verbose".equals(loopOptionKey)) { debug = true; } i += 1; } } protected static void printArgs() { System.out.printf(BenchmarkRunner.argOutputFormat, "N (num pings)", N); System.out.printf(BenchmarkRunner.argOutputFormat, "W (num actors)", W); System.out.printf(BenchmarkRunner.argOutputFormat, "debug", debug); } protected static interface Message { } protected static final class PingMessage implements Message { public final int sender; protected PingMessage(final int sender) { this.sender = sender; } } protected static final class PongMessage implements Message { public final int sender; protected PongMessage(final int sender) { this.sender = sender; } } protected static final class ExitMessage implements Message { public static final ExitMessage ONLY = new ExitMessage(); protected ExitMessage() { super(); } } }
1,877
28.34375
92
java
savina
savina-master/src/main/java/edu/rice/habanero/benchmarks/apsp/ApspConfig.java
package edu.rice.habanero.benchmarks.apsp; import edu.rice.habanero.benchmarks.BenchmarkRunner; /** * @author <a href="http://shams.web.rice.edu/">Shams Imam</a> (shams@rice.edu) */ public final class ApspConfig { protected static int N = 300; protected static int B = 50; protected static int W = 100; protected static boolean debug = false; protected static void parseArgs(final String[] args) { int i = 0; while (i < args.length) { final String loopOptionKey = args[i]; switch (loopOptionKey) { case "-n": i += 1; N = Integer.parseInt(args[i]); break; case "-b": i += 1; B = Integer.parseInt(args[i]); break; case "-w": i += 1; W = Integer.parseInt(args[i]); break; case "-debug": case "-verbose": debug = true; break; } i += 1; } } protected static void printArgs() { System.out.printf(BenchmarkRunner.argOutputFormat, "N (num workers)", N); System.out.printf(BenchmarkRunner.argOutputFormat, "B (block size)", B); System.out.printf(BenchmarkRunner.argOutputFormat, "W (max edge weight)", W); System.out.printf(BenchmarkRunner.argOutputFormat, "debug", debug); } }
1,512
30.520833
85
java
savina
savina-master/src/main/java/edu/rice/habanero/benchmarks/threadring/ThreadRingConfig.java
package edu.rice.habanero.benchmarks.threadring; import edu.rice.habanero.benchmarks.BenchmarkRunner; /** * @author <a href="http://shams.web.rice.edu/">Shams Imam</a> (shams@rice.edu) */ public final class ThreadRingConfig { protected static int N = 100; // num actors protected static int R = 100_000; // num pings, does not need to be divisible by N protected static boolean debug = false; protected static void parseArgs(final String[] args) { int i = 0; while (i < args.length) { final String loopOptionKey = args[i]; if ("-n".equals(loopOptionKey)) { i += 1; N = Integer.parseInt(args[i]); } else if ("-r".equals(loopOptionKey)) { i += 1; R = Integer.parseInt(args[i]); } else if ("-debug".equals(loopOptionKey) || "-verbose".equals(loopOptionKey)) { debug = true; } i += 1; } } protected static void printArgs() { System.out.printf(BenchmarkRunner.argOutputFormat, "N (num actors)", N); System.out.printf(BenchmarkRunner.argOutputFormat, "R (num rounds)", R); System.out.printf(BenchmarkRunner.argOutputFormat, "debug", debug); } protected static final class PingMessage { public final int pingsLeft; protected PingMessage(final int pingsLeft) { this.pingsLeft = pingsLeft; } protected boolean hasNext() { return pingsLeft > 0; } protected PingMessage next() { return new PingMessage(pingsLeft - 1); } } protected static final class DataMessage { public final Object data; protected DataMessage(final Object data) { this.data = data; } } protected static final class ExitMessage { public final int exitsLeft; protected ExitMessage(final int exitsLeft) { this.exitsLeft = exitsLeft; } protected boolean hasNext() { return exitsLeft > 0; } protected ExitMessage next() { return new ExitMessage(exitsLeft - 1); } } }
2,210
27.714286
92
java
g-ssl-crf
g-ssl-crf-master/src/GraphConstruct/src/main/java/PMI/PMIUtility.java
package main.java.PMI; /** * Copyright: Masoud Kiaeeha, Mohammad Aliannejadi * This work is licensed under the Creative Commons Attribution-NonCommercial 4.0 * International License. To view a copy of this license, visit * http://creativecommons.org/licenses/by-nc/4.0/. */ public class PMIUtility { public static double calculatePMI(int N, int countPair, int countFirstMember, int countSecondMember){ return (Math.log(N * countPair)) - (Math.log(countFirstMember * countSecondMember)); } }
528
36.785714
105
java
g-ssl-crf
g-ssl-crf-master/src/GraphConstruct/src/main/java/PMI/FeatureHandler.java
package main.java.PMI; import main.java.Graph.GraphStructure.GraphContainerAbstract; import main.java.TextToNgram.NgramContainer; import main.java.Utility.TextFileInput; import java.util.ArrayList; import java.util.StringTokenizer; /** * Copyright: Masoud Kiaeeha, Mohammad Aliannejadi * This work is licensed under the Creative Commons Attribution-NonCommercial 4.0 * International License. To view a copy of this license, visit * http://creativecommons.org/licenses/by-nc/4.0/. */ public class FeatureHandler { /** * Use of this identifier as a member of a given ngram means the given * member position can be replaced with any word from the corpus */ public static final String nullTokenIdentifier = "?"; public enum FeatureType{Simple, IsClass, IsPreposition, POS} /** * a set of features to use when calculating main.java.PMI */ private static NgramContainer[] featureList = {new NgramContainer(new String[] {"-1", "0", "1", "2", "3"}), new NgramContainer(new String[] {"-1", "0"}), new NgramContainer(new String[] {"2", "3"}), new NgramContainer(new String[] {"1"})}; /*new NgramContainer(new String[] {"0", "?", "2"}), new NgramContainer(new String[] {"0", "?", "2", "3"}), new NgramContainer(new String[] {"-1", "0", "?", "2"})};*/ /** * a set of features used as complementary for main features. */ private static NgramContainer[] combinationFeatureList = {new NgramContainer(new String[] {"-1", "0", "1", "2", "3"}), new NgramContainer(new String[] {"-1", "0", "1", "2"}), new NgramContainer(new String[] {"0", "1", "2", "3"}), new NgramContainer(new String[] {"0", "1", "2"})}; /*new NgramContainer(new String[] {"0", "1", "2"}), new NgramContainer(new String[] {"0", "1", "2", "3"}), new NgramContainer(new String[] {"-1", "0", "1", "2"})};*/ private static NgramContainer[] classTypeFeatures = {new NgramContainer(new String[] {"class", "?"}), new NgramContainer(new String[] {"pos"}), new NgramContainer(new String[] {"preposition", "?"})}; /** * Use this method to extract all the features of a given context (a 5-gram as in here) * defined in FeatureHandler.featureList * @param context the context to extract features from * @return a set of extracted features of the given context */ public static NgramContainer[] extractFeaturesOfContext(NgramContainer context){ NgramContainer[] result = new NgramContainer[featureList.length]; int indexInContext; int innerBounds; for (int index=0; index<featureList.length ; ++index){ if (isNonSimpleFeature(featureList[index])){ result[index] = featureList[index]; } else { result[index] = new NgramContainer(featureList[index].getSize()); innerBounds = result[index].getSize(); for (int j=0; j<innerBounds ; ++j){ if (featureList[index].getMemberValue(j).equals(FeatureHandler.nullTokenIdentifier)) result[index].setMemberValue(j, FeatureHandler.nullTokenIdentifier); else{ indexInContext = Integer.parseInt(featureList[index].getMemberValue(j)); indexInContext += 1; result[index].setMemberValue(j, context.getMemberValue(indexInContext)); } } } } return result; } /** * Use this method to extract all the features of a given context (a 5-gram as in here) * defined in FeatureHandler.featureList * @param context the context to extract features from * @return a set of extracted features of the given context */ public static NgramContainer[] extractFeaturesOfContext(NgramContainer context, NgramContainer POSTagscontext){ NgramContainer[] result = new NgramContainer[featureList.length]; int indexInContext; int innerBounds; for (int index=0; index<featureList.length ; ++index){ if (isNonSimpleFeature(featureList[index])){ result[index] = featureList[index]; } else { result[index] = new NgramContainer(featureList[index].getSize()); innerBounds = result[index].getSize(); for (int j=0; j<innerBounds ; ++j){ if (featureList[index].getMemberValue(j).equals(FeatureHandler.nullTokenIdentifier)) result[index].setMemberValue(j, FeatureHandler.nullTokenIdentifier); else{ indexInContext = Integer.parseInt(featureList[index].getMemberValue(j)); indexInContext += 1; result[index].setMemberValue(j, context.getMemberValue(indexInContext)); } } } } return result; } /** * Use this method to extract combined form of all the features of a given context (a 5-gram as in here) * defined in FeatureHandler.combinationFeatureList * @param context the context to extract features from * @return a set of extracted features in combined form */ public static NgramContainer[] extractFeaturesInCombinedFormOfContext(NgramContainer context){ NgramContainer[] result = new NgramContainer[combinationFeatureList.length]; int indexInContext; int innerBounds; for (int index=0; index<combinationFeatureList.length ; ++index){ result[index] = new NgramContainer(combinationFeatureList[index].getSize()); innerBounds = result[index].getSize(); for (int j=0; j<innerBounds ; ++j){ indexInContext = Integer.parseInt(combinationFeatureList[index].getMemberValue(j)); indexInContext += 1; result[index].setMemberValue(j, context.getMemberValue(indexInContext)); } } return result; } public static boolean isTemplate(NgramContainer ngramOfFeature){ return ngramOfFeature.hasMember(FeatureHandler.nullTokenIdentifier); } /** * Use this method to overwrite default features and use features specified in a given file. * features should be defined using indexed references to words occurring in a context, * after that comes a ';' and combined form of features should be specified in the same manner. * @param featureFileAddress address of a given features file */ public static void readFeaturesFromFile(String featureFileAddress){ TextFileInput fileInput = new TextFileInput(featureFileAddress); String line; ArrayList<NgramContainer> features = new ArrayList<NgramContainer>(); ArrayList<NgramContainer> featuresInCombinedForm = new ArrayList<NgramContainer>(); String currentFeature, currentFeatureInCombinedForm; while ((line = fileInput.readLine()) != null){ if (line.indexOf("#") == 0 || line.trim().equals("")) //this is a comment line, ignore this continue; currentFeature = line.split(";")[0]; currentFeatureInCombinedForm = line.split(";")[1]; features.add( new NgramContainer( getTokens(currentFeature) ) ); featuresInCombinedForm.add( new NgramContainer( getTokens(currentFeatureInCombinedForm) ) ); } featureList = features.toArray(new NgramContainer[features.size()]); combinationFeatureList = featuresInCombinedForm.toArray(new NgramContainer[featuresInCombinedForm.size()]); fileInput.close(); } private static String[] getTokens(String str){ StringTokenizer tokenizer = new StringTokenizer(str, " "); ArrayList<String> tokensList = new ArrayList<String>(); while (tokenizer.hasMoreTokens()){ tokensList.add(tokenizer.nextToken()); } return tokensList.toArray(new String[tokensList.size()]); } public static boolean isClassFeature(NgramContainer ngram) { return ngram.equalsWithTemplate(classTypeFeatures[0]); } public static boolean isPOSFeature(NgramContainer ngram) { return ngram.getMemberValue(0).equals(classTypeFeatures[1].getMemberValue(0)); } public static boolean isPrepositionFeature(NgramContainer ngram) { return ngram.equalsWithTemplate(classTypeFeatures[2]); } public static boolean isNonSimpleFeature(NgramContainer ngram){ return getTypeOfFeature(ngram) != FeatureType.Simple; } public static double computePMIForPair(int totalFrequency, NgramContainer ngram1, NgramContainer ngram2, NgramContainer combinedForm, GraphContainerAbstract graph) { double result = 0; int countOfNgram1, countOfNgram2, countOfCombination; switch (getTypeOfFeature(ngram2)){ case Simple: countOfNgram1 = graph.getCountOfNgram(ngram1); countOfNgram2 = graph.getCountOfNgram(ngram2); countOfCombination = graph.getCountOfNgram(combinedForm); result = main.java.PMI.PMIUtility.calculatePMI(totalFrequency, countOfCombination, countOfNgram1, countOfNgram2); break; case IsClass: if (graph.getDictionaryOfClasses().containsKey(combinedForm.getMemberValue(0))) result = main.java.PMI.PMIUtility.calculatePMI(totalFrequency, 1, graph.getCountOfNgram(ngram1), 1); break; case IsPreposition: if (graph.getDictionaryOfPrepositions().containsKey(combinedForm.getMemberValue(0))) result = main.java.PMI.PMIUtility.calculatePMI(totalFrequency, 1, graph.getCountOfNgram(ngram1), 1); break; case POS: NgramContainer posFeature = getMainPartOfNonSimpleFeature(ngram2); countOfNgram1 = graph.getCountOfNgram(ngram1); countOfNgram2 = graph.getNgramStatMapForPOS().getValueOf(posFeature); countOfCombination = graph.getNgramPairStatMapForPOS().getValueOf(ngram1, posFeature); result = main.java.PMI.PMIUtility.calculatePMI(totalFrequency, countOfCombination, countOfNgram1, countOfNgram2); break; } return result; } public static FeatureType getTypeOfFeature(NgramContainer ngram){ FeatureType result = FeatureType.Simple; if (FeatureHandler.isClassFeature(ngram)) result = FeatureType.IsClass; else if (FeatureHandler.isPOSFeature(ngram)) result = FeatureType.POS; else if (FeatureHandler.isPrepositionFeature(ngram)) result = FeatureType.IsPreposition; return result; } public static NgramContainer getMainPartOfNonSimpleFeature(NgramContainer nonSimpleFeature){ return nonSimpleFeature.getSubNgram(1); } }
11,358
43.027132
129
java
g-ssl-crf
g-ssl-crf-master/src/GraphConstruct/src/main/java/PMI/Struct/NodePairFeatureContainer.java
package main.java.PMI.Struct; import main.java.TextToNgram.NgramContainer; /** * Created with IntelliJ IDEA. * User: masouD * Date: 12/31/13 * Time: 5:11 PM * To change this template use File | Settings | File Templates. */ public class NodePairFeatureContainer { private NgramContainer ngram; private double[] nodeScores; private boolean[] valueSet; public NodePairFeatureContainer(NgramContainer ngram){ this.ngram = ngram; nodeScores = new double[2]; nodeScores[0] = 0; nodeScores[1] = 0; valueSet = new boolean[2]; valueSet[0] = false; valueSet[1] = false; } public NgramContainer getNgram() { return ngram; } public void setNgram(NgramContainer ngram) { this.ngram = ngram; } public double getNodeScore(int index) { return nodeScores[index]; } public void setNodeScore(int memberIndex, double memberScore) { this.nodeScores[memberIndex] = memberScore; this.valueSet[memberIndex] = true; } public boolean isSet(int index){ return valueSet[index]; } public NodePairFeatureContainer makeCopy() { NodePairFeatureContainer copy = new NodePairFeatureContainer(this.ngram); copy.nodeScores[0] = this.nodeScores[0]; copy.nodeScores[1] = this.nodeScores[1]; copy.valueSet[0] = this.valueSet[0]; copy.valueSet[1] = this.valueSet[1]; return copy; } }
1,482
24.135593
81
java
g-ssl-crf
g-ssl-crf-master/src/GraphConstruct/src/main/java/PMI/Struct/NodePairFeatureSetContainer.java
package main.java.PMI.Struct; import main.java.TextToNgram.NgramContainer; import main.java.Utility.Config; import java.util.ArrayList; /** * Created with IntelliJ IDEA. * User: masouD * Date: 12/31/13 * Time: 5:09 PM * To change this template use File | Settings | File Templates. */ public class NodePairFeatureSetContainer { private ArrayList<NodePairFeatureContainer> featureMap; public NodePairFeatureSetContainer(){ featureMap = new ArrayList<NodePairFeatureContainer>(); } public int add(NgramContainer ngram){ int nodeIndex = this.indexOf(ngram); if (nodeIndex < 0){ //node does not exist, create a new node nodeIndex = featureMap.size(); featureMap.add(nodeIndex, new NodePairFeatureContainer(ngram)); } return nodeIndex; } public int indexOf(NgramContainer ngram){ int result = -1; for (int i=0; i<this.featureMap.size() ; ++i) if (this.featureMap.get(i).getNgram().equals(ngram)){ result = i; break; } return result; } public boolean isSet(int nodeIndex, int memberIndex){ return nodeIndex >= 0 && this.featureMap.get(nodeIndex).isSet(memberIndex); } public void setScore(int nodeIndex, int memberIndex, double memberScore){ this.featureMap.get(nodeIndex).setNodeScore(memberIndex, memberScore); } public double measureSimilarity(){ double dotSum = 0; double sumOfSquaresNode1 = 0, sumOfSquaresNode2 = 0; for (NodePairFeatureContainer feature : this.featureMap) { dotSum += feature.getNodeScore(0) * feature.getNodeScore(1); sumOfSquaresNode1 += feature.getNodeScore(0) * feature.getNodeScore(0); sumOfSquaresNode2 += feature.getNodeScore(1) * feature.getNodeScore(1); } sumOfSquaresNode1 = Math.sqrt(sumOfSquaresNode1); sumOfSquaresNode2 = Math.sqrt(sumOfSquaresNode2); if (Config.pmiSmoothing) dotSum += Config.pmiSmoothingEpsilon; double result = dotSum / (sumOfSquaresNode1 * sumOfSquaresNode2); if (Double.isNaN(result)) result = 0; return result; } public NodePairFeatureSetContainer makeCopy() { NodePairFeatureSetContainer copy = new NodePairFeatureSetContainer(); for (NodePairFeatureContainer aFeatureMap : featureMap) { copy.featureMap.add(aFeatureMap.makeCopy()); } return copy; } public double measureSimilarity(NodePairFeatureSetContainer featureSetContainerNode2) { int nodeIndex; for (NodePairFeatureContainer featureContainer : featureSetContainerNode2.featureMap){ nodeIndex = this.add(featureContainer.getNgram()); this.setScore(nodeIndex, 1, featureContainer.getNodeScore(0)); } return this.measureSimilarity(); } }
2,948
32.134831
94
java
g-ssl-crf
g-ssl-crf-master/src/GraphConstruct/src/main/java/CRF/CRFFileReader.java
package main.java.CRF; import main.java.Utility.TextFileInput; import java.util.ArrayList; import java.util.StringTokenizer; /** * Copyright: Masoud Kiaeeha, Mohammad Aliannejadi * This work is licensed under the Creative Commons Attribution-NonCommercial 4.0 * International License. To view a copy of this license, visit * http://creativecommons.org/licenses/by-nc/4.0/. */ public class CRFFileReader { protected TextFileInput fileInput; protected String wordClassSentence, nextWordClassSentence, wordSentence, nextWordSentence; protected ArrayList<Integer> labels, nextLabels; protected boolean hasMoreSentences; public CRFFileReader(String fileAddress){ this.hasMoreSentences = true; fileInput = new TextFileInput(fileAddress); this.readNext(); } public boolean hasNext(){ return this.hasMoreSentences; } public void getNext(){ this.wordClassSentence = this.nextWordClassSentence; this.wordSentence = this.nextWordSentence; this.labels = this.nextLabels; this.readNext(); } protected void readNext(){ if (!this.hasMoreSentences) return; String line = this.fileInput.readLine(); while (line != null && isEmptyString(line)){ line = fileInput.readLine(); } if (line == null){ this.hasMoreSentences = false; this.setStateToNull(); }else { this.hasMoreSentences = true; this.readOneSentence(line); } } protected void readOneSentence(String line){ initializeState(); StringTokenizer tokenizer; while (line != null && !isEmptyString(line)){ tokenizer = new StringTokenizer(line, " "); this.nextWordSentence += tokenizer.nextToken() + " "; this.nextWordClassSentence += tokenizer.nextToken() + " "; this.nextLabels.add(Integer.parseInt(tokenizer.nextToken())); line = this.fileInput.readLine(); } this.nextWordSentence = this.nextWordSentence.substring(0, this.nextWordSentence.length() - 1); this.nextWordClassSentence = this.nextWordClassSentence.substring(0, this.nextWordClassSentence.length() - 1);//remove the extra space (" ") added to the end of sentence } protected void initializeState() { this.nextWordSentence = ""; this.nextWordClassSentence = ""; this.nextLabels = new ArrayList<Integer>(); } protected void setStateToNull(){ this.nextWordClassSentence = null; this.nextWordSentence = null; this.nextLabels = null; } protected boolean isEmptyString(String line) { return line.trim().equals(""); } public void close(){ fileInput.close(); } public String getWordClassSentence() { return this.wordClassSentence; } public String getWordSentence() { return this.wordSentence; } public ArrayList<Integer> getLabels(){ return this.labels; } }
3,090
27.62037
177
java
g-ssl-crf
g-ssl-crf-master/src/GraphConstruct/src/main/java/CRF/CRFFileReaderWithPOSTags.java
package main.java.CRF; import java.util.ArrayList; import java.util.StringTokenizer; /** * Copyright: Masoud Kiaeeha, Mohammad Aliannejadi * This work is licensed under the Creative Commons Attribution-NonCommercial 4.0 * International License. To view a copy of this license, visit * http://creativecommons.org/licenses/by-nc/4.0/. */ public class CRFFileReaderWithPOSTags extends CRFFileReader { protected String POSTagSentence, nextPOSTagSentence; public CRFFileReaderWithPOSTags(String fileAddress){ super(fileAddress); } public void getNext(){ this.POSTagSentence = this.nextPOSTagSentence; super.getNext(); } protected void readOneSentence(String line){ this.initializeState(); StringTokenizer tokenizer; while (line != null && !isEmptyString(line)){ tokenizer = new StringTokenizer(line, " "); this.nextWordSentence += tokenizer.nextToken() + " "; this.nextWordClassSentence += tokenizer.nextToken() + " "; this.nextLabels.add(Integer.parseInt(tokenizer.nextToken())); this.nextPOSTagSentence += tokenizer.nextToken() + " "; line = this.fileInput.readLine(); } this.nextWordSentence = this.nextWordSentence.substring(0, this.nextWordSentence.length() - 1); this.nextWordClassSentence = this.nextWordClassSentence.substring(0, this.nextWordClassSentence.length() - 1);//remove the extra space (" ") added to the end of sentence this.nextPOSTagSentence = this.nextPOSTagSentence.substring(0, this.nextPOSTagSentence.length() - 1); } protected void initializeState() { super.initializeState(); this.nextPOSTagSentence = ""; } protected void setStateToNull(){ super.setStateToNull(); this.nextPOSTagSentence = null; } public String getPOSTagSentence(){ return this.POSTagSentence; } }
1,948
33.192982
177
java
g-ssl-crf
g-ssl-crf-master/src/GraphConstruct/src/main/java/Text/MessagePrinter.java
package main.java.Text; public class MessagePrinter { public static void Print (String msg) { System.out.println(msg); } public static void PrintAndDie(String msg) { Print(msg); printHelpMessage(); System.exit(1); } private static void printHelpMessage() { System.out.println(); System.out.println("Input arguments format:"); System.out.println("\"-text [fileAddress]\" specifies the address of input text file. Input file should be in" + " standard CRF input format"); System.out.println("\"-output [fileAddress]\" output file name format. Indexed CRF file, word class dictionary" + " file and label dictionary file will be save in files named as [fileAddress][.predefined postfix]"); } }
814
32.958333
121
java
g-ssl-crf
g-ssl-crf-master/src/GraphConstruct/src/main/java/Text/WordDictionary.java
package main.java.Text; import main.java.Utility.Config; import main.java.Utility.TextFileInput; import java.util.Hashtable; import java.util.StringTokenizer; /** * Copyright: Masoud Kiaeeha, Mohammad Aliannejadi * This work is licensed under the Creative Commons Attribution-NonCommercial 4.0 * International License. To view a copy of this license, visit * http://creativecommons.org/licenses/by-nc/4.0/. */ public class WordDictionary { private Hashtable<Integer, String> wordLookUpTable; private static final float tableLoadFactor = (float)0.8; private static final int tableInitialCapacity = 400; public WordDictionary(){ this.wordLookUpTable = new Hashtable<Integer, String>(WordDictionary.tableInitialCapacity, WordDictionary.tableLoadFactor); //insert 0 as "null_word" this.addEntry(Config.packageOutputDummyValue, Config.packageOutputDummyValue); } public String getEntry(int index){ return this.wordLookUpTable.get(index); } public String getEntry(String indexInStringFormat){ return this.getEntry(Integer.parseInt(indexInStringFormat)); } public void addEntry(int index, String value){ this.wordLookUpTable.put(index, value); } public void addEntry(String index, String value){ this.addEntry(Integer.parseInt(index), value); } public boolean containsValue(String value){ return wordLookUpTable.containsValue(value); } public void buildDictionaryFromFile(String fileName){ TextFileInput inputFile = new TextFileInput(fileName); String line; StringTokenizer tokenizer; String wordIndex,word; while ((line = inputFile.readLine()) != null){ tokenizer = new StringTokenizer(line, " "); if (tokenizer.countTokens() < 2) continue; wordIndex = tokenizer.nextToken(); word = tokenizer.nextToken(); this.addEntry(wordIndex, word); } inputFile.close(); } public boolean containsKey(String key) { return wordLookUpTable.containsKey(Integer.parseInt(key)); } }
2,175
29.647887
116
java
g-ssl-crf
g-ssl-crf-master/src/GraphConstruct/src/main/java/Text/CRFInputIndexer.java
package main.java.Text; import main.java.Utility.Defaults; import java.util.Hashtable; /** * Copyright: Masoud Kiaeeha, Mohammad Aliannejadi * This work is licensed under the Creative Commons Attribution-NonCommercial 4.0 * International License. To view a copy of this license, visit * http://creativecommons.org/licenses/by-nc/4.0/. */ public class CRFInputIndexer { private static String inputFileAddress, outputFileAddress; public static void main(String[] args) { processArguments(args); CRFInputHandler crfInputHandler = new CRFInputHandler(); crfInputHandler.convertSimpleCRFInputToIndexedFormat(inputFileAddress, outputFileAddress + Config.exportFileIndexedCRFPostfix, outputFileAddress + Config.exportFileWordClassDictionaryPostfix, outputFileAddress + Config.exportFileLabelDictionaryPostfix); } private static void processArguments(String[] args) { Hashtable<String, String> config = new Hashtable<String, String>(10, (float) 0.9); for (int i=0; i<args.length ; ++i){ if (args[i].startsWith("-")){ if (i+1 < args.length){ config.put(getCommandFromArg(args[i]), args[++i]); } } } if (config.containsKey("h") || config.containsKey("help")) MessagePrinter.PrintAndDie("help->"); inputFileAddress = Defaults.GetValueOrDie(config, "text"); outputFileAddress = Defaults.GetValueOrDie(config, "output"); } /** * returns the command without the first character e.g. given "-command" output would be "command" * @param arg the command string * @return the command without the first "-" character */ private static String getCommandFromArg(String arg) { return arg.substring(1, arg.length()).toLowerCase(); } }
1,892
36.86
102
java
g-ssl-crf
g-ssl-crf-master/src/GraphConstruct/src/main/java/Text/Config.java
package main.java.Text; /** * Copyright: Masoud Kiaeeha, Mohammad Aliannejadi * This work is licensed under the Creative Commons Attribution-NonCommercial 4.0 * International License. To view a copy of this license, visit * http://creativecommons.org/licenses/by-nc/4.0/. */ public class Config { public static final String defaultLogFileAddress = "CRFInputIndexer.log"; public static final String exportFileIndexedCRFPostfix = ".crfindexed"; public static final String exportFileWordClassDictionaryPostfix = ".wdic"; public static final String exportFileLabelDictionaryPostfix = ".ldic"; }
614
37.4375
81
java
g-ssl-crf
g-ssl-crf-master/src/GraphConstruct/src/main/java/Text/CRFInputHandler.java
package main.java.Text; import main.java.Utility.TextFileInput; import main.java.Utility.TextFileOutput; import java.util.Hashtable; import java.util.StringTokenizer; /** * Copyright: Masoud Kiaeeha, Mohammad Aliannejadi * This work is licensed under the Creative Commons Attribution-NonCommercial 4.0 * International License. To view a copy of this license, visit * http://creativecommons.org/licenses/by-nc/4.0/. */ public class CRFInputHandler { private static final int wordClassStartingIndex = 3; private static final int labelStartingIndex = 0; public void convertSimpleCRFInputToIndexedFormat(String fileAddress, String outputFileAddress, String outputWordClassDictionaryFile, String outputLabelDictionaryFile){ TextFileInput fileInput = new TextFileInput(fileAddress); TextFileOutput fileOutput = new TextFileOutput(outputFileAddress); Hashtable<Integer, String> indexToWordClassMap = new Hashtable<Integer, String>(300, (float)0.8); Hashtable<String, Integer> wordClassToIndexMap = new Hashtable<String, Integer>(300, (float)0.8); Hashtable<Integer, String> indexToLabelMap = new Hashtable<Integer, String>(300, (float)0.8); Hashtable<String, Integer> labelToIndexMap = new Hashtable<String, Integer>(300, (float)0.8); int wordClassIndex = wordClassStartingIndex, labelIndex = labelStartingIndex; String line; StringTokenizer tokenizer; String word, wordClass, label; while ((line = fileInput.readLine()) != null){ tokenizer = new StringTokenizer(line, " "); if (tokenizer.countTokens() == 3){ word = tokenizer.nextToken(); wordClass = tokenizer.nextToken(); if (!indexToWordClassMap.contains(wordClass)){ indexToWordClassMap.put(wordClassIndex, wordClass); wordClassToIndexMap.put(wordClass, wordClassIndex); ++wordClassIndex; } label = tokenizer.nextToken(); if (!indexToLabelMap.contains(label)){ indexToLabelMap.put(labelIndex, label); labelToIndexMap.put(label, labelIndex); ++labelIndex; } fileOutput.writeLine(word + " " + wordClassToIndexMap.get(wordClass) + " " + labelToIndexMap.get(label)); } else{ fileOutput.writeLine(line); } } TextFileOutput wordClassDictionary = new TextFileOutput(outputWordClassDictionaryFile); for (int i=wordClassStartingIndex; i<wordClassIndex ; ++i){ wordClassDictionary.writeLine(i + " " + indexToWordClassMap.get(i)); } wordClassDictionary.close(); TextFileOutput labelDictionary = new TextFileOutput(outputLabelDictionaryFile); for (int i=labelStartingIndex; i<labelIndex ; ++i){ labelDictionary.writeLine(i + " " + indexToLabelMap.get(i)); } labelDictionary.close(); fileOutput.close(); fileInput.close(); } }
3,215
40.766234
121
java
g-ssl-crf
g-ssl-crf-master/src/GraphConstruct/src/main/java/TextToNgram/NgramUtility.java
package main.java.TextToNgram; import main.java.Utility.Config; import main.java.Utility.TextFileInput; import main.java.Utility.TextFileOutput; import java.util.StringTokenizer; /** * Copyright: Masoud Kiaeeha, Mohammad Aliannejadi * This work is licensed under the Creative Commons Attribution-NonCommercial 4.0 * International License. To view a copy of this license, visit * http://creativecommons.org/licenses/by-nc/4.0/. */ public class NgramUtility { private int ngramSize = Utils.packageDefaultNgramSize; public void CreateNgramFileFromTextFile(String inputFileAddress, String outputFileAddress, int ingramSize){ String line; NgramContainer[] ngramSet; TextFileInput fileInput = new TextFileInput(inputFileAddress); TextFileOutput fileOutput = new TextFileOutput(outputFileAddress); ngramSize = ingramSize; while ((line = fileInput.readLine()) != null) { //ignore first line //todo: if input file is corrected next line of code should be removed fileInput.readLine(); //ignore one line because of duplicate sentence line = fileInput.readLine(); ngramSet = extractNgramsFromSentenceDefaultWithEscapeCharacters(line, ngramSize); for(int i=0; i<ngramSet.length ; i++){ for(int j=0; j<ngramSize ; j++){ fileOutput.write(ngramSet[i].getMemberValue(j)); fileOutput.write(Utils.packageOutputDelimiter); } fileOutput.write(Utils.packageOutputNewLineCharacter); } } fileOutput.close(); fileInput.close(); } /** * given sentence (as in a line of input file) this method creates the n-grams associated with the given sentence * and returns them as an array of type NgramContainer </br> * note: this method currently can only be used for uni-grams and tri-grams. This implementation considers first and * last words of a sentence as Begin_Of_Sentence and _End_Of_Sentence words. * @param line the sentence to process * @param sizeOfNgram size of each n-gram, e.g. sizeOfNgram=3 means 3-grams are intended * @return an array containing all the n-grams existing in the given sentence */ public NgramContainer[] extractNgramsFromSentenceDefaultWithEscapeCharacters(String line, int sizeOfNgram){ /* if (sizeOfNgram != 1 && sizeOfNgram != 3){ throw new IllegalArgumentException(Utils.packageExceptionPrefix + "[invalid use of method: extractNgramsFromSentenceDefaultWithEscapeCharacters] " + "value of ngramSize can only be 1 or 3"); } */ int offset = (sizeOfNgram / 2) + ((sizeOfNgram+1) % 2); if (offset<0) offset = 0; StringTokenizer stringTokenizer = new StringTokenizer(line, " "); int wordCount = stringTokenizer.countTokens(); //wordCount-2 means first and last characters of a sentence are BOS and EOS wordCount = wordCount - 2; NgramContainer wholeSentenceContainer = new NgramContainer(wordCount + (offset*2)); int i,j; for(i=0; i<offset ; ++i) wholeSentenceContainer.setMemberValue(i, Config.packageOutputDummyValue); stringTokenizer.nextToken();//ignore first word as BOS character for(j=0; j<wordCount ; ++j) wholeSentenceContainer.setMemberValue(i + j, stringTokenizer.nextToken()); j = i+j; for(i=0; i<offset ; ++i) wholeSentenceContainer.setMemberValue(i + j, Config.packageOutputDummyValue); int resultSetSize; if (sizeOfNgram % 2 == 1) resultSetSize = wordCount; else resultSetSize = wholeSentenceContainer.getSize() - sizeOfNgram + 1; NgramContainer[] resultSet = new NgramContainer[resultSetSize]; for(i=0; i<resultSetSize ; ++i){ resultSet[i] = new NgramContainer(sizeOfNgram); for(j=0; j< sizeOfNgram; ++j) resultSet[i].setMemberValue(j, wholeSentenceContainer.getMemberValue(i + j)); } return resultSet; } /** * given sentence (as in a line of input file) this method creates the n-grams associated with the given sentence * and returns them as an array of type NgramContainer </br> * @param line the sentence to process * @param sizeOfNgram size of each n-gram, e.g. sizeOfNgram=3 means 3-grams are intended * @return an array containing all the n-grams existing in the given sentence */ public NgramContainer[] extractNgramsFromSentence(String line, int sizeOfNgram){ if (line.trim().equals("")) return null; //todo: created this new method to handle standard CRF input int offset; if (sizeOfNgram == 1) offset = 1; else { offset = (sizeOfNgram / 2) + ((sizeOfNgram+1) % 2); if (offset<0) offset = 0; } StringTokenizer stringTokenizer = new StringTokenizer(line, " "); int wordCount = stringTokenizer.countTokens(); NgramContainer wholeSentenceContainer = new NgramContainer(wordCount + (offset*2)); int i,j; for(i=0; i<offset ; ++i) wholeSentenceContainer.setMemberValue(i, Config.packageOutputDummyValue); for(j=0; j<wordCount ; ++j) wholeSentenceContainer.setMemberValue(i + j, stringTokenizer.nextToken()); j = i+j; for(i=0; i<offset ; ++i) wholeSentenceContainer.setMemberValue(i + j, Config.packageOutputDummyValue); int resultSetSize; if (sizeOfNgram == 1){ resultSetSize = wordCount + (offset*2); } else{ if (sizeOfNgram % 2 == 1) resultSetSize = wordCount; else resultSetSize = wholeSentenceContainer.getSize() - sizeOfNgram + 1; } NgramContainer[] resultSet = new NgramContainer[resultSetSize]; for(i=0; i<resultSetSize ; ++i){ resultSet[i] = new NgramContainer(sizeOfNgram); for(j=0; j< sizeOfNgram; ++j) resultSet[i].setMemberValue(j, wholeSentenceContainer.getMemberValue(i + j)); } return resultSet; } /** * given sentence (as in a line of input file) this method creates the n-grams associated with the given sentence * and returns them as an array of type NgramContainer </br> * note: this method currently can only be used for uni-grams and tri-grams * @param line the sentence to process * @param sizeOfNgram size of each n-gram, e.g. sizeOfNgram=3 means 3-grams are intended * @return an array containing all the n-grams existing in the given sentence */ private NgramContainer[] extractNgramsFromSentenceDefaultOld(String line, int sizeOfNgram){ if (sizeOfNgram != 1 && sizeOfNgram != 3){ throw new IllegalArgumentException(Utils.packageExceptionPrefix + "[invalid use of method: extractNgramsFromSentenceDefaultWithEscapeCharacters] " + "value of ngramSize can only be 1 or 3"); } int offset = (sizeOfNgram - 2); if (offset<0) offset = 0; StringTokenizer stringTokenizer = new StringTokenizer(line, " "); int wordCount = stringTokenizer.countTokens(); NgramContainer wholeSentenceContainer = new NgramContainer(wordCount + (offset*2)); int i,j; for(i=0; i<offset ; ++i) wholeSentenceContainer.setMemberValue(i, Config.packageOutputDummyValue); for(j=0; j<wordCount ; ++j) wholeSentenceContainer.setMemberValue(i + j, stringTokenizer.nextToken()); j = i+j; for(i=0; i<offset ; ++i) wholeSentenceContainer.setMemberValue(i + j, Config.packageOutputDummyValue); NgramContainer[] resultSet = new NgramContainer[wordCount]; for(i=0; i<wordCount ; i++){ resultSet[i] = new NgramContainer(sizeOfNgram); for(j=0; j< sizeOfNgram; j++) resultSet[i].setMemberValue(j, wholeSentenceContainer.getMemberValue(i + j)); } return resultSet; } public NgramContainer sentenceToNgram(String ngramSentence){ StringTokenizer stringTokenizer = new StringTokenizer(ngramSentence, " "); int wordCount = stringTokenizer.countTokens(); NgramContainer result = new NgramContainer(wordCount); if(wordCount==0){ result = null; }else{ for(int j=0; j<wordCount ; ++j) result.setMemberValue(j, stringTokenizer.nextToken()); } return result; } }
8,774
41.597087
120
java