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
depends
depends-master/src/main/java/depends/extractor/python/union/PythonVersion.java
package depends.extractor.python.union; public enum PythonVersion { Autodetect(0), Python2(2), Python3(3); private final int value; PythonVersion(int value) { this.value = value; } public int getValue() { return value; } }
275
14.333333
39
java
depends
depends-master/src/main/java/depends/extractor/python/union/PythonParserBase.java
package depends.extractor.python.union; import org.antlr.v4.runtime.Parser; import org.antlr.v4.runtime.TokenStream; public abstract class PythonParserBase extends Parser { public PythonVersion Version = PythonVersion.Autodetect; protected PythonParserBase(TokenStream input) { super(input); } protected boolean CheckVersion(int version) { return Version == PythonVersion.Autodetect || version == Version.getValue(); } protected void SetVersion(int requiredVersion) { if (requiredVersion == 2) { Version = PythonVersion.Python2; } else if (requiredVersion == 3) { Version = PythonVersion.Python3; } } }
701
25
84
java
depends
depends-master/src/main/java/depends/extractor/java/JavaBuiltInType.java
/* MIT License Copyright (c) 2018-2019 Gang ZHANG Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package depends.extractor.java; import depends.entity.repo.BuiltInType; public class JavaBuiltInType extends BuiltInType{ @Override protected String[] getBuiltInTypeName() { return new String[]{ "void","int","double","char","byte","boolean","long","short","float", "BigDecimal","Integer","Double","Char","Byte","Boolean","Long","Short","Float", "String","Object","Class","Exception","StringBuilder", "Appendable","AutoCloseable","Cloneable","Comparable","Iterable","Readable", "Runnable","Thread.UncaughtExceptionHandler","Boolean","Byte","Character","Character.Subset", "Character.UnicodeBlock","ClassLoader","ClassValue","Compiler","Double","Enum", "InheritableThreadLocal","Math","Number","Package","Process", "ProcessBuilder","ProcessBuilder.Redirect","Runtime","RuntimePermission", "SecurityManager","StackTraceElement","StrictMath","StringBuffer", "System","Thread","ThreadGroup","ThreadLocal","Throwable","Void","ProcessBuilder.Redirect.Type", "Thread.State","ArithmeticException","ArrayIndexOutOfBoundsException", "ArrayStoreException","ClassCastException","ClassNotFoundException","CloneNotSupportedException", "EnumConstantNotPresentException","Exception","IllegalAccessException","IllegalArgumentException", "IllegalMonitorStateException","IllegalStateException","IllegalThreadStateException", "IndexOutOfBoundsException","InstantiationException","InterruptedException", "NegativeArraySizeException","NoSuchFieldException","NoSuchMethodException","NullPointerException", "NumberFormatException","ReflectiveOperationException","RuntimeException","SecurityException", "StringIndexOutOfBoundsException","TypeNotPresentException","UnsupportedOperationException","AbstractMethodError", "AssertionError","BootstrapMethodError","ClassCircularityError","ClassFormatError","Error","ExceptionInInitializerError", "IllegalAccessError","IncompatibleClassChangeError","InstantiationError","InternalError","LinkageError","NoClassDefFoundError" ,"NoSuchFieldError","NoSuchMethodError","OutOfMemoryError","StackOverflowError","ThreadDeath","UnknownError", "UnsatisfiedLinkError","UnsupportedClassVersionError","VerifyError","VirtualMachineError","Deprecated","Override", "SafeVarargs","SuppressWarnings", "Collection","Comparator","Deque","Enumeration","EventListener","Formattable","Iterator","List", "ListIterator","Map","Map.Entry","NavigableMap","NavigableSet","Observer","Queue","RandomAccess", "Set","SortedMap","SortedSet","AbstractCollection","AbstractList","AbstractMap","AbstractMap.SimpleEntry", "AbstractMap.SimpleImmutableEntry","AbstractQueue","AbstractSequentialList","AbstractSet","ArrayDeque", "ArrayList","Arrays","BitSet","Calendar","Collections","Currency","Date","Dictionary","EnumMap","EnumSet", "EventListenerProxy","EventObject","FormattableFlags","Formatter","GregorianCalendar","HashMap","HashSet", "Hashtable","IdentityHashMap","LinkedHashMap","LinkedHashSet","LinkedList","ListResourceBundle","Locale", "Locale.Builder","Objects","Observable","PriorityQueue","Properties","PropertyPermission", "PropertyResourceBundle","Random","ResourceBundle","ResourceBundle.Control","Scanner", "ServiceLoader","SimpleTimeZone","Stack","StringTokenizer","Timer","TimerTask","TimeZone", "TreeMap","TreeSet","UUID","Vector","WeakHashMap","Formatter.BigDecimalLayoutForm", "Locale.Category","ConcurrentModificationException","DuplicateFormatFlagsException", "EmptyStackException","FormatFlagsConversionMismatchException","FormatterClosedException", "IllegalFormatCodePointException","IllegalFormatConversionException","IllegalFormatException", "IllegalFormatFlagsException","IllegalFormatPrecisionException","IllegalFormatWidthException", "IllformedLocaleException","InputMismatchException","InvalidPropertiesFormatException","MissingFormatArgumentException", "MissingFormatWidthException","MissingResourceException","NoSuchElementException","TooManyListenersException", "UnknownFormatConversionException","UnknownFormatFlagsException","ServiceConfigurationError", "<Built-in>" }; } @Override protected String[] getBuiltInTypePrefix() { return new String[]{ "java.","javax.","com.sun." }; } }
5,368
62.164706
130
java
depends
depends-master/src/main/java/depends/extractor/java/JavaImportLookupStrategy.java
/* MIT License Copyright (c) 2018-2019 Gang ZHANG Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package depends.extractor.java; import depends.entity.Entity; import depends.entity.FileEntity; import depends.entity.PackageEntity; import depends.entity.repo.EntityRepo; import depends.extractor.UnsolvedBindings; import depends.importtypes.Import; import depends.relations.ImportLookupStrategy; import java.util.ArrayList; import java.util.List; import java.util.Set; public class JavaImportLookupStrategy extends ImportLookupStrategy{ public JavaImportLookupStrategy(EntityRepo repo) { super(repo); } @Override public Entity lookupImportedType(String name, FileEntity fileEntity) { //Java Strategy String importedString = fileEntity.importedSuffixMatch(name); if (importedString==null) return null; return repo.getEntity(importedString); } @Override public List<Entity> getImportedRelationEntities(List<Import> importedList) { ArrayList<Entity> result = new ArrayList<>(); for (Import importedItem:importedList) { Entity imported = repo.getEntity(importedItem.getContent()); if (imported==null) continue; if (imported instanceof PackageEntity) { //ignore wildcard import relation }else { result.add(imported); } } return result; } @Override public List<Entity> getImportedTypes(List<Import> importedList,Set<UnsolvedBindings> unsolvedBindings) { ArrayList<Entity> result = new ArrayList<>(); for (Import importedItem:importedList) { Entity imported = repo.getEntity(importedItem.getContent()); if (imported==null) { unsolvedBindings.add(new UnsolvedBindings(importedItem.getContent(),null)); continue; } if (imported instanceof PackageEntity) { //expand import of package to all classes under the package due to we dis-courage the behavior for (Entity child:imported.getChildren()) { if (child instanceof FileEntity) { child.getChildren().forEach(item->result.add(item)); }else { result.add(child); } } }else { result.add(imported); } } return result; } @Override public List<Entity> getImportedFiles(List<Import> importedList) { return new ArrayList<Entity>(); } @Override public boolean supportGlobalNameLookup() { return true; } }
3,270
29.858491
105
java
depends
depends-master/src/main/java/depends/extractor/java/JavaFileParser.java
/* MIT License Copyright (c) 2018-2019 Gang ZHANG Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package depends.extractor.java; import depends.entity.repo.EntityRepo; import depends.extractor.FileParser; import depends.relations.IBindingResolver; import org.antlr.v4.runtime.CharStream; import org.antlr.v4.runtime.CharStreams; import org.antlr.v4.runtime.CommonTokenStream; import org.antlr.v4.runtime.Lexer; import org.antlr.v4.runtime.atn.LexerATNSimulator; import org.antlr.v4.runtime.atn.ParserATNSimulator; import org.antlr.v4.runtime.atn.PredictionContextCache; import org.antlr.v4.runtime.tree.ParseTreeWalker; import java.io.IOException; public class JavaFileParser extends FileParser { private IBindingResolver bindingResolver; public JavaFileParser(EntityRepo entityRepo, IBindingResolver bindingResolver) { this.entityRepo = entityRepo; this.bindingResolver = bindingResolver; } @Override protected void parseFile(String fileFullPath) throws IOException { CharStream input = CharStreams.fromFileName(fileFullPath); Lexer lexer = new JavaLexer(input); lexer.setInterpreter(new LexerATNSimulator(lexer, lexer.getATN(), lexer.getInterpreter().decisionToDFA, new PredictionContextCache())); CommonTokenStream tokens = new CommonTokenStream(lexer); JavaParser parser = new JavaParser(tokens); ParserATNSimulator interpreter = new ParserATNSimulator(parser, parser.getATN(), parser.getInterpreter().decisionToDFA, new PredictionContextCache()); parser.setInterpreter(interpreter); JavaListener bridge = new JavaListener(fileFullPath, entityRepo, bindingResolver); ParseTreeWalker walker = new ParseTreeWalker(); try { walker.walk(bridge, parser.compilationUnit()); interpreter.clearDFA(); }catch (Exception e) { System.err.println("error encountered during parse..." ); e.printStackTrace(); } } }
2,924
39.625
158
java
depends
depends-master/src/main/java/depends/extractor/java/JavaListener.java
/* MIT License Copyright (c) 2018-2019 Gang ZHANG Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package depends.extractor.java; import depends.entity.*; import depends.entity.repo.EntityRepo; import depends.extractor.java.JavaParser.*; import depends.extractor.java.context.*; import depends.importtypes.ExactMatchImport; import depends.relations.IBindingResolver; import java.util.ArrayList; import java.util.List; public class JavaListener extends JavaParserBaseListener { private final JavaHandlerContext context; private final AnnotationProcessor annotationProcessor; private final ExpressionUsage expressionUsage; private final EntityRepo entityRepo; public JavaListener(String fileFullPath, EntityRepo entityRepo, IBindingResolver bindingResolver) { this.context = new JavaHandlerContext(entityRepo, bindingResolver); this.entityRepo = entityRepo; annotationProcessor = new AnnotationProcessor(); expressionUsage = new ExpressionUsage(context,entityRepo); context.startFile(fileFullPath); } //////////////////////// // Package @Override public void enterPackageDeclaration(PackageDeclarationContext ctx) { context.foundNewPackage(QualitiedNameContextHelper.getName(ctx.qualifiedName())); super.enterPackageDeclaration(ctx); } //////////////////////// // Import @Override public void enterImportDeclaration(ImportDeclarationContext ctx) { context.foundNewImport(new ExactMatchImport(ctx.qualifiedName().getText())); super.enterImportDeclaration(ctx); } /////////////////////// // Class or Interface // classDeclaration | enumDeclaration | interfaceDeclaration | /////////////////////// annotationTypeDeclaration @Override public void enterClassDeclaration(ClassDeclarationContext ctx) { if (ctx.IDENTIFIER()==null) return; context.foundNewType(GenericName.build(ctx.IDENTIFIER().getText()), ctx.getStart().getLine()); // implements if (ctx.typeList() != null) { for (int i = 0; i < ctx.typeList().typeType().size(); i++) { context.foundImplements(GenericName.build(ClassTypeContextHelper.getClassName(ctx.typeList().typeType().get(i)))); } } // extends relation if (ctx.typeType() != null) { context.foundExtends(GenericName.build(ClassTypeContextHelper.getClassName(ctx.typeType()))); } if (ctx.typeParameters() != null) { foundTypeParametersUse(ctx.typeParameters()); } annotationProcessor.processAnnotationModifier(ctx, TypeDeclarationContext.class ,"classOrInterfaceModifier.annotation",context.lastContainer()); super.enterClassDeclaration(ctx); } @Override public void exitClassDeclaration(ClassDeclarationContext ctx) { exitLastEntity(); super.exitClassDeclaration(ctx); } @Override public void enterEnumDeclaration(EnumDeclarationContext ctx) { context.foundNewType(GenericName.build(ctx.IDENTIFIER().getText()), ctx.getStart().getLine()); annotationProcessor.processAnnotationModifier(ctx, TypeDeclarationContext.class ,"classOrInterfaceModifier.annotation",context.lastContainer()); super.enterEnumDeclaration(ctx); } @Override public void enterAnnotationTypeDeclaration(AnnotationTypeDeclarationContext ctx) { context.foundNewType(GenericName.build(ctx.IDENTIFIER().getText()), ctx.getStart().getLine()); annotationProcessor.processAnnotationModifier(ctx, TypeDeclarationContext.class ,"classOrInterfaceModifier.annotation",context.lastContainer()); super.enterAnnotationTypeDeclaration(ctx); } @Override public void exitEnumDeclaration(EnumDeclarationContext ctx) { exitLastEntity(); super.exitEnumDeclaration(ctx); } /** * interfaceDeclaration : INTERFACE IDENTIFIER typeParameters? (EXTENDS * typeList)? interfaceBody ; */ @Override public void enterInterfaceDeclaration(InterfaceDeclarationContext ctx) { context.foundNewType(GenericName.build(ctx.IDENTIFIER().getText()), ctx.getStart().getLine()); // type parameters if (ctx.typeParameters() != null) { foundTypeParametersUse(ctx.typeParameters()); } // extends relation if (ctx.typeList() != null) { for (int i = 0; i < ctx.typeList().typeType().size(); i++) { context.foundExtends(ClassTypeContextHelper.getClassName(ctx.typeList().typeType().get(i))); } } annotationProcessor.processAnnotationModifier(ctx, TypeDeclarationContext.class ,"classOrInterfaceModifier.annotation",context.lastContainer()); super.enterInterfaceDeclaration(ctx); } @Override public void exitInterfaceDeclaration(InterfaceDeclarationContext ctx) { exitLastEntity(); super.exitInterfaceDeclaration(ctx); } @Override public void exitAnnotationTypeDeclaration(AnnotationTypeDeclarationContext ctx) { exitLastEntity(); super.exitAnnotationTypeDeclaration(ctx); } ///////////////////////// // Method @Override public void enterMethodDeclaration(MethodDeclarationContext ctx) { List<String> throwedType = QualitiedNameContextHelper.getNames(ctx.qualifiedNameList()); String methodName = ctx.IDENTIFIER().getText(); String returnedType = ClassTypeContextHelper.getClassName(ctx.typeTypeOrVoid()); FunctionEntity method = context.foundMethodDeclarator(methodName, returnedType, throwedType,ctx.getStart().getLine()); new FormalParameterListContextHelper(ctx.formalParameters(), method, entityRepo); if (ctx.typeParameters() != null) { List<GenericName> parameters = TypeParameterContextHelper.getTypeParameters(ctx.typeParameters()); method.addTypeParameter(parameters); } annotationProcessor.processAnnotationModifier(ctx, ClassBodyDeclarationContext.class,"modifier.classOrInterfaceModifier.annotation",context.lastContainer()); super.enterMethodDeclaration(ctx); } @Override public void exitMethodDeclaration(MethodDeclarationContext ctx) { exitLastEntity(); super.exitMethodDeclaration(ctx); } private void exitLastEntity() { context.exitLastedEntity(); } // interfaceMethodDeclaration // : interfaceMethodModifier* (typeTypeOrVoid | typeParameters annotation* typeTypeOrVoid) // IDENTIFIER formalParameters ('[' ']')* (THROWS qualifiedNameList)? methodBody @Override public void enterInterfaceMethodDeclaration(InterfaceMethodDeclarationContext ctx) { List<String> throwedType = QualitiedNameContextHelper.getNames(ctx.qualifiedNameList()); FunctionEntity method = context.foundMethodDeclarator(ctx.IDENTIFIER().getText(), ClassTypeContextHelper.getClassName(ctx.typeTypeOrVoid()), throwedType,ctx.getStart().getLine()); new FormalParameterListContextHelper(ctx.formalParameters(), method, entityRepo); if (ctx.typeParameters() != null) { foundTypeParametersUse(ctx.typeParameters()); } annotationProcessor.processAnnotationModifier(ctx, InterfaceBodyDeclarationContext.class,"modifier.classOrInterfaceModifier.annotation",context.lastContainer()); super.enterInterfaceMethodDeclaration(ctx); } @Override public void exitInterfaceMethodDeclaration(InterfaceMethodDeclarationContext ctx) { exitLastEntity(); super.exitInterfaceMethodDeclaration(ctx); } @Override public void enterConstructorDeclaration(ConstructorDeclarationContext ctx) { List<String> throwedType = QualitiedNameContextHelper.getNames(ctx.qualifiedNameList()); FunctionEntity method = context.foundMethodDeclarator(ctx.IDENTIFIER().getText(), ctx.IDENTIFIER().getText(), throwedType,ctx.getStart().getLine()); new FormalParameterListContextHelper(ctx.formalParameters(), method, entityRepo); method.addReturnType(context.currentType()); annotationProcessor.processAnnotationModifier(ctx, ClassBodyDeclarationContext.class,"modifier.classOrInterfaceModifier.annotation",context.lastContainer()); super.enterConstructorDeclaration(ctx); } @Override public void exitConstructorDeclaration(ConstructorDeclarationContext ctx) { exitLastEntity(); super.exitConstructorDeclaration(ctx); } ///////////////////////////////////////////////////////// // Field @Override public void enterFieldDeclaration(FieldDeclarationContext ctx) { List<String> varNames = VariableDeclaratorsContextHelper.getVariables(ctx.variableDeclarators()); String type = ClassTypeContextHelper.getClassName(ctx.typeType()); List<GenericName> typeArguments = ClassTypeContextHelper.getTypeArguments(ctx.typeType()); List<VarEntity> vars = context.foundVarDefinitions(varNames, type,typeArguments,ctx.getStart().getLine()); annotationProcessor.processAnnotationModifier(ctx, ClassBodyDeclarationContext.class,"modifier.classOrInterfaceModifier.annotation",vars); super.enterFieldDeclaration(ctx); } @Override public void enterConstDeclaration(ConstDeclarationContext ctx) { List<GenericName> typeArguments = ClassTypeContextHelper.getTypeArguments(ctx.typeType()); List<VarEntity> vars = context.foundVarDefinitions(VariableDeclaratorsContextHelper.getVariables(ctx.constantDeclarator()), ClassTypeContextHelper.getClassName(ctx.typeType()),typeArguments, ctx.getStart().getLine()); annotationProcessor.processAnnotationModifier(ctx, InterfaceBodyDeclarationContext.class,"modifier.classOrInterfaceModifier.annotation",vars); super.enterConstDeclaration(ctx); } @Override public void enterEnumConstant(EnumConstantContext ctx) { if (ctx.IDENTIFIER() != null) { context.foundEnumConstDefinition(ctx.IDENTIFIER().getText(),ctx.getStart().getLine()); } super.enterEnumConstant(ctx); } @Override public void enterAnnotationMethodRest(AnnotationMethodRestContext ctx) { context.foundMethodDeclarator(ctx.IDENTIFIER().getText(), ClassTypeContextHelper.getClassName(ctx.typeType()), new ArrayList<>(),ctx.getStart().getLine()); super.enterAnnotationMethodRest(ctx); } @Override public void exitAnnotationMethodRest(AnnotationMethodRestContext ctx) { exitLastEntity(); super.exitAnnotationMethodRest(ctx); } @Override public void enterAnnotationConstantRest(AnnotationConstantRestContext ctx) { // TODO: no variable type defined in annotation const? context.foundVarDefinitions(VariableDeclaratorsContextHelper.getVariables(ctx.variableDeclarators()), "", new ArrayList<>(), ctx.getStart().getLine()); super.enterAnnotationConstantRest(ctx); } /////////////////////////////////////////// // variables // TODO: all modifier have not processed yet. @Override public void enterLocalVariableDeclaration(LocalVariableDeclarationContext ctx) { List<GenericName> typeArguments = ClassTypeContextHelper.getTypeArguments(ctx.typeType()); context.foundVarDefinitions(VariableDeclaratorsContextHelper.getVariables((ctx.variableDeclarators())), ClassTypeContextHelper.getClassName(ctx.typeType()), typeArguments, ctx.getStart().getLine()); super.enterLocalVariableDeclaration(ctx); } public void enterEnhancedForControl(EnhancedForControlContext ctx) { List<GenericName> typeArguments = ClassTypeContextHelper.getTypeArguments(ctx.typeType()); context.foundVarDefinitions(VariableDeclaratorsContextHelper.getVariable((ctx.variableDeclaratorId())), ClassTypeContextHelper.getClassName(ctx.typeType()), typeArguments, ctx.getStart().getLine()); super.enterEnhancedForControl(ctx); } // resource // : variableModifier* classOrInterfaceType variableDeclaratorId '=' expression // ; @Override public void enterResource(ResourceContext ctx) { List<GenericName> typeArguments = ClassTypeContextHelper.getTypeArguments(ctx.classOrInterfaceType()); context.foundVarDefinition(ctx.variableDeclaratorId().IDENTIFIER().getText(), GenericName.build(IdentifierContextHelper.getName(ctx.classOrInterfaceType().IDENTIFIER())), typeArguments,ctx.getStart().getLine()); super.enterResource(ctx); } @Override public void enterExpression(ExpressionContext ctx) { Expression expr = expressionUsage.foundExpression(ctx); expr.setLine(ctx.getStart().getLine()); super.enterExpression(ctx); } ///////////////////////////////////////////// // Block @Override public void enterBlock(BlockContext ctx) { // TODO support block in java super.enterBlock(ctx); } @Override public void exitBlock(BlockContext ctx) { // TODO support block in java super.exitBlock(ctx); } /* type parameters <T> <T1,T2>, <> treat as USE */ private void foundTypeParametersUse(TypeParametersContext typeParameters) { for (int i = 0; i < typeParameters.typeParameter().size(); i++) { TypeParameterContext typeParam = typeParameters.typeParameter(i); if (typeParam.typeBound() != null) { for (int j = 0; j < typeParam.typeBound().typeType().size(); j++) { context.foundTypeParametes(GenericName.build(ClassTypeContextHelper.getClassName(typeParam.typeBound().typeType(j)))); } } context.currentType().addTypeParameter(GenericName.build(typeParam.IDENTIFIER().getText())); } } }
13,657
39.408284
163
java
depends
depends-master/src/main/java/depends/extractor/java/JavaProcessor.java
/* MIT License Copyright (c) 2018-2019 Gang ZHANG Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package depends.extractor.java; import depends.entity.repo.BuiltInType; import depends.extractor.AbstractLangProcessor; import depends.extractor.FileParser; import depends.relations.ImportLookupStrategy; import java.util.ArrayList; import java.util.List; import static depends.deptypes.DependencyType.*; public class JavaProcessor extends AbstractLangProcessor { private static final String JAVA_LANG = "java"; private static final String JAVA_SUFFIX = ".java"; public JavaProcessor() { } @Override public String supportedLanguage() { return JAVA_LANG; } @Override public String[] fileSuffixes() { return new String[] {JAVA_SUFFIX}; } @Override public FileParser createFileParser() { return new JavaFileParser(entityRepo, bindingResolver); } @Override public ImportLookupStrategy getImportLookupStrategy() { return new JavaImportLookupStrategy(entityRepo); } @Override public BuiltInType getBuiltInType() { return new JavaBuiltInType(); } @Override public List<String> supportedRelations() { ArrayList<String> depedencyTypes = new ArrayList<>(); depedencyTypes.add(IMPORT); depedencyTypes.add(CONTAIN); depedencyTypes.add(IMPLEMENT); depedencyTypes.add(INHERIT); depedencyTypes.add(CALL); depedencyTypes.add(PARAMETER); depedencyTypes.add(RETURN); depedencyTypes.add(SET); depedencyTypes.add(CREATE); depedencyTypes.add(USE); depedencyTypes.add(CAST); depedencyTypes.add(THROW); depedencyTypes.add(ANNOTATION); return depedencyTypes; } }
2,617
28.41573
78
java
depends
depends-master/src/main/java/depends/extractor/java/JavaHandlerContext.java
/* MIT License Copyright (c) 2018-2019 Gang ZHANG Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package depends.extractor.java; import depends.entity.Entity; import depends.entity.FileEntity; import depends.entity.PackageEntity; import depends.entity.repo.EntityRepo; import depends.extractor.HandlerContext; import depends.relations.IBindingResolver; public class JavaHandlerContext extends HandlerContext { public JavaHandlerContext(EntityRepo entityRepo, IBindingResolver bindingResolver) { super(entityRepo, bindingResolver); } public Entity foundNewPackage(String packageName) { Entity pkgEntity = entityRepo.getEntity(packageName); if (pkgEntity == null) { pkgEntity = new PackageEntity(packageName, idGenerator.generateId()); entityRepo.add(pkgEntity); } Entity.setParent(currentFileEntity,pkgEntity); return pkgEntity; } public FileEntity startFile(String fileName) { return super.startFile(false, fileName); } }
1,936
34.218182
85
java
depends
depends-master/src/main/java/depends/extractor/java/context/OpHelper.java
/* MIT License Copyright (c) 2018-2019 Gang ZHANG Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package depends.extractor.java.context; //: primary //| expression bop='.' // ( IDENTIFIER // | methodCall // | THIS // | NEW nonWildcardTypeArguments? innerCreator // | SUPER superSuffix // | explicitGenericInvocation // ) //| expression '[' expression ']' //| methodCall //| NEW creator //| '(' typeType ')' expression //| expression ('<' '<' | '>' '>' '>' | '>' '>') expression //| expression bop=INSTANCEOF typeType //| <assoc=right> expression // expression //| lambdaExpression // Java8 public class OpHelper { public static boolean isLogic(String op) { return op.equals("<") || op.equals(">") || op.equals("<=") || op.equals(">=") || op.equals("==") || op.equals("!=") || op.equals("&&") || op.equals("||") || op.equals("?"); } public static boolean isAssigment(String op) { return op.equals("=") || op.equals("+=") || op.equals("-=") || op.equals("*=") || op.equals("/=") || op.equals("&=") || op.equals("|=") || op.equals("^=") || op.equals(">>=") || op.equals(">>>=") || op.equals("<<=") || op.equals("%="); } public static boolean isIncrementalDecremental(String op) { return op.equals("++") || op.equals("--"); } }
2,246
35.241935
101
java
depends
depends-master/src/main/java/depends/extractor/java/context/FormalParameterListContextHelper.java
/* MIT License Copyright (c) 2018-2019 Gang ZHANG Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package depends.extractor.java.context; import java.util.ArrayList; import java.util.List; import org.antlr.v4.runtime.tree.TerminalNode; import depends.entity.FunctionEntity; import depends.entity.GenericName; import depends.entity.VarEntity; import depends.entity.repo.IdGenerator; import depends.extractor.java.JavaParser.FormalParameterContext; import depends.extractor.java.JavaParser.FormalParameterListContext; import depends.extractor.java.JavaParser.FormalParametersContext; import depends.extractor.java.JavaParser.LastFormalParameterContext; import depends.extractor.java.JavaParser.TypeTypeContext; import depends.extractor.java.JavaParser.VariableModifierContext; public class FormalParameterListContextHelper { FormalParameterListContext context; private IdGenerator idGenerator; private List<String> annotations; private FunctionEntity container; public FormalParameterListContextHelper(FormalParameterListContext formalParameterListContext,FunctionEntity container, IdGenerator idGenerator) { this.context = formalParameterListContext; this.container = container; annotations = new ArrayList<>(); this.idGenerator = idGenerator; if (context!=null) extractParameterTypeList(); } public FormalParameterListContextHelper(FormalParametersContext formalParameters,FunctionEntity container, IdGenerator idGenerator) { this(formalParameters.formalParameterList(),container,idGenerator); } public void extractParameterTypeList() { if (context != null) { if (context.formalParameter() != null) { for (FormalParameterContext p : context.formalParameter()) { foundParameterDefintion(p.typeType(),p.variableDeclaratorId().IDENTIFIER(),p.variableModifier()); } if (context.lastFormalParameter()!=null) { LastFormalParameterContext p = context.lastFormalParameter(); foundParameterDefintion(p.typeType(),p.variableDeclaratorId().IDENTIFIER(),p.variableModifier()); } } } return; } private void foundParameterDefintion(TypeTypeContext typeType, TerminalNode identifier, List<VariableModifierContext> variableModifier) { GenericName type = GenericName.build(ClassTypeContextHelper.getClassName(typeType)); GenericName varName = GenericName.build(identifier.getText()); VarEntity varEntity = new VarEntity(varName,type,container,idGenerator.generateId()); container.addParameter(varEntity); for ( VariableModifierContext modifier:variableModifier) { if (modifier.annotation()!=null) { this.annotations.add(QualitiedNameContextHelper.getName(modifier.annotation().qualifiedName())); } } } public List<String> getAnnotations() { return annotations; } }
3,743
36.44
147
java
depends
depends-master/src/main/java/depends/extractor/java/context/QualitiedNameContextHelper.java
/* MIT License Copyright (c) 2018-2019 Gang ZHANG Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package depends.extractor.java.context; import java.util.ArrayList; import java.util.List; import depends.extractor.java.JavaParser.QualifiedNameContext; import depends.extractor.java.JavaParser.QualifiedNameListContext; public class QualitiedNameContextHelper { public static String getName(QualifiedNameContext ctx) { String r = ""; for (int i=0;i<ctx.IDENTIFIER().size();i++) { String dot = r.isEmpty()?"":"."; r = r + dot + ctx.IDENTIFIER(i).getText(); } return r; } public static List<String> getNames(QualifiedNameListContext qualifiedNameList) { List<String> names = new ArrayList<>(); if (qualifiedNameList == null) return names; for (QualifiedNameContext item : qualifiedNameList.qualifiedName()) { names.add(getName(item)); } return names; } }
1,873
34.358491
82
java
depends
depends-master/src/main/java/depends/extractor/java/context/ExpressionUsage.java
/* MIT License Copyright (c) 2018-2019 Gang ZHANG Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package depends.extractor.java.context; import org.antlr.v4.runtime.RuleContext; import depends.entity.Expression; import depends.entity.GenericName; import depends.entity.repo.IdGenerator; import depends.extractor.HandlerContext; import depends.extractor.java.JavaParser.ExpressionContext; import depends.extractor.java.JavaParser.MethodCallContext; import depends.extractor.java.JavaParser.PrimaryContext; public class ExpressionUsage { HandlerContext context; IdGenerator idGenerator; public ExpressionUsage(HandlerContext context,IdGenerator idGenerator) { this.context = context; this.idGenerator = idGenerator; } public Expression foundExpression(ExpressionContext ctx) { Expression parent = findParentInStack(ctx); /* create expression and link it with parent*/ Expression expression = new Expression(idGenerator.generateId()); context.lastContainer().addExpression(ctx,expression); expression.setParent(parent); if (ctx.primary()!=null) { tryFillExpressionTypeAndIdentifier(ctx.primary(),expression); return expression; } expression.setSet (isSet(ctx)); expression.setCall(ctx.methodCall()==null?false:true); expression.setLogic (isLogic(ctx)); expression.setDot(isDot(ctx)); if (ctx.creator()!=null ||ctx.innerCreator()!=null){ expression.setCreate( true); } /** * | expression bop='.' ( IDENTIFIER | methodCall | THIS | NEW nonWildcardTypeArguments? innerCreator | SUPER superSuffix | explicitGenericInvocation ) */ //method call if (ctx.methodCall()!=null) { expression.setIdentifier(getMethodCallIdentifier(ctx.methodCall())); expression.setCall(true); } //new if (ctx.NEW()!=null && ctx.creator()!=null) { expression.setRawType(CreatorContextHelper.getCreatorType(ctx.creator())); expression.setCall(true); expression.disableDriveTypeFromChild(); } if (ctx.typeCast()!=null) { expression.setCast(true); expression.setRawType(ctx.typeCast().typeType().getText()); expression.disableDriveTypeFromChild(); } if (ctx.bop!=null && ctx.bop.getText().equals("instanceof")) { expression.setCast(true); expression.setRawType(ctx.typeType().getText()); expression.disableDriveTypeFromChild(); } if (ctx.creator()!=null) { expression.disableDriveTypeFromChild(); } if (expression.isDot()) { if (ctx.IDENTIFIER()!=null) expression.setIdentifier(ctx.IDENTIFIER().getText()); else if (ctx.methodCall()!=null) expression.setIdentifier(getMethodCallIdentifier(ctx.methodCall())); else if (ctx.THIS()!=null) expression.setIdentifier("this"); else if (ctx.innerCreator()!=null) //innner creator like new List(){} expression.setIdentifier(ctx.innerCreator().IDENTIFIER().getText()); else if (ctx.SUPER()!=null) expression.setIdentifier("super"); return expression; } return expression; } private GenericName getMethodCallIdentifier(MethodCallContext methodCall) { if (methodCall.THIS()!=null) { return GenericName.build("this"); }else if (methodCall.SUPER()!=null) { return GenericName.build("super"); }else { return GenericName.build(methodCall.IDENTIFIER().getText()); } } private boolean isDot(ExpressionContext ctx) { if (ctx.bop!=null) if (ctx.bop.getText().equals(".")) return true; return false; } private boolean isLogic(ExpressionContext ctx) { if (ctx.bop != null) { if (OpHelper.isLogic(ctx.bop.getText())) { return true; } } return false; } public boolean isSet(ExpressionContext ctx) { if (ctx.bop != null) { if (OpHelper.isAssigment(ctx.bop.getText())) { return true; } } if (ctx.prefix != null) { if (OpHelper.isIncrementalDecremental(ctx.prefix.getText())) { return true; } } if (ctx.postfix != null) { if (OpHelper.isIncrementalDecremental(ctx.postfix.getText())) { return true; } } return false; } // primary // : '(' expression ')' // | THIS // | SUPER // | literal // | IDENTIFIER // | typeTypeOrVoid '.' CLASS // | nonWildcardTypeArguments (explicitGenericInvocationSuffix | THIS arguments) //Just USE relation // private void tryFillExpressionTypeAndIdentifier(PrimaryContext ctx, Expression expression) { if (ctx.expression()!=null) return; //1. we only handle leaf node. if there is still expression, // the type will be determined by child node in the expression if (ctx.literal()!=null) { //2. if it is a build-in type like "hello"(string), 10(integer), etc. expression.setRawType("<Built-in>"); expression.setIdentifier("<Literal>"); }else if (ctx.IDENTIFIER()!=null) { //2. if it is a var name, dertermine the type based on context. expression.setIdentifier(ctx.IDENTIFIER().getText()); }else if (ctx.typeTypeOrVoid()!=null) { //3. if given type directly expression.setRawType(ClassTypeContextHelper.getClassName(ctx.typeTypeOrVoid())); }else if (ctx.THIS()!=null){ expression.setIdentifier("this"); }else if (ctx.SUPER()!=null){ expression.setIdentifier("super"); } } private Expression findParentInStack(RuleContext ctx) { if (ctx==null) return null; if (ctx.parent==null) return null; if (context.lastContainer()==null) { return null; } if (context.lastContainer().expressions().containsKey(ctx.parent)) return context.lastContainer().expressions().get(ctx.parent); return findParentInStack(ctx.parent); } }
6,529
30.853659
130
java
depends
depends-master/src/main/java/depends/extractor/java/context/CreatorContextHelper.java
/* MIT License Copyright (c) 2018-2019 Gang ZHANG Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package depends.extractor.java.context; import java.util.List; import org.antlr.v4.runtime.tree.TerminalNode; import depends.extractor.java.JavaParser.CreatorContext; public class CreatorContextHelper { public static String getCreatorType(CreatorContext creator) { if (creator==null) return null; if (creator.createdName()==null) return creator.getText(); if (creator.createdName().IDENTIFIER()==null) return creator.createdName().getText(); if (creator.createdName().IDENTIFIER().size()>0) return buildName(creator.createdName().IDENTIFIER()); return null; } private static String buildName(List<TerminalNode> identifiers) { StringBuffer sb = new StringBuffer(); for(TerminalNode id:identifiers) { if (sb.length()>0) sb.append("."); sb.append(id); } return sb.toString(); } }
1,903
33
78
java
depends
depends-master/src/main/java/depends/extractor/java/context/AnnotationProcessor.java
/* MIT License Copyright (c) 2018-2019 Gang ZHANG Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package depends.extractor.java.context; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.stream.Collectors; import org.antlr.v4.runtime.RuleContext; import org.codehaus.plexus.util.StringUtils; import depends.entity.ContainerEntity; import depends.entity.GenericName; import depends.extractor.java.JavaParser.AnnotationContext; public class AnnotationProcessor { public AnnotationProcessor() { } public void processAnnotationModifier(RuleContext ctx, @SuppressWarnings("rawtypes") Class rootClass, String toAnnotationPath,ContainerEntity container) { List<ContainerEntity> list = new ArrayList<>() ; list.add(container); processAnnotationModifier(ctx, rootClass, toAnnotationPath, list); } public void processAnnotationModifier(RuleContext ctx, @SuppressWarnings("rawtypes") Class rootClass, String toAnnotationPath, List<?> containers) { while (true) { if (ctx == null) break; if (ctx.getClass().equals(rootClass)) break; ctx = ctx.parent; } if (ctx == null) return; try { Object r = ctx; String[] paths = toAnnotationPath.split("\\."); for (String path : paths) { r = invokeMethod(r, path); if (r == null) return; } Collection<AnnotationContext> contexts = new HashSet<>(); mergeElements(contexts, r); for (Object item : contexts) { AnnotationContext annotation = (AnnotationContext) item; String name = QualitiedNameContextHelper.getName(annotation.qualifiedName()); containers.stream().forEach(container->((ContainerEntity)container).addAnnotation(GenericName.build(name))); } } catch (Exception e) { return; } } private void mergeElements(Collection<AnnotationContext> collection, Object r) { if (r instanceof Collection) { for (Object item : (Collection<?>) r) { mergeElements(collection, item); } } else { if (r instanceof AnnotationContext) collection.add((AnnotationContext) r); } } private Object invokeMethod(Object r, String path) { if (StringUtils.isEmpty(path)) return null; if (r instanceof Collection) { Collection<?> list = (Collection<?>) r; return list.stream().map(item -> invokeMethod(item, path)).filter(item -> item != null) .collect(Collectors.toSet()); } try { Method m = r.getClass().getMethod(path); return m.invoke(r); } catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { return null; } } }
3,731
29.590164
112
java
depends
depends-master/src/main/java/depends/extractor/java/context/VariableDeclaratorsContextHelper.java
/* MIT License Copyright (c) 2018-2019 Gang ZHANG Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package depends.extractor.java.context; import java.util.ArrayList; import java.util.List; import depends.extractor.java.JavaParser.ConstantDeclaratorContext; import depends.extractor.java.JavaParser.VariableDeclaratorContext; import depends.extractor.java.JavaParser.VariableDeclaratorIdContext; import depends.extractor.java.JavaParser.VariableDeclaratorsContext; public class VariableDeclaratorsContextHelper { public static List<String> getVariables(VariableDeclaratorsContext variableDeclarators) { List<String> vars = new ArrayList<>(); if (variableDeclarators==null) return vars; for (VariableDeclaratorContext vContext:variableDeclarators.variableDeclarator()) { vars.add(vContext.variableDeclaratorId().IDENTIFIER().getText()); } return vars; } public static List<String> getVariables(List<ConstantDeclaratorContext> constantDeclarator) { List<String> vars = new ArrayList<>(); if (constantDeclarator==null) return vars; for (ConstantDeclaratorContext vContext:constantDeclarator) { vars.add(vContext.IDENTIFIER().getText()); } return vars; } public static List<String> getVariable(VariableDeclaratorIdContext variableDeclaratorIdContext) { List<String> vars = new ArrayList<>(); if (variableDeclaratorIdContext==null) return vars; vars.add(variableDeclaratorIdContext.IDENTIFIER().getText()); return vars; } }
2,451
36.723077
98
java
depends
depends-master/src/main/java/depends/extractor/java/context/TypeParameterContextHelper.java
/* MIT License Copyright (c) 2018-2019 Gang ZHANG Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package depends.extractor.java.context; import java.util.ArrayList; import java.util.List; import depends.entity.GenericName; import depends.extractor.java.JavaParser.TypeParameterContext; import depends.extractor.java.JavaParser.TypeParametersContext; public class TypeParameterContextHelper { public static List<GenericName> getTypeParameters(TypeParametersContext typeParameters) { ArrayList<GenericName> r = new ArrayList<>(); for(TypeParameterContext param:typeParameters.typeParameter()) { r.add(GenericName.build(param.IDENTIFIER().getText())); } return r; } }
1,665
36.022222
90
java
depends
depends-master/src/main/java/depends/extractor/java/context/ClassTypeContextHelper.java
/* MIT License Copyright (c) 2018-2019 Gang ZHANG Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package depends.extractor.java.context; import java.util.ArrayList; import java.util.List; import depends.entity.GenericName; import depends.extractor.java.JavaParser.ClassOrInterfaceTypeContext; import depends.extractor.java.JavaParser.TypeArgumentContext; import depends.extractor.java.JavaParser.TypeArgumentsContext; import depends.extractor.java.JavaParser.TypeTypeContext; import depends.extractor.java.JavaParser.TypeTypeOrVoidContext; public class ClassTypeContextHelper { /** typeType : annotation? (classOrInterfaceType | primitiveType) ('[' ']')* ; classOrInterfaceType : IDENTIFIER typeArguments? ('.' IDENTIFIER typeArguments?)* ; */ public static String getClassName(TypeTypeContext ctx) { if (ctx.primitiveType()!=null) return ctx.primitiveType().getText(); if (ctx.classOrInterfaceType()!=null) return getType(ctx.classOrInterfaceType()); return null; } private static String getType(ClassOrInterfaceTypeContext ctx) { String r = ""; for (int i=0;i<ctx.IDENTIFIER().size();i++) { String dot = r.isEmpty()?"":"."; r = r + dot + ctx.IDENTIFIER(i).getText(); } return r; } public static String getClassName(TypeTypeOrVoidContext typeTypeOrVoid) { if (typeTypeOrVoid.typeType()!=null) return getClassName(typeTypeOrVoid.typeType()); return "void"; } public static List<GenericName> getTypeArguments(TypeTypeContext ctx){ if (ctx.classOrInterfaceType()==null) return new ArrayList<>(); return getTypeArguments(ctx.classOrInterfaceType()); } public static List<GenericName> getTypeArguments(ClassOrInterfaceTypeContext type) { List<GenericName> typeArguments = new ArrayList<>(); for(TypeArgumentsContext args:type.typeArguments()) { for (TypeArgumentContext arg:args.typeArgument()) { if (arg.typeType()==null) continue; String argumentType = getClassName(arg.typeType()); List<GenericName> subTypes = getTypeArguments(arg.typeType()); if (argumentType!=null) typeArguments.add(GenericName.build(argumentType,subTypes)); } } return typeArguments; } }
3,164
34.561798
86
java
depends
depends-master/src/main/java/depends/extractor/java/context/IdentifierContextHelper.java
/* MIT License Copyright (c) 2018-2019 Gang ZHANG Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package depends.extractor.java.context; import java.util.List; import org.antlr.v4.runtime.tree.TerminalNode; public class IdentifierContextHelper { public static String getName(List<TerminalNode> identifiers) { String r = ""; for (TerminalNode id:identifiers) { String dot = r.isEmpty()?"":"."; r = r + dot + id.getText(); } return r; } }
1,438
34.097561
78
java
depends
depends-master/src/main/java/depends/extractor/golang/GoProcessor.java
/* MIT License Copyright (c) 2018-2019 Gang ZHANG Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package depends.extractor.golang; import depends.entity.repo.BuiltInType; import depends.extractor.AbstractLangProcessor; import depends.extractor.FileParser; import depends.relations.ImportLookupStrategy; import java.util.ArrayList; import java.util.List; import static depends.deptypes.DependencyType.*; public class GoProcessor extends AbstractLangProcessor { private static final String LANG = "go"; private static final String[] SUFFIX = new String[] { ".go" }; public GoProcessor() { super(); } @Override public String supportedLanguage() { return LANG; } @Override public String[] fileSuffixes() { return SUFFIX; } @Override public FileParser createFileParser() { return new GoFileParser( entityRepo, bindingResolver); } @Override public ImportLookupStrategy getImportLookupStrategy() { return new GoImportLookupStrategy(entityRepo); } @Override public BuiltInType getBuiltInType() { return new GoBuiltInType(); } @Override public List<String> supportedRelations() { ArrayList<String> depedencyTypes = new ArrayList<>(); depedencyTypes.add(IMPORT); depedencyTypes.add(CONTAIN); depedencyTypes.add(IMPLEMENT); depedencyTypes.add(INHERIT); depedencyTypes.add(CALL); depedencyTypes.add(PARAMETER); depedencyTypes.add(RETURN); depedencyTypes.add(SET); depedencyTypes.add(CREATE); depedencyTypes.add(USE); depedencyTypes.add(CAST); depedencyTypes.add(THROW); depedencyTypes.add(LINK); return depedencyTypes; } }
2,568
27.865169
78
java
depends
depends-master/src/main/java/depends/extractor/golang/GoImportLookupStrategy.java
/* MIT License Copyright (c) 2018-2019 Gang ZHANG Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package depends.extractor.golang; import depends.entity.Entity; import depends.entity.FileEntity; import depends.entity.PackageEntity; import depends.entity.repo.EntityRepo; import depends.extractor.UnsolvedBindings; import depends.importtypes.Import; import depends.relations.ImportLookupStrategy; import java.util.ArrayList; import java.util.List; import java.util.Set; public class GoImportLookupStrategy extends ImportLookupStrategy{ public GoImportLookupStrategy(EntityRepo repo) { super(repo); } public Entity lookupImportedType(String name, FileEntity fileEntity) { //Java Strategy String importedString = fileEntity.importedSuffixMatch(name); if (importedString==null) return null; return repo.getEntity(importedString); } @Override public List<Entity> getImportedRelationEntities(List<Import> importedList) { ArrayList<Entity> result = new ArrayList<>(); for (Import importedItem:importedList) { Entity imported = repo.getEntity(importedItem.getContent()); if (imported==null) continue; if (imported instanceof PackageEntity) { //ignore wildcard import relation }else { result.add(imported); } } return result; } @Override public List<Entity> getImportedTypes(List<Import> importedList, Set<UnsolvedBindings> unsolvedBindings) { ArrayList<Entity> result = new ArrayList<>(); for (Import importedItem:importedList) { Entity imported = repo.getEntity(importedItem.getContent()); if (imported==null) { unsolvedBindings.add(new UnsolvedBindings(importedItem.getContent(),null)); continue; } if (imported instanceof PackageEntity) { //expand import of package to all classes under the package due to we dis-courage the behavior for (Entity child:imported.getChildren()) { if (child instanceof FileEntity) { child.getChildren().forEach(item->result.add(item)); }else { result.add(child); } } }else { result.add(imported); } } return result; } @Override public List<Entity> getImportedFiles(List<Import> importedList) { return new ArrayList<Entity>(); } @Override public boolean supportGlobalNameLookup() { return true; } }
3,257
30.326923
106
java
depends
depends-master/src/main/java/depends/extractor/golang/GoBuiltInType.java
/* MIT License Copyright (c) 2018-2019 Gang ZHANG Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package depends.extractor.golang; import depends.entity.repo.BuiltInType; public class GoBuiltInType extends BuiltInType { @Override protected String[] getBuiltInTypeName() { return new String[]{ "<Built-in>", "break", "default", "func", "interface", "select", "case", "defer", "go", "map", "struct", "chan", "else", "goto", "package", "switch", "const", "fallthrough", "if", "range", "type", "continue", "for", "import", "return", "var", "append", "bool", "byte", "cap", "close", "complex", "complex64", "complex128", "uint16", "copy", "false", "float32", "float64", "imag", "int", "int8", "int16", "uint32", "int32", "int64", "iota", "len", "make", "new", "nil", "panic", "uint64", "print", "println", "real", "recover", "string", "true", "uint", "uint8", "uintptr", "_" }; } }
1,962
39.061224
78
java
depends
depends-master/src/main/java/depends/extractor/golang/GoFileParser.java
/* MIT License Copyright (c) 2018-2019 Gang ZHANG Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package depends.extractor.golang; import depends.entity.Entity; import depends.entity.FileEntity; import depends.entity.repo.EntityRepo; import depends.relations.IBindingResolver; import org.antlr.v4.runtime.CharStream; import org.antlr.v4.runtime.CharStreams; import org.antlr.v4.runtime.CommonTokenStream; import org.antlr.v4.runtime.Lexer; import org.antlr.v4.runtime.atn.LexerATNSimulator; import org.antlr.v4.runtime.atn.ParserATNSimulator; import org.antlr.v4.runtime.atn.PredictionContextCache; import org.antlr.v4.runtime.tree.ParseTreeWalker; import java.io.IOException; public class GoFileParser extends depends.extractor.FileParser{ private IBindingResolver bindingResolver; public GoFileParser(EntityRepo entityRepo, IBindingResolver bindingResolver) { this.entityRepo = entityRepo; this.bindingResolver = bindingResolver; } @Override protected void parseFile(String fileFullPath) throws IOException { CharStream input = CharStreams.fromFileName(fileFullPath); Lexer lexer = new GoLexer(input); lexer.setInterpreter(new LexerATNSimulator(lexer, lexer.getATN(), lexer.getInterpreter().decisionToDFA, new PredictionContextCache())); CommonTokenStream tokens = new CommonTokenStream(lexer); GoParser parser = new GoParser(tokens); ParserATNSimulator interpreter = new ParserATNSimulator(parser, parser.getATN(), parser.getInterpreter().decisionToDFA, new PredictionContextCache()); parser.setInterpreter(interpreter); GoListener bridge = new GoListener(fileFullPath, entityRepo, bindingResolver); ParseTreeWalker walker = new ParseTreeWalker(); try { walker.walk(bridge, parser.sourceFile()); Entity fileEntity = entityRepo.getEntity(fileFullPath); ((FileEntity)fileEntity).cacheAllExpressions(); interpreter.clearDFA(); bridge.done(); }catch (Exception e) { System.err.println("error encountered during parse..." ); e.printStackTrace(); } } }
3,079
40.066667
158
java
depends
depends-master/src/main/java/depends/extractor/golang/TypeSpecHelper.java
package depends.extractor.golang; public class TypeSpecHelper { private final GoParser.TypeSpecContext ctx; private final TypeDefHelper typeDefHelper; public TypeSpecHelper(GoParser.TypeSpecContext ctx) { this.ctx = ctx; this.typeDefHelper = new TypeDefHelper(ctx.type_()); } public String getIdentifier(){ return ctx.IDENTIFIER().getText(); } public TypeDefHelper getTypeDefHelper(){ return typeDefHelper; } }
479
24.263158
60
java
depends
depends-master/src/main/java/depends/extractor/golang/TypeDefHelper.java
package depends.extractor.golang; public class TypeDefHelper { private GoParser.Type_Context type; public TypeDefHelper(GoParser.Type_Context type_context) { this.type = type_context; //go to deepest type definition while(type.type_()!=null){ this.type = this.type.type_(); } } public boolean isTypeRef(){ return type.typeName()!=null; } public String getTypeRefName(){ if (!isTypeRef()) return null; return type.typeName().getText(); } public boolean isStruct(){ if (type.typeLit()==null) return false; if (type.typeLit().structType()!=null) return true; return false; } }
707
23.413793
62
java
depends
depends-master/src/main/java/depends/extractor/golang/FieldDeclHelper.java
package depends.extractor.golang; import org.antlr.v4.runtime.tree.TerminalNode; import java.util.ArrayList; import java.util.List; public class FieldDeclHelper { private String string; private String typeName = null; List<String> identifiers = null; private String anonymousField = null; public FieldDeclHelper(GoParser.FieldDeclContext ctx) { if (ctx.identifierList()!=null){ identifiers = new ArrayList<>(); for (TerminalNode identifier:ctx.identifierList().IDENTIFIER()){ this.identifiers.add(identifier.getText()); } } if (ctx.type_()!=null){ TypeDefHelper typeDefHelper = new TypeDefHelper(ctx.type_()); if (typeDefHelper.isTypeRef()){ this.typeName = typeDefHelper.getTypeRefName(); } else /*define new one*/{ //TOOD: } } if (ctx.string_()!=null){ string = ctx.string_().getText(); } if (ctx.anonymousField()!=null) { anonymousField = ctx.anonymousField().getText(); } } public List<String> getIdentifiers() { return this.identifiers; } public String getTypeName() { return typeName; } public String getAnonymousField() { return anonymousField; } public String getString() { return this.string; } }
1,435
25.109091
76
java
depends
depends-master/src/main/java/depends/extractor/golang/GoParserBase.java
package depends.extractor.golang; import org.antlr.v4.runtime.*; import java.util.List; /** * All parser methods that used in grammar (p, prev, notLineTerminator, etc.) * should start with lower case char similar to parser rules. */ public abstract class GoParserBase extends Parser { protected GoParserBase(TokenStream input) { super(input); } /** * Returns {@code true} iff on the current index of the parser's * token stream a token exists on the {@code HIDDEN} channel which * either is a line terminator, or is a multi line comment that * contains a line terminator. * * @return {@code true} iff on the current index of the parser's * token stream a token exists on the {@code HIDDEN} channel which * either is a line terminator, or is a multi line comment that * contains a line terminator. */ protected boolean lineTerminatorAhead() { // Get the token ahead of the current index. int possibleIndexEosToken = this.getCurrentToken().getTokenIndex() - 1; if (possibleIndexEosToken == -1) { return true; } Token ahead = _input.get(possibleIndexEosToken); if (ahead.getChannel() != Lexer.HIDDEN) { // We're only interested in tokens on the HIDDEN channel. return false; } if (ahead.getType() == GoLexer.TERMINATOR) { // There is definitely a line terminator ahead. return true; } if (ahead.getType() == GoLexer.WS) { // Get the token ahead of the current whitespaces. possibleIndexEosToken = this.getCurrentToken().getTokenIndex() - 2; ahead = _input.get(possibleIndexEosToken); } // Get the token's text and type. String text = ahead.getText(); int type = ahead.getType(); // Check if the token is, or contains a line terminator. return (type == GoLexer.COMMENT && (text.contains("\r") || text.contains("\n"))) || (type == GoLexer.TERMINATOR); } /** * Returns {@code true} if no line terminator exists between the specified * token offset and the prior one on the {@code HIDDEN} channel. * * @return {@code true} if no line terminator exists between the specified * token offset and the prior one on the {@code HIDDEN} channel. */ protected boolean noTerminatorBetween(int tokenOffset) { BufferedTokenStream stream = (BufferedTokenStream)_input; List<Token> tokens = stream.getHiddenTokensToLeft(stream.LT(tokenOffset).getTokenIndex()); if (tokens == null) { return true; } for (Token token : tokens) { if (token.getText().contains("\n")) return false; } return true; } /** * Returns {@code true} if no line terminator exists after any encounterd * parameters beyond the specified token offset and the next on the * {@code HIDDEN} channel. * * @return {@code true} if no line terminator exists after any encounterd * parameters beyond the specified token offset and the next on the * {@code HIDDEN} channel. */ protected boolean noTerminatorAfterParams(int tokenOffset) { BufferedTokenStream stream = (BufferedTokenStream)_input; int leftParams = 1; int rightParams = 0; int valueType; if (stream.LT(tokenOffset).getType() == GoLexer.L_PAREN) { // Scan past parameters while (leftParams != rightParams) { tokenOffset++; valueType = stream.LT(tokenOffset).getType(); if (valueType == GoLexer.L_PAREN){ leftParams++; } else if (valueType == GoLexer.R_PAREN) { rightParams++; } } tokenOffset++; return noTerminatorBetween(tokenOffset); } return true; } protected boolean checkPreviousTokenText(String text) { BufferedTokenStream stream = (BufferedTokenStream)_input; String prevTokenText = stream.LT(1).getText(); if (prevTokenText == null) return false; return prevTokenText.equals(text); } }
4,369
31.857143
98
java
depends
depends-master/src/main/java/depends/extractor/golang/GoListener.java
package depends.extractor.golang; import depends.entity.FunctionEntity; import depends.entity.GenericName; import depends.entity.VarEntity; import depends.entity.repo.EntityRepo; import depends.relations.IBindingResolver; import org.antlr.v4.runtime.tree.TerminalNode; import java.util.ArrayList; public class GoListener extends GoParserBaseListener { private final EntityRepo entityRepo; GoHandlerContext context; @Override public void enterSourceFile(GoParser.SourceFileContext ctx) { super.enterSourceFile(ctx); } public GoListener(String fileFullPath, EntityRepo entityRepo, IBindingResolver bindingResolver) { context = new GoHandlerContext(entityRepo, bindingResolver); context.startFile(fileFullPath); this.entityRepo = entityRepo; } @Override public void enterFunctionDecl(GoParser.FunctionDeclContext ctx) { String funcName = ctx.IDENTIFIER().getText(); context.foundMethodDeclarator(funcName,ctx.getStart().getLine()); foundFuncSignature(ctx.signature()); super.enterFunctionDecl(ctx); } @Override public void exitFunctionDecl(GoParser.FunctionDeclContext ctx) { context.exitLastedEntity(); super.exitFunctionDecl(ctx); } @Override public void enterPackageClause(GoParser.PackageClauseContext ctx) { context.foundPackageDeclaration(ctx.IDENTIFIER().getText()); super.enterPackageClause(ctx); } private void foundFuncSignature(GoParser.SignatureContext signature) { FunctionEntity func = (FunctionEntity) context.lastContainer(); if (signature.parameters()!=null) { for (GoParser.ParameterDeclContext param : signature.parameters().parameterDecl()) { if (param.identifierList() != null) { TypeDefHelper typeDefHelper = new TypeDefHelper(param.type_()); for (TerminalNode id : param.identifierList().IDENTIFIER()) { VarEntity varEntity = new VarEntity(GenericName.build(id.getText()), GenericName.build(typeDefHelper.getTypeRefName()), context.lastContainer(), entityRepo.generateId()); func.addParameter(varEntity); } } else/* with ... parameters*/ { } } } if (signature.result()!=null){ if(signature.result().parameters()!=null){ for (GoParser.ParameterDeclContext paramDecl:signature.result().parameters().parameterDecl()){ TypeDefHelper typeDefHelper = new TypeDefHelper(paramDecl.type_()); if (typeDefHelper.isTypeRef()) { func.addReturnType(GenericName.build(typeDefHelper.getTypeRefName())); }else{ System.err.println("TODO: unsupport return type"); } } } if (signature.result().type_()!=null){ TypeDefHelper typeDefHelper = new TypeDefHelper(signature.result().type_()); if (typeDefHelper.isTypeRef()) { func.addReturnType(GenericName.build(typeDefHelper.getTypeRefName())); }else{ System.err.println("TODO: unsupport return type"); } } System.err.println(signature.result().getText()); } } @Override public void enterTypeSpec(GoParser.TypeSpecContext ctx) { TypeSpecHelper specHelper = new TypeSpecHelper(ctx); if (specHelper.getTypeDefHelper().isTypeRef()){ context.foundNewAlias(specHelper.getIdentifier(),specHelper.getTypeDefHelper().getTypeRefName()); }else if (specHelper.getTypeDefHelper().isStruct()){ context.foundNewType(specHelper.getIdentifier(),ctx.getStart().getLine()); } super.enterTypeSpec(ctx); } @Override public void exitTypeSpec(GoParser.TypeSpecContext ctx) { TypeSpecHelper specHelper = new TypeSpecHelper(ctx); if (specHelper.getTypeDefHelper().isStruct()){ context.exitLastedEntity(); } super.exitTypeSpec(ctx); } // fieldDecl // : ({noTerminatorBetween(2)}? identifierList type_ | anonymousField) string_? // ; @Override public void enterFieldDecl(GoParser.FieldDeclContext ctx) { FieldDeclHelper fieldDeclHelper = new FieldDeclHelper(ctx); String typeName = fieldDeclHelper.getTypeName(); if (fieldDeclHelper.getIdentifiers()!=null){ for (String id:fieldDeclHelper.getIdentifiers()){ if (typeName==null){ System.err.println("TODO: unsupport fieldDecl without type"); } context.foundVarDefinition(id, GenericName.build(typeName),new ArrayList<>(),ctx.getStart().getLine()); } } if (fieldDeclHelper.getAnonymousField()!=null){ System.err.println("TODO: unsupport anonymousField"); } if (fieldDeclHelper.getString()!=null){ System.err.println("TODO: unsupport field with string " + fieldDeclHelper.getString()); } super.enterFieldDecl(ctx); } public void done() { } }
5,352
38.072993
119
java
depends
depends-master/src/main/java/depends/extractor/golang/GoHandlerContext.java
/* MIT License Copyright (c) 2018-2019 Gang ZHANG Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package depends.extractor.golang; import depends.entity.Entity; import depends.entity.FileEntity; import depends.entity.PackageEntity; import depends.entity.repo.EntityRepo; import depends.extractor.HandlerContext; import depends.relations.IBindingResolver; public class GoHandlerContext extends HandlerContext { public GoHandlerContext(EntityRepo entityRepo, IBindingResolver bindingResolver) { super(entityRepo, bindingResolver); } public Entity foundPackageDeclaration(String packageName){ Entity pkgEntity = entityRepo.getEntity(packageName); if (pkgEntity == null) { pkgEntity = new PackageEntity(packageName, idGenerator.generateId()); entityRepo.add(pkgEntity); } Entity.setParent(currentFileEntity,pkgEntity); return pkgEntity; } public FileEntity startFile(String fileName) { return super.startFile(false, fileName); } }
1,940
34.944444
83
java
depends
depends-master/src/main/java/depends/format/AbstractFormatDependencyDumper.java
/* MIT License Copyright (c) 2018-2019 Gang ZHANG Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package depends.format; import java.io.File; import depends.matrix.core.DependencyMatrix; public abstract class AbstractFormatDependencyDumper { protected String name; protected DependencyMatrix matrix; protected String outputDir; public AbstractFormatDependencyDumper(DependencyMatrix matrix, String projectName, String outputDir) { this.matrix = matrix; this.name = projectName; this.outputDir = outputDir; } public abstract boolean output(); public abstract String getFormatName(); protected String composeFilename() { return outputDir+File.separator+name; } }
1,665
33.708333
103
java
depends
depends-master/src/main/java/depends/format/FileAttributes.java
/* MIT License Copyright (c) 2018-2019 Gang ZHANG Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package depends.format; public class FileAttributes { private String schemaVersion = "1.0"; private String attributeName; public FileAttributes( String projectName) { this.attributeName = projectName + "-sdsm"; } public String getSchemaVersion() { return schemaVersion; } public String getAttributeName() { return this.attributeName; } }
1,470
33.209302
78
java
depends
depends-master/src/main/java/depends/format/DependencyDumper.java
/* MIT License Copyright (c) 2018-2019 Gang ZHANG Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package depends.format; import java.util.List; import depends.format.detail.DetailTextFormatDependencyDumper; import depends.format.dot.DotFormatDependencyDumper; import depends.format.dot.DotFullnameDependencyDumper; import depends.format.excel.ExcelXlsFormatDependencyDumper; import depends.format.excel.ExcelXlsxFormatDependencyDumper; import depends.format.json.JsonFormatDependencyDumper; import depends.format.plantuml.BriefPlantUmlFormatDependencyDumper; import depends.format.plantuml.PlantUmlFormatDependencyDumper; import depends.format.xml.XmlFormatDependencyDumper; import depends.matrix.core.DependencyMatrix; import edu.emory.mathcs.backport.java.util.Arrays; public class DependencyDumper { private DependencyMatrix dependencyMatrix; public DependencyDumper(DependencyMatrix dependencies) { this.dependencyMatrix = dependencies; } public void outputResult(String projectName, String outputDir, String[] outputFormat) { outputDeps(projectName,outputDir,outputFormat); } private final void outputDeps(String projectName, String outputDir, String[] outputFormat) { @SuppressWarnings("unchecked") List<String> formatList = Arrays.asList(outputFormat); AbstractFormatDependencyDumper[] builders = new AbstractFormatDependencyDumper[] { new DetailTextFormatDependencyDumper(dependencyMatrix,projectName,outputDir), new XmlFormatDependencyDumper(dependencyMatrix,projectName,outputDir), new JsonFormatDependencyDumper(dependencyMatrix,projectName,outputDir), new ExcelXlsFormatDependencyDumper(dependencyMatrix,projectName,outputDir), new ExcelXlsxFormatDependencyDumper(dependencyMatrix,projectName,outputDir), new DotFormatDependencyDumper(dependencyMatrix,projectName,outputDir), new DotFullnameDependencyDumper(dependencyMatrix,projectName,outputDir), new PlantUmlFormatDependencyDumper(dependencyMatrix,projectName,outputDir), new BriefPlantUmlFormatDependencyDumper(dependencyMatrix,projectName,outputDir) }; for (AbstractFormatDependencyDumper builder:builders) { if (formatList.contains(builder.getFormatName())){ builder.output(); } } } }
3,224
42
93
java
depends
depends-master/src/main/java/depends/format/detail/DetailTextFormatDependencyDumper.java
/* MIT License Copyright (c) 2018-2019 Gang ZHANG Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package depends.format.detail; import depends.format.AbstractFormatDependencyDumper; import depends.matrix.core.DependencyDetail; import depends.matrix.core.DependencyMatrix; import depends.matrix.core.DependencyPair; import depends.matrix.core.DependencyValue; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Collection; public class DetailTextFormatDependencyDumper extends AbstractFormatDependencyDumper{ ArrayList<String> files; @Override public String getFormatName() { return "detail"; } public DetailTextFormatDependencyDumper(DependencyMatrix matrix, String name, String outputDir) { super(matrix,name,outputDir); } @Override public boolean output() { PrintWriter writer; try { files = matrix.getNodes(); writer = new PrintWriter(composeFilename() +".txt"); Collection<DependencyPair> dependencyPairs = matrix.getDependencyPairs(); addRelations(writer,dependencyPairs); writer.close(); return true; } catch (FileNotFoundException e) { e.printStackTrace(); return false; } } private void addRelations(PrintWriter writer, Collection<DependencyPair> dependencyPairs) { for (DependencyPair dependencyPair:dependencyPairs) { int src = dependencyPair.getFrom(); int dst = dependencyPair.getTo(); writer.println("======="+files.get(src) + " -> " + files.get(dst) + "========="); for (DependencyValue dependency:dependencyPair.getDependencies()) { for (DependencyDetail item:dependency.getDetails()) { writer.println("["+dependency.getType()+"]"+item.getSrc() + "->" + item.getDest()); } } } } }
2,802
35.881579
100
java
depends
depends-master/src/main/java/depends/format/detail/UnsolvedSymbolDumper.java
/* MIT License Copyright (c) 2018-2019 Gang ZHANG Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package depends.format.detail; import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.HashSet; import java.util.Set; import java.util.TreeMap; import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import depends.extractor.UnsolvedBindings; import multilang.depends.util.file.strip.LeadingNameStripper; public class UnsolvedSymbolDumper{ private Set<UnsolvedBindings> unsolved; private String name; private String outputDir; private LeadingNameStripper leadingNameStripper; public UnsolvedSymbolDumper(Set<UnsolvedBindings> unsolved, String name, String outputDir, LeadingNameStripper leadingNameStripper) { this.unsolved = unsolved; this.name = name; this.outputDir = outputDir; this.leadingNameStripper = leadingNameStripper; } public void output() { outputDetail(); outputGrouped(); } private void outputGrouped() { TreeMap<String, Set<String>> grouped = new TreeMap<String, Set<String>>(); for (UnsolvedBindings symbol: unsolved) { String depended = symbol.getRawName(); String from = leadingNameStripper.stripFilename(symbol.getSourceDisplay()); Set<String> list = grouped.get(depended); if (list==null) { list = new HashSet<>(); grouped.put(depended, list); } list.add(from); } ObjectMapper om = new ObjectMapper(); om.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false); om.configure(SerializationFeature.INDENT_OUTPUT, true); om.setSerializationInclusion(Include.NON_NULL); try { om.writerWithDefaultPrettyPrinter().writeValue(new File(outputDir + File.separator + name +"-PotentialExternalDependencies.json"), grouped); } catch (Exception e) { e.printStackTrace(); } } private void outputDetail() { PrintWriter writer; try { writer = new PrintWriter(outputDir + File.separator + name +"-PotentialExternalDependencies.txt"); for (UnsolvedBindings symbol: unsolved) { String source = leadingNameStripper.stripFilename(symbol.getSourceDisplay()); writer.println(""+symbol.getRawName()+", "+source); } writer.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } } }
3,367
33.721649
143
java
depends
depends-master/src/main/java/depends/format/xml/XFiles.java
/* MIT License Copyright (c) 2018-2019 Gang ZHANG Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package depends.format.xml; import javax.xml.bind.annotation.XmlElement; import java.util.ArrayList; public class XFiles { private ArrayList<String> files; public ArrayList<String> getFiles() { return files; } @XmlElement(name = "variable") public void setFiles(ArrayList<String> files) { this.files = files; } }
1,437
32.44186
78
java
depends
depends-master/src/main/java/depends/format/xml/XCell.java
/* MIT License Copyright (c) 2018-2019 Gang ZHANG Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package depends.format.xml; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import java.util.ArrayList; public class XCell { private int src; private int dest; private ArrayList<XDepend> depends; @XmlAttribute(name = "src") public void setSrc(int src) { this.src = src; } public int getSrc() { return src; } @XmlAttribute(name = "dest") public void setDest(int dest) { this.dest = dest; } public int getDest() { return dest; } @XmlElement(name = "depend") public void setDepends(ArrayList<XDepend> depends) { this.depends = depends; } public ArrayList<XDepend> getDepends() { return depends; } }
1,847
28.333333
78
java
depends
depends-master/src/main/java/depends/format/xml/XmlFormatDependencyDumper.java
/* MIT License Copyright (c) 2018-2019 Gang ZHANG Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package depends.format.xml; import java.io.FileOutputStream; import javax.xml.bind.JAXBContext; import javax.xml.bind.Marshaller; import depends.format.AbstractFormatDependencyDumper; import depends.format.FileAttributes; import depends.matrix.core.DependencyMatrix; public class XmlFormatDependencyDumper extends AbstractFormatDependencyDumper{ @Override public String getFormatName() { return "xml"; } public XmlFormatDependencyDumper(DependencyMatrix dependencyMatrix, String projectName, String outputDir) { super(dependencyMatrix,projectName,outputDir); } private void toXml(XDepObject xDepObject, String xmlFileName) { try { JAXBContext jaxbContext = JAXBContext.newInstance(XDepObject.class); Marshaller marshaller = jaxbContext.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); marshaller.marshal(xDepObject, new FileOutputStream(xmlFileName)); } catch (Exception e) { e.printStackTrace(); } } @Override public boolean output() { XDataBuilder xBuilder = new XDataBuilder(); XDepObject xDepObject = xBuilder.build(matrix,new FileAttributes(name)); toXml(xDepObject,composeFilename()+".xml"); return true; } }
2,367
36
111
java
depends
depends-master/src/main/java/depends/format/xml/XCells.java
/* MIT License Copyright (c) 2018-2019 Gang ZHANG Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package depends.format.xml; import javax.xml.bind.annotation.XmlElement; import java.util.ArrayList; public class XCells { private ArrayList<XCell> cells; @XmlElement(name = "cell") public void setCells(ArrayList<XCell> cells) { this.cells = cells; } public ArrayList<XCell> getCells() { return cells; } }
1,429
33.047619
78
java
depends
depends-master/src/main/java/depends/format/xml/XDepend.java
/* MIT License Copyright (c) 2018-2019 Gang ZHANG Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package depends.format.xml; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement(name = "depend") public class XDepend { private String name; private float weight; public String getName() { return name; } @XmlAttribute(name = "name") public void setName(String name) { this.name = name; } public float getWeight() { return weight; } @XmlAttribute(name = "weight") public void setWeight(float weight) { this.weight = weight; } }
1,654
29.090909
78
java
depends
depends-master/src/main/java/depends/format/xml/XDataBuilder.java
/* MIT License Copyright (c) 2018-2019 Gang ZHANG Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package depends.format.xml; import java.util.ArrayList; import java.util.Collection; import depends.format.FileAttributes; import depends.matrix.core.DependencyMatrix; import depends.matrix.core.DependencyPair; import depends.matrix.core.DependencyValue; public class XDataBuilder { public XDepObject build(DependencyMatrix matrix,FileAttributes attribute) { ArrayList<String> files = matrix.getNodes(); Collection<DependencyPair> dependencyPairs = matrix.getDependencyPairs(); XFiles xFiles = new XFiles(); xFiles.setFiles(files); ArrayList<XCell> xCellList = buildCellList(dependencyPairs); XCells xCells = new XCells(); xCells.setCells(xCellList); XDepObject xDepObject = new XDepObject(); xDepObject.setName(attribute.getAttributeName()); xDepObject.setSchemaVersion(attribute.getSchemaVersion()); xDepObject.setVariables(xFiles); xDepObject.setCells(xCells); return xDepObject; } private ArrayList<XCell> buildCellList(Collection<DependencyPair> dependencyPairs) { ArrayList<XCell> cellList = new ArrayList<XCell>(); for (DependencyPair pair : dependencyPairs) { ArrayList<XDepend> xDepends = buildDependList(pair.getDependencies()); XCell xCell = new XCell(); xCell.setSrc(pair.getFrom()); xCell.setDest(pair.getTo()); xCell.setDepends(xDepends); cellList.add(xCell); } return cellList; } private ArrayList<XDepend> buildDependList(Collection<DependencyValue> dependencies) { ArrayList<XDepend> dependList = new ArrayList<XDepend>(); for (DependencyValue dependency : dependencies) { XDepend xDepend = new XDepend(); xDepend.setWeight(dependency.getWeight()); xDepend.setName(dependency.getType()); dependList.add(xDepend); } return dependList; } }
3,066
35.951807
88
java
depends
depends-master/src/main/java/depends/format/xml/XDepObject.java
/* MIT License Copyright (c) 2018-2019 Gang ZHANG Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package depends.format.xml; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; @XmlRootElement(name = "matrix") @XmlType(propOrder = {"variables", "cells"}) public class XDepObject { private String schemaVersion; private String name; private XFiles variables; private XCells cells; private String xmlns="http://dv8.archdia.com/xml/matrix"; public String getName() { return name; } @XmlAttribute(name = "name") public void setName(String name) { this.name = name; } public String getSchemaVersion() { return schemaVersion; } @XmlAttribute(name = "schema-version") public void setSchemaVersion(String schemaVersion) { this.schemaVersion = schemaVersion; } @XmlElement(name = "variables") public void setVariables(XFiles variables) { this.variables = variables; } public XFiles getVariables() { return variables; } @XmlElement(name = "cells") public void setCells(XCells cells) { this.cells = cells; } public XCells getCells() { return cells; } public String getXmlns() { return xmlns; } @XmlAttribute(name = "xmlns") public void setXmlns(String xmlns) { this.xmlns = xmlns; } }
2,487
26.644444
78
java
depends
depends-master/src/main/java/depends/format/excel/ExcelXlsFormatDependencyDumper.java
/* MIT License Copyright (c) 2018-2019 Gang ZHANG Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package depends.format.excel; import java.io.File; import java.io.IOException; import java.util.Collection; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import depends.format.AbstractFormatDependencyDumper; import depends.matrix.core.DependencyMatrix; import depends.matrix.core.DependencyPair; import depends.matrix.core.DependencyValue; public class ExcelXlsFormatDependencyDumper extends AbstractFormatDependencyDumper { private HSSFWorkbook workbook; private HSSFSheet sheet; @Override public String getFormatName() { return "xls"; } public ExcelXlsFormatDependencyDumper(DependencyMatrix dependencyMatrix, String projectName, String outputDir) { super(dependencyMatrix, projectName,outputDir); } @Override public boolean output() { String filename = composeFilename() + ".xls"; if (matrix.getNodes().size() > 255) { System.out.println("We can only export small matrix(<256 items) to excel" + "due to MS Office limitation"); return false; } startFile(); Collection<DependencyPair> dependencyPairs = matrix.getDependencyPairs(); HSSFRow[] row = new HSSFRow[matrix.getNodes().size()]; // create header row HSSFRow header = sheet.createRow(0); for (int i = 0; i < matrix.getNodes().size(); i++) { HSSFCell cell = header.createCell(i + 2); cell.setCellValue(i); } ; // create header col for (int i = 0; i < matrix.getNodes().size(); i++) { row[i] = sheet.createRow(i + 1); String node = matrix.getNodes().get(i); HSSFCell cell = row[i].createCell(0); cell.setCellValue(i); cell = row[i].createCell(1); cell.setCellValue(node); } ; // create header col for (int i = 0; i < matrix.getNodes().size(); i++) { HSSFCell cell = row[i].createCell(i + 2); cell.setCellValue("(" + i + ")"); } ; for (DependencyPair dependencyPair : dependencyPairs) { HSSFCell cell = row[dependencyPair.getFrom()].createCell(dependencyPair.getTo() + 2); cell.setCellValue(buildDependencyValues(dependencyPair.getDependencies())); } closeFile(filename); return true; } private String buildDependencyValues(Collection<DependencyValue> dependencies) { StringBuilder sb = new StringBuilder(); for (DependencyValue dependency : dependencies) { String comma = sb.length() > 0 ? "," : ""; sb.append(comma).append(dependency.getType()).append("(").append(dependency.getWeight()).append(")"); } return sb.toString(); } private void closeFile(String filename) { try { workbook.write(new File(filename)); workbook.close(); } catch (IOException e) { e.printStackTrace(); } } private void startFile() { workbook = new HSSFWorkbook(); sheet = workbook.createSheet("DSM"); } }
3,915
31.363636
113
java
depends
depends-master/src/main/java/depends/format/excel/ExcelXlsxFormatDependencyDumper.java
/* MIT License Copyright (c) 2018-2019 Gang ZHANG Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package depends.format.excel; import java.io.FileOutputStream; import java.io.IOException; import java.util.Collection; import org.apache.poi.xssf.usermodel.XSSFCell; import org.apache.poi.xssf.usermodel.XSSFRow; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import depends.format.AbstractFormatDependencyDumper; import depends.matrix.core.DependencyMatrix; import depends.matrix.core.DependencyPair; import depends.matrix.core.DependencyValue; public class ExcelXlsxFormatDependencyDumper extends AbstractFormatDependencyDumper { private XSSFWorkbook workbook; private XSSFSheet sheet; @Override public String getFormatName() { return "xlsx"; } public ExcelXlsxFormatDependencyDumper(DependencyMatrix dependencyMatrix, String projectName, String outputDir) { super(dependencyMatrix, projectName,outputDir); } @Override public boolean output() { String filename = composeFilename() + ".xlsx"; startFile(); Collection<DependencyPair> dependencyPairs = matrix.getDependencyPairs(); XSSFRow[] row = new XSSFRow[matrix.getNodes().size()]; // create header row XSSFRow header = sheet.createRow(0); for (int i = 0; i < matrix.getNodes().size(); i++) { XSSFCell cell = header.createCell(i + 2); cell.setCellValue(i); } ; // create header col for (int i = 0; i < matrix.getNodes().size(); i++) { row[i] = sheet.createRow(i + 1); String node = matrix.getNodes().get(i); XSSFCell cell = row[i].createCell(0); cell.setCellValue(i); cell = row[i].createCell(1); cell.setCellValue(node); } ; // create header col for (int i = 0; i < matrix.getNodes().size(); i++) { XSSFCell cell = row[i].createCell(i + 2); cell.setCellValue("(" + i + ")"); } ; for (DependencyPair dependencyPair : dependencyPairs) { XSSFCell cell = row[dependencyPair.getFrom()].createCell(dependencyPair.getTo() + 2); cell.setCellValue(buildDependencyValues(dependencyPair.getDependencies())); } closeFile(filename); return true; } private String buildDependencyValues(Collection<DependencyValue> dependencies) { StringBuilder sb = new StringBuilder(); for (DependencyValue dependency : dependencies) { String comma = sb.length() > 0 ? "," : ""; sb.append(comma).append(dependency.getType()).append("(").append(dependency.getWeight()).append(")"); } return sb.toString(); } private void closeFile(String filename) { try { FileOutputStream out = new FileOutputStream(filename); workbook.write(out); workbook.close(); out.close(); } catch (IOException e) { e.printStackTrace(); } } private void startFile() { workbook = new XSSFWorkbook(); sheet = workbook.createSheet("DSM"); } }
3,843
31.033333
114
java
depends
depends-master/src/main/java/depends/format/plantuml/BriefPlantUmlFormatDependencyDumper.java
package depends.format.plantuml; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import depends.format.AbstractFormatDependencyDumper; import depends.matrix.core.DependencyMatrix; import depends.matrix.core.DependencyPair; import depends.matrix.core.DependencyValue; public class BriefPlantUmlFormatDependencyDumper extends AbstractFormatDependencyDumper { @Override public String getFormatName() { return "briefplantuml"; } public BriefPlantUmlFormatDependencyDumper(DependencyMatrix dependencyMatrix, String projectName, String outputDir) { super(dependencyMatrix,projectName,outputDir); } @Override public boolean output() { PrintWriter writer; try { writer = new PrintWriter(composeFilename()+".uml"); ArrayList<String> files = matrix.getNodes(); for (int i=0;i<files.size();i++) { String file = files.get(i); writer.println("class " + " "+file); } writer.println("@startuml"); Collection<DependencyPair> dependencyPairs = matrix.getDependencyPairs(); addRelations(writer,dependencyPairs); writer.println("@enduml"); writer.close(); return true; } catch (FileNotFoundException e) { e.printStackTrace(); return false; } } private void addRelations(PrintWriter writer, Collection<DependencyPair> dependencyPairs) { HashMap <String,HashMap<String,Integer>> relationMap = new HashMap<>(); for (DependencyPair dependencyPair:dependencyPairs) { int src = dependencyPair.getFrom(); int dst = dependencyPair.getTo(); for (DependencyValue dep:dependencyPair.getDependencies()) { String key = getNodeName(src)+"..>" + getNodeName(dst); if (!relationMap.containsKey(key)){ relationMap.put(key, new HashMap<>()); } HashMap<String, Integer> relationValues = relationMap.get(key); Integer value = 0; if (!relationValues.containsKey(dep.getType())) { relationValues.get(dep.getType()); } relationValues.put(dep.getType(), value+=dep.getWeight()); } } for (String key:relationMap.keySet()) { writer.println("\t"+key + " : " + buildNotes(relationMap.get(key)) ); } } private String buildNotes(HashMap<String, Integer> relations) { StringBuffer sb = new StringBuffer(); for (String dep:relations.keySet()) { sb.append(dep.substring(0,3).toUpperCase()).append(relations.get(dep)); } return sb.toString(); } private String getNodeName(int src) { String result = matrix.getNodeName(src); result = result.replace("-", "_"); return result; } }
2,763
30.05618
118
java
depends
depends-master/src/main/java/depends/format/plantuml/PlantUmlFormatDependencyDumper.java
package depends.format.plantuml; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.Set; import depends.deptypes.DependencyType; import depends.format.AbstractFormatDependencyDumper; import depends.matrix.core.DependencyMatrix; import depends.matrix.core.DependencyPair; import depends.matrix.core.DependencyValue; public class PlantUmlFormatDependencyDumper extends AbstractFormatDependencyDumper { @Override public String getFormatName() { return "plantuml"; } public PlantUmlFormatDependencyDumper(DependencyMatrix dependencyMatrix, String projectName, String outputDir) { super(dependencyMatrix,projectName,outputDir); } @Override public boolean output() { PrintWriter writer; try { writer = new PrintWriter(composeFilename()+".uml"); ArrayList<String> files = matrix.getNodes(); for (int i=0;i<files.size();i++) { String file = files.get(i); writer.println("class " + " "+file); } writer.println("@startuml"); Collection<DependencyPair> dependencyPairs = matrix.getDependencyPairs(); addRelations(writer,dependencyPairs); writer.println("@enduml"); writer.close(); return true; } catch (FileNotFoundException e) { e.printStackTrace(); return false; } } private void addRelations(PrintWriter writer, Collection<DependencyPair> dependencyPairs) { for (DependencyPair dependencyPair:dependencyPairs) { int src = dependencyPair.getFrom(); int dst = dependencyPair.getTo(); Set<String> relations = new HashSet<>(); for (DependencyValue dep:dependencyPair.getDependencies()) { relations.add("\t"+ getNodeName(src) + " " + getRelationSymbol(dep.getType()) +" " + getNodeName(dst) + ""); } for (String relation:relations) { writer.println(relation); } } } private String getRelationSymbol(String type) { if (type.equals(DependencyType.IMPLEMENT)) { return "..|>"; }else if (type.equals(DependencyType.INHERIT)) { return "--|>"; }else if (type.equals(DependencyType.CONTAIN)) { return "*-->"; }else if (type.equals(DependencyType.MIXIN)) { return "o-->"; } return "..>"; } private String getNodeName(int src) { String result = matrix.getNodeName(src); result = result.replace("-", "_"); return result; } }
2,460
28.650602
121
java
depends
depends-master/src/main/java/depends/format/dot/DotFormatDependencyDumper.java
/* MIT License Copyright (c) 2018-2019 Gang ZHANG Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package depends.format.dot; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Collection; import depends.format.AbstractFormatDependencyDumper; import depends.matrix.core.DependencyMatrix; import depends.matrix.core.DependencyPair; public class DotFormatDependencyDumper extends AbstractFormatDependencyDumper{ @Override public String getFormatName() { return "dot"; } public DotFormatDependencyDumper(DependencyMatrix dependencyMatrix, String projectName, String outputDir) { super(dependencyMatrix,projectName,outputDir); } @Override public boolean output() { PrintWriter writer; try { writer = new PrintWriter(composeFilename()+".dot"); ArrayList<String> files = matrix.getNodes(); for (int i=0;i<files.size();i++) { String file = files.get(i); writer.println("// "+i + ":"+file); } writer.println("digraph"); writer.println("{"); Collection<DependencyPair> dependencyPairs = matrix.getDependencyPairs(); addRelations(writer,dependencyPairs); writer.println("}"); writer.close(); return true; } catch (FileNotFoundException e) { e.printStackTrace(); return false; } } private void addRelations(PrintWriter writer, Collection<DependencyPair> dependencyPairs) { for (DependencyPair dependencyPair:dependencyPairs) { int src = dependencyPair.getFrom(); int dst = dependencyPair.getTo(); writer.println("\t"+src + " -> " + dst + ";"); } } }
2,617
33
108
java
depends
depends-master/src/main/java/depends/format/dot/DotFullnameDependencyDumper.java
/* MIT License Copyright (c) 2018-2019 Gang ZHANG Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package depends.format.dot; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Collection; import depends.format.AbstractFormatDependencyDumper; import depends.matrix.core.DependencyMatrix; import depends.matrix.core.DependencyPair; public class DotFullnameDependencyDumper extends AbstractFormatDependencyDumper{ ArrayList<String> files = null; @Override public String getFormatName() { return "dotx"; } public DotFullnameDependencyDumper(DependencyMatrix dependencyMatrix, String projectName, String outputDir) { super(dependencyMatrix,projectName,outputDir); } @Override public boolean output() { PrintWriter writer; try { writer = new PrintWriter(composeFilename()+".dot"); files = matrix.getNodes(); writer.println("digraph"); writer.println("{"); Collection<DependencyPair> dependencyPairs = matrix.getDependencyPairs(); addRelations(writer,dependencyPairs); writer.println("}"); writer.close(); return true; } catch (FileNotFoundException e) { e.printStackTrace(); return false; } } private void addRelations(PrintWriter writer, Collection<DependencyPair> dependencyPairs) { for (DependencyPair dependencyPair:dependencyPairs) { int src = dependencyPair.getFrom(); int dst = dependencyPair.getTo(); writer.println("\t\""+files.get(src) + "\" -> \"" + files.get(dst) + "\";"); } } }
2,553
33.513514
110
java
depends
depends-master/src/main/java/depends/format/json/JDataBuilder.java
/* MIT License Copyright (c) 2018-2019 Gang ZHANG Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package depends.format.json; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import depends.format.FileAttributes; import depends.matrix.core.DependencyDetail; import depends.matrix.core.DependencyMatrix; import depends.matrix.core.DependencyPair; import depends.matrix.core.DependencyValue; public class JDataBuilder { public JDepObject build(DependencyMatrix dependencyMatrix, FileAttributes attribute) { ArrayList<String> files = dependencyMatrix.getNodes(); Collection<DependencyPair> dependencyPairs = dependencyMatrix.getDependencyPairs(); ArrayList<JCellObject> cellObjects = buildCellObjects(dependencyPairs); // transform finalRes into cellObjects JDepObject depObject = new JDepObject(); depObject.setVariables(files); depObject.setName(attribute.getAttributeName()); depObject.setSchemaVersion(attribute.getSchemaVersion()); depObject.setCells(cellObjects); return depObject; } private ArrayList<JCellObject> buildCellObjects(Collection<DependencyPair> dependencyPairs) { ArrayList<JCellObject> cellObjects = new ArrayList<JCellObject>(); for (DependencyPair dependencyPair : dependencyPairs) { Map<String, Float> valueObject = buildValueObject(dependencyPair.getDependencies()); List<DetailItem> details = buildDetails(dependencyPair.getDependencies()); JCellObject cellObject = new JCellObject(); cellObject.setSrc(dependencyPair.getFrom()); cellObject.setDest(dependencyPair.getTo()); cellObject.setValues(valueObject); cellObject.setDetails(details); cellObjects.add(cellObject); } return cellObjects; } private List<DetailItem> buildDetails(Collection<DependencyValue> dependencies) { List<DetailItem> r = new ArrayList<>(); for (DependencyValue dependency : dependencies) { for (DependencyDetail detail:dependency.getDetails()) { r.add(new DetailItem(detail.getSrc(),detail.getDest(),dependency.getType())); } } if (r.size()==0) return null; return r; } private Map<String, Float> buildValueObject(Collection<DependencyValue> dependencies) { Map<String, Float> valueObject = new HashMap<String, Float>(); for (DependencyValue dependency : dependencies) { valueObject.put(dependency.getType(), (float) dependency.getWeight()); } return valueObject; } }
3,427
37.516854
112
java
depends
depends-master/src/main/java/depends/format/json/JsonFormatDependencyDumper.java
/* MIT License Copyright (c) 2018-2019 Gang ZHANG Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package depends.format.json; import java.io.File; import com.fasterxml.jackson.databind.ObjectMapper; import depends.format.AbstractFormatDependencyDumper; import depends.format.FileAttributes; import depends.matrix.core.DependencyMatrix; public class JsonFormatDependencyDumper extends AbstractFormatDependencyDumper { @Override public String getFormatName() { return "json"; } public JsonFormatDependencyDumper(DependencyMatrix dependencyMatrix, String projectName, String outputDir) { super(dependencyMatrix, projectName,outputDir); } @Override public boolean output() { JDataBuilder jBuilder = new JDataBuilder(); JDepObject jDepObject = jBuilder.build(matrix, new FileAttributes(name)); toJson(jDepObject, composeFilename()+ ".json"); return true; } private void toJson(JDepObject depObject, String jsonFileName) { ObjectMapper mapper = new ObjectMapper(); try { mapper.writerWithDefaultPrettyPrinter().writeValue(new File(jsonFileName), depObject); } catch (Exception e) { e.printStackTrace(); } } }
2,133
31.333333
109
java
depends
depends-master/src/main/java/depends/format/json/JDepObject.java
/* MIT License Copyright (c) 2018-2019 Gang ZHANG Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package depends.format.json; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import java.util.ArrayList; @XmlRootElement(name = "matrix") public class JDepObject { private String schemaVersion; private String name; private ArrayList<String> variables; private ArrayList<JCellObject> cells; public String getName() { return name; } @XmlAttribute(name = "name") public void setName(String name) { this.name = name; } public String getSchemaVersion() { return schemaVersion; } @XmlAttribute(name = "schema-version") public void setSchemaVersion(String schemaVersion) { this.schemaVersion = schemaVersion; } public ArrayList<String> getVariables() { return variables; } @XmlElement public void setVariables(ArrayList<String> variables) { this.variables = variables; } public ArrayList<JCellObject> getCells() { return cells; } @XmlElement public void setCells(ArrayList<JCellObject> cells) { this.cells = cells; } }
2,254
29.066667
78
java
depends
depends-master/src/main/java/depends/format/json/JCellObject.java
/* MIT License Copyright (c) 2018-2019 Gang ZHANG Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package depends.format.json; import java.util.List; import java.util.Map; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude.Include; public class JCellObject { private int src; private int dest; private Map<String, Float> values; @JsonInclude(Include.NON_NULL) private List<DetailItem> details; public int getSrc() { return src; } public void setSrc(int src) { this.src = src; } public int getDest() { return dest; } public void setDest(int dest) { this.dest = dest; } public void setValues(Map<String, Float> values) { this.values = values; } public Map<String, Float> getValues() { return values; } public List<DetailItem> getDetails() { return details; } public void setDetails(List<DetailItem> details) { this.details = details; } }
2,007
26.506849
78
java
depends
depends-master/src/main/java/depends/format/json/DetailItem.java
package depends.format.json; import depends.matrix.core.LocationInfo; public class DetailItem { private LocationInfo src; private LocationInfo dest; private String type; public DetailItem(LocationInfo src, LocationInfo dest, String type) { this.src = src; this.dest = dest; this.type = type; } public LocationInfo getSrc() { return src; } public LocationInfo getDest() { return dest; } public String getType() { return type; } }
460
14.366667
70
java
AHaH
AHaH-master/ahah-clusterer/src/test/java/com/knowmtech/ahah/clusterer/TestConverter.java
/** * Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]> * * M. Alexander Nugent Consulting Research License Agreement * Non-Commercial Academic Use Only * * This Software is proprietary. By installing, copying, or otherwise using this * Software, you agree to be bound by the terms of this license. If you do not agree, * do not install, copy, or use the Software. The Software is protected by copyright * and other intellectual property laws. * * You may use the Software for non-commercial academic purpose, subject to the following * restrictions. You may copy and use the Software for peer-review and methods verification * only. You may not create derivative works of the Software. You may not use or distribute * the Software or any derivative works in any form for commercial or non-commercial purposes. * * Violators will be prosecuted to the full extent of the law. * * All rights reserved. No warranty, explicit or implicit, provided. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.knowmtech.ahah.clusterer; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import org.junit.Test; import com.mancrd.ahah.clusterer.Converter; /** * @author timmolter */ public class TestConverter { @Test public void testGetSignature() { Converter converter = new Converter(); double[] nodeActivations = new double[] { 1, 1, 1, 1 }; int signature = converter.getSignature(nodeActivations); System.out.println("signature: " + signature); assertThat(signature, is(15)); nodeActivations = new double[] { 0, 0, 0, 0, 0 }; signature = converter.getSignature(nodeActivations); System.out.println("signature: " + signature); assertThat(signature, is(0)); nodeActivations = new double[] { 0, -.99, -.08, .44, .88 }; signature = converter.getSignature(nodeActivations); System.out.println("signature: " + signature); assertThat(signature, is(3)); } // @Test // public void testGetAhahNodeActivations() { // // Converter converter = new Converter(); // double[] ahahActivations = converter.getAhahNodeActivations(15, 4); // System.out.println("ahahActivations: " + Arrays.toString(ahahActivations)); // assertTrue(Arrays.equals(ahahActivations, new double[] { 1, 1, 1, 1 })); // // ahahActivations = converter.getAhahNodeActivations(0, 5); // System.out.println("ahahActivations: " + Arrays.toString(ahahActivations)); // assertTrue(Arrays.equals(ahahActivations, new double[] { -1.0, -1.0, -1.0, -1.0, -1.0 })); // // ahahActivations = converter.getAhahNodeActivations(3, 5); // System.out.println("ahahActivations: " + Arrays.toString(ahahActivations)); // assertTrue(Arrays.equals(ahahActivations, new double[] { -1.0, -1.0, -1.0, 1.0, 1.0 })); // } }
3,279
39.493827
95
java
AHaH
AHaH-master/ahah-clusterer/src/test/java/com/knowmtech/ahah/clusterer/BitManipulationTest.java
/** * Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]> * * M. Alexander Nugent Consulting Research License Agreement * Non-Commercial Academic Use Only * * This Software is proprietary. By installing, copying, or otherwise using this * Software, you agree to be bound by the terms of this license. If you do not agree, * do not install, copy, or use the Software. The Software is protected by copyright * and other intellectual property laws. * * You may use the Software for non-commercial academic purpose, subject to the following * restrictions. You may copy and use the Software for peer-review and methods verification * only. You may not create derivative works of the Software. You may not use or distribute * the Software or any derivative works in any form for commercial or non-commercial purposes. * * Violators will be prosecuted to the full extent of the law. * * All rights reserved. No warranty, explicit or implicit, provided. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.knowmtech.ahah.clusterer; import org.junit.Ignore; /** * @author alexnugent */ @Ignore public class BitManipulationTest { public static void main(String[] args) { int spike = 13348349; short id = 5667; long longSpike = spike; System.out.println("spike: " + Long.toString(longSpike, 2)); System.out.println("id: " + Long.toString(id, 2)); long shift = longSpike << 16; long composite = shift | id; System.out.println("shift: " + Long.toString(shift, 2)); System.out.println("composite: " + Long.toString(composite, 2)); long idMask = 65535;// 0b1111111111111111; long idReconstructed = composite & idMask; long spikeReconstructed = composite >> 16; System.out.println("reconstructedSpike: " + Long.toString(spikeReconstructed, 2)); System.out.println("reconstructedSpike: " + spikeReconstructed); System.out.println("idReconstructed: " + Long.toString(idReconstructed, 2)); System.out.println("idReconstructed: " + idReconstructed); } }
2,504
35.838235
94
java
AHaH
AHaH-master/ahah-clusterer/src/test/java/com/knowmtech/ahah/clusterer/TestLRUCache.java
/** * Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]> * * M. Alexander Nugent Consulting Research License Agreement * Non-Commercial Academic Use Only * * This Software is proprietary. By installing, copying, or otherwise using this * Software, you agree to be bound by the terms of this license. If you do not agree, * do not install, copy, or use the Software. The Software is protected by copyright * and other intellectual property laws. * * You may use the Software for non-commercial academic purpose, subject to the following * restrictions. You may copy and use the Software for peer-review and methods verification * only. You may not create derivative works of the Software. You may not use or distribute * the Software or any derivative works in any form for commercial or non-commercial purposes. * * Violators will be prosecuted to the full extent of the law. * * All rights reserved. No warranty, explicit or implicit, provided. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.knowmtech.ahah.clusterer; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.util.Iterator; import org.junit.Test; import com.mancrd.ahah.commons.LRUCache; /** * Test class for LRUCache * * @author timmolter */ public class TestLRUCache { private String[] getSampleKeys() { return new String[] { "A", "B", "C", "D", "E" }; } /** * tests basic functionality */ @Test public void testBasicFunction() { String[] keys = getSampleKeys(); assertThat(keys.length, is(equalTo(5))); Iterator<String> keyItr = null; Iterator<Integer> labelItr = null; // empty map LRUCache lruCache = new LRUCache(2); assertThat(lruCache.size(), is(equalTo(0))); assertFalse(lruCache.isFull()); assertFalse(lruCache.isReassign()); assertThat(lruCache.maxSize(), is(equalTo(2))); System.out.println("initial: " + lruCache.getAll().toString()); // map with one value Integer label = lruCache.put(keys[0]); System.out.println(keys[0] + " added: " + lruCache.getAll().toString()); assertThat(label, is(equalTo(new Integer(0)))); assertThat(lruCache.size(), is(equalTo(new Integer(1)))); assertFalse(lruCache.isFull()); assertFalse(lruCache.isReassign()); assertThat(lruCache.maxSize(), is(equalTo(new Integer(2)))); // map with two values, full label = lruCache.put(keys[1]); System.out.println(keys[1] + " added: " + lruCache.getAll().toString()); assertThat(label, is(equalTo(new Integer(1)))); assertThat(lruCache.size(), is(equalTo(new Integer(2)))); assertTrue(lruCache.isFull()); assertFalse(lruCache.isReassign()); assertThat(lruCache.maxSize(), is(equalTo(new Integer(2)))); keyItr = lruCache.getMap().keySet().iterator(); assertThat(keyItr.next(), is(equalTo(keys[0]))); assertThat(keyItr.next(), is(equalTo(keys[1]))); labelItr = lruCache.getMap().values().iterator(); assertThat(labelItr.next(), is(equalTo(new Integer(0)))); assertThat(labelItr.next(), is(equalTo(new Integer(1)))); // map with new key, overflow occurs label = lruCache.put(keys[2]); System.out.println(keys[2] + " added: " + lruCache.getAll().toString()); assertThat(label, is(equalTo(new Integer(0)))); assertThat(lruCache.size(), is(equalTo(new Integer(2)))); assertTrue(lruCache.isFull()); assertTrue(lruCache.isReassign()); assertThat(lruCache.maxSize(), is(equalTo(new Integer(2)))); keyItr = lruCache.getMap().keySet().iterator(); assertThat(keyItr.next(), is(equalTo(keys[1]))); assertThat(keyItr.next(), is(equalTo(keys[2]))); labelItr = lruCache.getMap().values().iterator(); assertThat(labelItr.next(), is(equalTo(new Integer(1)))); assertThat(labelItr.next(), is(equalTo(new Integer(0)))); // map with same key, overflow occurs label = lruCache.put(keys[1]); System.out.println(keys[1] + " added: " + lruCache.getAll().toString()); assertThat(label, is(equalTo(new Integer(1)))); assertThat(lruCache.size(), is(equalTo(new Integer(2)))); assertTrue(lruCache.isFull()); assertTrue(lruCache.isReassign()); assertThat(lruCache.maxSize(), is(equalTo(new Integer(2)))); keyItr = lruCache.getMap().keySet().iterator(); assertThat(keyItr.next(), is(equalTo(keys[2]))); assertThat(keyItr.next(), is(equalTo(keys[1]))); labelItr = lruCache.getMap().values().iterator(); assertThat(labelItr.next(), is(equalTo(new Integer(0)))); assertThat(labelItr.next(), is(equalTo(new Integer(1)))); // map with new key, overflow occurs label = lruCache.put(keys[3]); System.out.println(keys[3] + " added: " + lruCache.getAll().toString()); assertThat(label, is(equalTo(new Integer(0)))); assertThat(lruCache.size(), is(equalTo(new Integer(2)))); assertTrue(lruCache.isFull()); assertThat(lruCache.maxSize(), is(equalTo(new Integer(2)))); keyItr = lruCache.getMap().keySet().iterator(); assertThat(keyItr.next(), is(equalTo(keys[1]))); assertThat(keyItr.next(), is(equalTo(keys[3]))); labelItr = lruCache.getMap().values().iterator(); assertThat(labelItr.next(), is(equalTo(new Integer(1)))); assertThat(labelItr.next(), is(equalTo(new Integer(0)))); } @Test public void testReset() { String[] keys = getSampleKeys(); // empty map LRUCache lruCache = new LRUCache(2); assertThat(lruCache.size(), is(equalTo(0))); assertFalse(lruCache.isFull()); assertThat(lruCache.maxSize(), is(equalTo(2))); // add one value lruCache.put(keys[0]); assertThat(lruCache.size(), is(equalTo(1))); assertFalse(lruCache.isFull()); // add another value lruCache.put(keys[1]); assertThat(lruCache.size(), is(equalTo(2))); assertTrue(lruCache.isFull()); // add one value, overflowing lruCache.put(keys[2]); assertThat(lruCache.size(), is(equalTo(2))); assertTrue(lruCache.isFull()); lruCache.reset(); assertThat(lruCache.size(), is(equalTo(0))); assertFalse(lruCache.isFull()); assertThat(lruCache.maxSize(), is(equalTo(2))); } @Test public void testReverseLookup() { String[] keys = getSampleKeys(); // empty map LRUCache lruCache = new LRUCache(2); assertThat(lruCache.size(), is(equalTo(0))); assertFalse(lruCache.isFull()); assertThat(lruCache.maxSize(), is(equalTo(2))); // add one value Integer label = lruCache.put(keys[0]); assertThat(label, is(equalTo(new Integer(0)))); assertThat(lruCache.reverseLookup(label), is(equalTo(keys[0]))); // add another value, cache full label = lruCache.put(keys[1]); assertThat(label, is(equalTo(new Integer(1)))); assertThat(lruCache.reverseLookup(label), is(equalTo(keys[1]))); // add another value, cache overflow label = lruCache.put(keys[2]); assertThat(label, is(equalTo(new Integer(0)))); assertThat(lruCache.reverseLookup(label), is(equalTo(keys[2]))); } }
7,635
34.516279
94
java
AHaH
AHaH-master/ahah-clusterer/src/main/java/com/mancrd/ahah/clusterer/IClusterer.java
/** * Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]> * * M. Alexander Nugent Consulting Research License Agreement * Non-Commercial Academic Use Only * * This Software is proprietary. By installing, copying, or otherwise using this * Software, you agree to be bound by the terms of this license. If you do not agree, * do not install, copy, or use the Software. The Software is protected by copyright * and other intellectual property laws. * * You may use the Software for non-commercial academic purpose, subject to the following * restrictions. You may copy and use the Software for peer-review and methods verification * only. You may not create derivative works of the Software. You may not use or distribute * the Software or any derivative works in any form for commercial or non-commercial purposes. * * Violators will be prosecuted to the full extent of the law. * * All rights reserved. No warranty, explicit or implicit, provided. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.mancrd.ahah.clusterer; import java.util.Set; /** * @author timmolter */ public interface IClusterer { public static final int NUM_AHAH_NODES = 20; public Integer put(Set<String> spikes); }
1,685
38.209302
94
java
AHaH
AHaH-master/ahah-clusterer/src/main/java/com/mancrd/ahah/clusterer/Converter.java
/** * Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]> * * M. Alexander Nugent Consulting Research License Agreement * Non-Commercial Academic Use Only * * This Software is proprietary. By installing, copying, or otherwise using this * Software, you agree to be bound by the terms of this license. If you do not agree, * do not install, copy, or use the Software. The Software is protected by copyright * and other intellectual property laws. * * You may use the Software for non-commercial academic purpose, subject to the following * restrictions. You may copy and use the Software for peer-review and methods verification * only. You may not create derivative works of the Software. You may not use or distribute * the Software or any derivative works in any form for commercial or non-commercial purposes. * * Violators will be prosecuted to the full extent of the law. * * All rights reserved. No warranty, explicit or implicit, provided. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.mancrd.ahah.clusterer; /** * @author timmolter */ public class Converter { /** * converts the core's node activations to a base-10 int * * @param nodeActivations * @return */ public static int getSignature(double[] nodeActivations) { // 1. create a binary number StringBuilder buf = new StringBuilder(); for (int i = 0; i < nodeActivations.length; i++) { if (nodeActivations[i] > 0) { buf.append("1"); } else { buf.append("0"); } } // 2. convert binary to base-10 int int base10 = (int) Long.parseLong(buf.toString(), 2); return base10; } }
2,124
33.274194
94
java
AHaH
AHaH-master/ahah-clusterer/src/main/java/com/mancrd/ahah/clusterer/syndata/NoiseInjector.java
/** * Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]> * * M. Alexander Nugent Consulting Research License Agreement * Non-Commercial Academic Use Only * * This Software is proprietary. By installing, copying, or otherwise using this * Software, you agree to be bound by the terms of this license. If you do not agree, * do not install, copy, or use the Software. The Software is protected by copyright * and other intellectual property laws. * * You may use the Software for non-commercial academic purpose, subject to the following * restrictions. You may copy and use the Software for peer-review and methods verification * only. You may not create derivative works of the Software. You may not use or distribute * the Software or any derivative works in any form for commercial or non-commercial purposes. * * Violators will be prosecuted to the full extent of the law. * * All rights reserved. No warranty, explicit or implicit, provided. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.mancrd.ahah.clusterer.syndata; import java.util.Iterator; import java.util.Random; import java.util.Set; /** * @author timmolter */ public class NoiseInjector { /** A Random object used for creating random numbers */ private Random random = new Random(); public enum Noise { ADDITIVE, SUBTRACTIVE, ADD_SUBTRACT, FLIP; } /** * @param spikePatterns * @param numInputs * @param noise * @param numNoiseBitsPerFeature */ public void injectNoise(Set<String> spikePatterns, Integer numInputs, Noise noise, int numNoiseBitsPerFeature) { switch (noise) { case ADDITIVE: additiveNoise(spikePatterns, numInputs, numNoiseBitsPerFeature); break; case SUBTRACTIVE: subtractiveNoise(spikePatterns, numNoiseBitsPerFeature); break; case ADD_SUBTRACT: subtractiveNoise(spikePatterns, numNoiseBitsPerFeature); additiveNoise(spikePatterns, numInputs, numNoiseBitsPerFeature); break; case FLIP: flipNoise(spikePatterns, numInputs, numNoiseBitsPerFeature); break; default: break; } } /** * randomly adds inputs to a feature * * @param spikePatterns * @param numInputs * @param numNoiseBitsPerFeature */ private void additiveNoise(Set<String> spikePatterns, int numInputs, int numNoiseBitsPerFeature) { for (int i = 0; i < numNoiseBitsPerFeature; i++) { boolean added = false; do { added = spikePatterns.add(new Integer(random.nextInt(numInputs)).toString()); } while (!added && spikePatterns.size() < numInputs); } } /** * randomly subtracts inputs to a feature * * @param spikePatterns * @param numNoiseBitsPerFeature */ private void subtractiveNoise(Set<String> spikePatterns, int numNoiseBitsPerFeature) { for (int i = 0; i < numNoiseBitsPerFeature; i++) { if (spikePatterns.size() <= 0) { throw new IllegalArgumentException("Too much subtractive noise added to feature, size()=0!"); } int index = this.random.nextInt(spikePatterns.size()); Iterator<String> itr = spikePatterns.iterator(); itr.next(); while (index > 0) { itr.next(); index--; } itr.remove(); } } /** * randomly flips bits of a spikePattern * * @param spikePatterns * @param numInputs * @param numNoiseBitsPerFeature */ private void flipNoise(Set<String> spikePatterns, int numInputs, int numNoiseBitsPerFeature) { for (int i = 0; i < numNoiseBitsPerFeature; i++) { String sensorId = new Integer(random.nextInt(numInputs)).toString(); if (spikePatterns.contains(sensorId)) { spikePatterns.remove(sensorId); } else {// add it spikePatterns.add(sensorId); } } } }
4,271
30.411765
114
java
AHaH
AHaH-master/ahah-clusterer/src/main/java/com/mancrd/ahah/clusterer/syndata/RandomSpikeGeneratorDefaultValues.java
/** * Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]> * * M. Alexander Nugent Consulting Research License Agreement * Non-Commercial Academic Use Only * * This Software is proprietary. By installing, copying, or otherwise using this * Software, you agree to be bound by the terms of this license. If you do not agree, * do not install, copy, or use the Software. The Software is protected by copyright * and other intellectual property laws. * * You may use the Software for non-commercial academic purpose, subject to the following * restrictions. You may copy and use the Software for peer-review and methods verification * only. You may not create derivative works of the Software. You may not use or distribute * the Software or any derivative works in any form for commercial or non-commercial purposes. * * Violators will be prosecuted to the full extent of the law. * * All rights reserved. No warranty, explicit or implicit, provided. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.mancrd.ahah.clusterer.syndata; import com.mancrd.ahah.clusterer.syndata.NoiseInjector.Noise; /** * Defaults for AHaH RandomSpikeGenerator */ public class RandomSpikeGeneratorDefaultValues { public static final int NUM_NOISE_BITS = 3; public static final Noise NOISE = Noise.FLIP; public static final int SPIKE_PATTERN_LENGTH = 16; public static final int NUM_SPIKE_PATTERNS = 16; public static final int MAX_INPUT_SPIKES = 256; }
1,931
41.933333
94
java
AHaH
AHaH-master/ahah-clusterer/src/main/java/com/mancrd/ahah/clusterer/syndata/RandomSpikePatternGenerator.java
/** * Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]> * * M. Alexander Nugent Consulting Research License Agreement * Non-Commercial Academic Use Only * * This Software is proprietary. By installing, copying, or otherwise using this * Software, you agree to be bound by the terms of this license. If you do not agree, * do not install, copy, or use the Software. The Software is protected by copyright * and other intellectual property laws. * * You may use the Software for non-commercial academic purpose, subject to the following * restrictions. You may copy and use the Software for peer-review and methods verification * only. You may not create derivative works of the Software. You may not use or distribute * the Software or any derivative works in any form for commercial or non-commercial purposes. * * Violators will be prosecuted to the full extent of the law. * * All rights reserved. No warranty, explicit or implicit, provided. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.mancrd.ahah.clusterer.syndata; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Random; import java.util.Set; import com.mancrd.ahah.clusterer.syndata.NoiseInjector.Noise; /** * @author alexnugent */ public class RandomSpikePatternGenerator { /** the number of spikePatterns to create */ private final int numSpikePatterns; /** the total number of spikes over all patterns */ private final int maxInputSpikes; /** the length of the input spike pattern. Note that for each actual trial, a smaller or larger number inputs may fire due to noise */ private final int spikePatternLength; /** the number of bits to randomly flip in each spikes */ private final int numNoiseBits; /** Noise type */ private final Noise noise; /** A 2D Matrix of Integers */ private final List<Set<String>> spikePatterns; /** A Random object used for creating random numbers */ private final Random random = new Random(); /** A NoiseInjector for injecting noise into a feature */ private final NoiseInjector noiseInjector = new NoiseInjector(); /** * Constructor * * @param builder */ private RandomSpikePatternGenerator(Builder builder) { this.numSpikePatterns = builder.numSpikePatterns; this.maxInputSpikes = builder.maxInputSpikes; if (builder.spikePatternLength > builder.maxInputSpikes) { throw new IllegalArgumentException("spikesLength cannot be greater than maxInputSpikes !"); } this.spikePatternLength = builder.spikePatternLength; this.numNoiseBits = builder.numNoiseBits; this.noise = builder.noise; this.spikePatterns = generateSpikePatterns(); } /** * create a set of random spikes * * @return */ private List<Set<String>> generateSpikePatterns() { List<Set<String>> spikePatternList = new ArrayList<Set<String>>(); for (int i = 0; i < numSpikePatterns; i++) { spikePatternList.add(generateRandomSpikePattern()); } return spikePatternList; } /** * create a random pattern defined by the co-activation of input lines. Each input line has an ID. A pattern is a collection of sensors that are * active for a pattern. * * @return */ private Set<String> generateRandomSpikePattern() { Set<String> spikes = new HashSet<String>(); do { spikes.add(new Integer(random.nextInt(this.maxInputSpikes)).toString()); } while (spikes.size() < this.spikePatternLength); return spikes; } /** * @return */ public List<Set<String>> getSpikePatterns() { return spikePatterns; } /** * @return a random spikes index between 0 and spikes.size() - 1 */ public int getRandomSpikeId() { return this.random.nextInt(spikePatterns.size()); } /** * @param spikeId * @return a spikePattern given in spikeId */ public Set<String> getSpikePattern(int spikeId) { return spikePatterns.get(spikeId); } public Set<String> getRandomClonedSpikePatternWithNoise() { return getClonedSpikePatternWithNoise(getRandomSpikeId()); } /** * @param spikeId * @return cloned spikes patterns with noise added to it */ public Set<String> getClonedSpikePatternWithNoise(int spikeId) { Set<String> noisySpikes = spikePatterns.get(spikeId); Set<String> clonedSpikes = new HashSet<String>(); for (String integer : noisySpikes) { clonedSpikes.add(new String(integer)); } noiseInjector.injectNoise(clonedSpikes, this.maxInputSpikes, this.noise, this.numNoiseBits); return clonedSpikes; } @Override public String toString() { StringBuilder sb = new StringBuilder(); for (int i = 0; i < spikePatterns.size(); i++) { sb.append(i + ": " + spikePatterns.get(i).toString() + "\n"); } return sb.toString(); } // BUILDER ///////////////////////////////////////////////////////// public static class Builder { private Noise noise = RandomSpikeGeneratorDefaultValues.NOISE; private int numNoiseBits = RandomSpikeGeneratorDefaultValues.NUM_NOISE_BITS; private int maxInputSpikes = RandomSpikeGeneratorDefaultValues.MAX_INPUT_SPIKES; private int spikePatternLength = RandomSpikeGeneratorDefaultValues.SPIKE_PATTERN_LENGTH; private int numSpikePatterns = RandomSpikeGeneratorDefaultValues.NUM_SPIKE_PATTERNS; public Builder numSpikePatterns(int numSpikePatterns) { this.numSpikePatterns = numSpikePatterns; return this; } public Builder maxInputSpikes(int maxInputSpikes) { this.maxInputSpikes = maxInputSpikes; return this; } public Builder spikePatternLength(int spikePatternLength) { this.spikePatternLength = spikePatternLength; return this; } public Builder numNoiseBits(int numNoiseBits) { this.numNoiseBits = numNoiseBits; return this; } public Builder noise(Noise noise) { this.noise = noise; return this; } /** * return fully built object * * @return a RandomFeatureGenerator */ public RandomSpikePatternGenerator build() { return new RandomSpikePatternGenerator(this); } } }
6,656
28.197368
146
java
AHaH
AHaH-master/ahah-clusterer/src/main/java/com/mancrd/ahah/clusterer/circuit/Clusterer.java
/** * Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]> * * M. Alexander Nugent Consulting Research License Agreement * Non-Commercial Academic Use Only * * This Software is proprietary. By installing, copying, or otherwise using this * Software, you agree to be bound by the terms of this license. If you do not agree, * do not install, copy, or use the Software. The Software is protected by copyright * and other intellectual property laws. * * You may use the Software for non-commercial academic purpose, subject to the following * restrictions. You may copy and use the Software for peer-review and methods verification * only. You may not create derivative works of the Software. You may not use or distribute * the Software or any derivative works in any form for commercial or non-commercial purposes. * * Violators will be prosecuted to the full extent of the law. * * All rights reserved. No warranty, explicit or implicit, provided. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.mancrd.ahah.clusterer.circuit; import java.util.HashSet; import java.util.Set; import com.mancrd.ahah.clusterer.Converter; import com.mancrd.ahah.clusterer.IClusterer; import com.mancrd.ahah.model.circuit.AHaH21Circuit; import com.mancrd.ahah.model.circuit.AHaH21CircuitBuilder; public class Clusterer implements IClusterer { private final AHaH21Circuit[] ahahNodes; /** * Constructor * * @param builder */ public Clusterer(ClustererBuilder builder) { ahahNodes = new AHaH21Circuit[builder.getNumAHaHNodes()]; for (int i = 0; i < ahahNodes.length; i++) { ahahNodes[i] = new AHaH21CircuitBuilder().numInputs(builder.getMaxInputSpikes()).numBiasInputs(builder.getNumBias()).readPeriod(builder.getReadPeriod()).writePeriod(builder.getWritePeriod()).Vss( builder.getVss()).Vdd(builder.getVdd()).build(); } } /** * spikes come in here * * @param inputSpikes * @return */ @Override public Integer put(Set<String> inputSpikes) { Set<Integer> inputSpikesIntegers = convertStringSpikes(inputSpikes); double[] nodeActivations = new double[ahahNodes.length]; for (int i = 0; i < ahahNodes.length; i++) { nodeActivations[i] = ahahNodes[i].update(inputSpikesIntegers, 0); } return Converter.getSignature(nodeActivations); } /** * convert String-valued spike to integer-valued spikes * * @param spikes * @return */ private static Set<Integer> convertStringSpikes(Set<String> spikes) { Set<Integer> integerSpikes = new HashSet<Integer>(); for (String s : spikes) { integerSpikes.add(Integer.parseInt(s)); } return integerSpikes; } }
3,172
33.48913
190
java
AHaH
AHaH-master/ahah-clusterer/src/main/java/com/mancrd/ahah/clusterer/circuit/ClustererDefaultValues.java
/** * Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]> * * M. Alexander Nugent Consulting Research License Agreement * Non-Commercial Academic Use Only * * This Software is proprietary. By installing, copying, or otherwise using this * Software, you agree to be bound by the terms of this license. If you do not agree, * do not install, copy, or use the Software. The Software is protected by copyright * and other intellectual property laws. * * You may use the Software for non-commercial academic purpose, subject to the following * restrictions. You may copy and use the Software for peer-review and methods verification * only. You may not create derivative works of the Software. You may not use or distribute * the Software or any derivative works in any form for commercial or non-commercial purposes. * * Violators will be prosecuted to the full extent of the law. * * All rights reserved. No warranty, explicit or implicit, provided. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.mancrd.ahah.clusterer.circuit; /** * Defaults for AHaH clusterer */ public class ClustererDefaultValues { public static final int NUM_BIAS = 8; // 1/2 of the number of the spike pattern length (16) public static final double VDD = .5; public static final double VSS = -.5; public static final double READ_PERIOD = 1E-6; public static final double WRITE_PERIOD = 1E-6; }
1,870
42.511628
94
java
AHaH
AHaH-master/ahah-clusterer/src/main/java/com/mancrd/ahah/clusterer/circuit/ClustererBuilder.java
/** * Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]> * * M. Alexander Nugent Consulting Research License Agreement * Non-Commercial Academic Use Only * * This Software is proprietary. By installing, copying, or otherwise using this * Software, you agree to be bound by the terms of this license. If you do not agree, * do not install, copy, or use the Software. The Software is protected by copyright * and other intellectual property laws. * * You may use the Software for non-commercial academic purpose, subject to the following * restrictions. You may copy and use the Software for peer-review and methods verification * only. You may not create derivative works of the Software. You may not use or distribute * the Software or any derivative works in any form for commercial or non-commercial purposes. * * Violators will be prosecuted to the full extent of the law. * * All rights reserved. No warranty, explicit or implicit, provided. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.mancrd.ahah.clusterer.circuit; import com.mancrd.ahah.clusterer.IClusterer; import com.mancrd.ahah.clusterer.syndata.RandomSpikeGeneratorDefaultValues; /** * Builder for IdealCircuitClusterer */ public class ClustererBuilder { private int numAHaHNodes = IClusterer.NUM_AHAH_NODES; private int maxInputSpikes = RandomSpikeGeneratorDefaultValues.MAX_INPUT_SPIKES; private int numBias = ClustererDefaultValues.NUM_BIAS; private double Vss = ClustererDefaultValues.VSS; private double Vdd = ClustererDefaultValues.VDD; private double readPeriod = ClustererDefaultValues.READ_PERIOD; private double writePeriod = ClustererDefaultValues.WRITE_PERIOD; public Clusterer build() { return new Clusterer(this); } public ClustererBuilder ahahNodes(int numAhahNodes) { this.numAHaHNodes = numAhahNodes; return this; } public ClustererBuilder numInputs(int numInputs) { this.maxInputSpikes = numInputs; return this; } public ClustererBuilder numBias(int numBias) { this.numBias = numBias; return this; } public ClustererBuilder Vss(int Vss) { this.Vss = Vss; return this; } public ClustererBuilder Vdd(int Vdd) { this.Vdd = Vdd; return this; } public ClustererBuilder readPeriod(int readPeriod) { this.readPeriod = readPeriod; return this; } public ClustererBuilder writePeriod(int writePeriod) { this.writePeriod = writePeriod; return this; } public int getNumAHaHNodes() { return numAHaHNodes; } public int getMaxInputSpikes() { return maxInputSpikes; } public int getNumBias() { return numBias; } public double getVss() { return Vss; } public double getVdd() { return Vdd; } public double getReadPeriod() { return readPeriod; } public double getWritePeriod() { return writePeriod; } }
3,357
24.830769
94
java
AHaH
AHaH-master/ahah-clusterer/src/main/java/com/mancrd/ahah/clusterer/eval/LabelCount.java
/** * Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]> * * M. Alexander Nugent Consulting Research License Agreement * Non-Commercial Academic Use Only * * This Software is proprietary. By installing, copying, or otherwise using this * Software, you agree to be bound by the terms of this license. If you do not agree, * do not install, copy, or use the Software. The Software is protected by copyright * and other intellectual property laws. * * You may use the Software for non-commercial academic purpose, subject to the following * restrictions. You may copy and use the Software for peer-review and methods verification * only. You may not create derivative works of the Software. You may not use or distribute * the Software or any derivative works in any form for commercial or non-commercial purposes. * * Violators will be prosecuted to the full extent of the law. * * All rights reserved. No warranty, explicit or implicit, provided. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.mancrd.ahah.clusterer.eval; /** * @author alexnugent */ public class LabelCount implements Comparable<LabelCount> { private int label; private int count; /** * Constructor * * @param label * @param count */ public LabelCount(int label, int count) { this.label = label; this.count = count; } @Override public int compareTo(LabelCount o) { if (o.getCount() > this.getCount()) { return 1; } else if (o.getCount() < this.getCount()) { return -1; } return 0; } public int getLabel() { return label; } public int getCount() { return count; } @Override public String toString() { return "[" + label + ", " + count + "]"; } }
2,217
26.382716
94
java
AHaH
AHaH-master/ahah-clusterer/src/main/java/com/mancrd/ahah/clusterer/eval/LabelHistory.java
/** * Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]> * * M. Alexander Nugent Consulting Research License Agreement * Non-Commercial Academic Use Only * * This Software is proprietary. By installing, copying, or otherwise using this * Software, you agree to be bound by the terms of this license. If you do not agree, * do not install, copy, or use the Software. The Software is protected by copyright * and other intellectual property laws. * * You may use the Software for non-commercial academic purpose, subject to the following * restrictions. You may copy and use the Software for peer-review and methods verification * only. You may not create derivative works of the Software. You may not use or distribute * the Software or any derivative works in any form for commercial or non-commercial purposes. * * Violators will be prosecuted to the full extent of the law. * * All rights reserved. No warranty, explicit or implicit, provided. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.mancrd.ahah.clusterer.eval; import java.util.HashMap; import java.util.Iterator; import java.util.Map; /** * keeps track of data related to the Clusterer's spikes corresponding to a label * * @author alexnugent */ public class LabelHistory { private int label; /** number of times this label has been generated */ private int count = 0; /** number of time this feature has been associated with this label */ private Map<Integer, Integer> spikes2CountMap = new HashMap<Integer, Integer>(); /** * Constructor * * @param labelId */ public LabelHistory(int labelId) { this.label = labelId; } public void correspondingFeature(int featureId) { this.count++; Integer count = spikes2CountMap.get(featureId); if (count == null) { count = 1; } else { count++; } spikes2CountMap.put(featureId, count); } public int getCount() { return this.count; } public int getNumCorrespondingFeatures() { return this.spikes2CountMap.size(); } @Override public String toString() { StringBuilder buf = new StringBuilder(); buf.append(label + "(" + this.count + "):"); Iterator<Integer> itr = spikes2CountMap.keySet().iterator(); while (itr.hasNext()) { Integer featureId = itr.next(); Integer featureCount = spikes2CountMap.get(featureId); buf.append(featureId + "(" + featureCount + "),"); } buf.replace(buf.length() - 1, buf.length() - 1, "");// remove the last comma return buf.toString(); } }
3,024
28.950495
94
java
AHaH
AHaH-master/ahah-clusterer/src/main/java/com/mancrd/ahah/clusterer/eval/SpikesHistory.java
/** * Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]> * * M. Alexander Nugent Consulting Research License Agreement * Non-Commercial Academic Use Only * * This Software is proprietary. By installing, copying, or otherwise using this * Software, you agree to be bound by the terms of this license. If you do not agree, * do not install, copy, or use the Software. The Software is protected by copyright * and other intellectual property laws. * * You may use the Software for non-commercial academic purpose, subject to the following * restrictions. You may copy and use the Software for peer-review and methods verification * only. You may not create derivative works of the Software. You may not use or distribute * the Software or any derivative works in any form for commercial or non-commercial purposes. * * Violators will be prosecuted to the full extent of the law. * * All rights reserved. No warranty, explicit or implicit, provided. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.mancrd.ahah.clusterer.eval; import java.util.HashMap; import java.util.Iterator; import java.util.Map; /** * Keeps track of data related to the Clusterer's labels generated as a response to spikes * * @author alexnugent */ public class SpikesHistory { private int spikesId; /** number of times this feature has been inputted */ private int count = 0; /** number of time these spikes have been associated with the labels */ private Map<Integer, Integer> label2CountMap = new HashMap<Integer, Integer>(); /** * Constructor * * @param spikesId */ public SpikesHistory(int spikesId) { this.spikesId = spikesId; } /** * Here a label corresponding to the spikes coming in to be recorded. * * @param labelId */ public void correspondingLabel(int labelId) { // 1. increment feature count this.count++; // 2. increment label count Integer count = label2CountMap.get(labelId); if (count == null) { count = 1; } else { count++; } label2CountMap.put(labelId, count); } public int getCount() { return this.count; } public int getNumCorrespondingLabels() { return this.label2CountMap.size(); } @Override public String toString() { StringBuilder buf = new StringBuilder(); buf.append(spikesId + "(" + this.count + "):"); Iterator<Integer> itr = label2CountMap.keySet().iterator(); while (itr.hasNext()) { Integer labelId = itr.next(); Integer labelCount = label2CountMap.get(labelId); buf.append(labelId + "(" + labelCount + "),"); } buf.replace(buf.length() - 1, buf.length() - 1, "");// remove the last comma return buf.toString(); } }
3,199
28.62963
94
java
AHaH
AHaH-master/ahah-clusterer/src/main/java/com/mancrd/ahah/clusterer/eval/VergenceEvaluator.java
/** * Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]> * * M. Alexander Nugent Consulting Research License Agreement * Non-Commercial Academic Use Only * * This Software is proprietary. By installing, copying, or otherwise using this * Software, you agree to be bound by the terms of this license. If you do not agree, * do not install, copy, or use the Software. The Software is protected by copyright * and other intellectual property laws. * * You may use the Software for non-commercial academic purpose, subject to the following * restrictions. You may copy and use the Software for peer-review and methods verification * only. You may not create derivative works of the Software. You may not use or distribute * the Software or any derivative works in any form for commercial or non-commercial purposes. * * Violators will be prosecuted to the full extent of the law. * * All rights reserved. No warranty, explicit or implicit, provided. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.mancrd.ahah.clusterer.eval; import java.util.HashMap; import java.util.Iterator; import java.util.Map; /** * This class keeps track of a Clusterer's feature --> label mappings for analysis. * * @author alexnugent */ public class VergenceEvaluator { /** A Map mapping features to its history */ private Map<Integer, SpikesHistory> spikes2SpikesHistoryMap = new HashMap<Integer, SpikesHistory>(); /** A Map mapping labels to its history */ private Map<Integer, LabelHistory> label2LabelHistoryMap = new HashMap<Integer, LabelHistory>(); /** * Entry points for recording labels the Clusterer produces corresponding to the spikeId * * @param spikeId - The feature Id. Given a feature list of size M, the id is between 0 and M-1 * @param label - the generated label produced by the Clusterer */ public void update(int spikeId, int label) { SpikesHistory spikesHistory = spikes2SpikesHistoryMap.get(spikeId); if (spikesHistory == null) { spikesHistory = new SpikesHistory(spikeId); } spikesHistory.correspondingLabel(label); spikes2SpikesHistoryMap.put(spikeId, spikesHistory); LabelHistory labelHistory = label2LabelHistoryMap.get(label); if (labelHistory == null) { labelHistory = new LabelHistory(label); } labelHistory.correspondingFeature(spikeId); label2LabelHistoryMap.put(label, labelHistory); } /** * @return - the vergence of the Clusterer */ public double getVergence() { return (getConvergence() + getDivergence()) / 2; } /** * @return - the convergence of the Clusterer */ public double getConvergence() { Iterator<Integer> itr = label2LabelHistoryMap.keySet().iterator(); double m = 0; while (itr.hasNext()) { Integer labelId = itr.next(); m += label2LabelHistoryMap.get(labelId).getNumCorrespondingFeatures(); } m /= label2LabelHistoryMap.size(); return 1 / m; } /** * @return - the divergence of the Clusterer */ public double getDivergence() { Iterator<Integer> itr = spikes2SpikesHistoryMap.keySet().iterator(); double m = 0; while (itr.hasNext()) { Integer featureId = itr.next(); m += spikes2SpikesHistoryMap.get(featureId).getNumCorrespondingLabels(); } m /= spikes2SpikesHistoryMap.size(); return 1 / m; } /** * prints the vergence of this Evaluation object */ public String toVergenceString() { StringBuilder sb = new StringBuilder(); sb.append("Convergence(ave. Spikes per Label) = " + getConvergence() + "\n"); sb.append("Divergence(ave. Labels per Spikes) = " + getDivergence() + "\n"); sb.append("Vergence = " + getVergence() + "\n"); return sb.toString(); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("*****SPIKES COUNTS*****" + "\n"); sb.append("Spike ID(count): LabelId0(count),LabelId1(count),..." + "\n"); Iterator<Integer> itr = spikes2SpikesHistoryMap.keySet().iterator(); while (itr.hasNext()) { Integer featureId = itr.next(); SpikesHistory featureHistory = spikes2SpikesHistoryMap.get(featureId); sb.append(featureHistory.toString() + "\n"); } sb.append("*****LABEL COUNTS*****" + "\n"); sb.append("Label ID(count): SpikeId0(count),SpikeId1(count),..." + "\n"); itr = label2LabelHistoryMap.keySet().iterator(); while (itr.hasNext()) { Integer labelId = itr.next(); LabelHistory labelHistory = label2LabelHistoryMap.get(labelId); sb.append(labelHistory.toString() + "\n"); } return sb.toString(); } public String toCompactString() { StringBuilder sb = new StringBuilder(); sb.append(getVergence() + " : "); sb.append(getConvergence() + " : "); sb.append(getDivergence()); return sb.toString(); } }
5,351
33.089172
102
java
AHaH
AHaH-master/ahah-clusterer/src/main/java/com/mancrd/ahah/clusterer/eval/LabelStatistics.java
/** * Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]> * * M. Alexander Nugent Consulting Research License Agreement * Non-Commercial Academic Use Only * * This Software is proprietary. By installing, copying, or otherwise using this * Software, you agree to be bound by the terms of this license. If you do not agree, * do not install, copy, or use the Software. The Software is protected by copyright * and other intellectual property laws. * * You may use the Software for non-commercial academic purpose, subject to the following * restrictions. You may copy and use the Software for peer-review and methods verification * only. You may not create derivative works of the Software. You may not use or distribute * the Software or any derivative works in any form for commercial or non-commercial purposes. * * Violators will be prosecuted to the full extent of the law. * * All rights reserved. No warranty, explicit or implicit, provided. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.mancrd.ahah.clusterer.eval; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; /** * @author alexnugent */ public class LabelStatistics { private final Map<Integer, Integer> counts = new HashMap<Integer, Integer>(); public int put(Integer labelID) { Integer count = counts.get(labelID); if (count == null) { count = 1; } else { count++; } counts.put(labelID, count); return count; } public int get(Integer labelID) { Integer count = counts.get(labelID); if (count == null) { return 0; } else { return count; } } public List<LabelCount> getCounts() { List<LabelCount> countArray = new ArrayList<LabelCount>(); for (Map.Entry<Integer, Integer> entry : counts.entrySet()) { LabelCount labelCount = new LabelCount(entry.getKey(), entry.getValue()); countArray.add(labelCount); } Collections.sort(countArray); return countArray; } public void printCounts() { Iterator<Integer> itt = counts.keySet().iterator(); while (itt.hasNext()) { int key = itt.next(); System.out.println(key + "-->" + counts.get(key)); } } }
2,762
28.709677
94
java
AHaH
AHaH-master/ahah-clusterer/src/main/java/com/mancrd/ahah/clusterer/functional/Clusterer.java
/** * Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]> * * M. Alexander Nugent Consulting Research License Agreement * Non-Commercial Academic Use Only * * This Software is proprietary. By installing, copying, or otherwise using this * Software, you agree to be bound by the terms of this license. If you do not agree, * do not install, copy, or use the Software. The Software is protected by copyright * and other intellectual property laws. * * You may use the Software for non-commercial academic purpose, subject to the following * restrictions. You may copy and use the Software for peer-review and methods verification * only. You may not create derivative works of the Software. You may not use or distribute * the Software or any derivative works in any form for commercial or non-commercial purposes. * * Violators will be prosecuted to the full extent of the law. * * All rights reserved. No warranty, explicit or implicit, provided. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.mancrd.ahah.clusterer.functional; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Random; import java.util.Set; import com.mancrd.ahah.clusterer.Converter; import com.mancrd.ahah.clusterer.IClusterer; import com.mancrd.ahah.commons.LRUCache; /** * @author alexnugent */ public final class Clusterer implements IClusterer { private final Converter converter = new Converter(); /************** Core Parameters **************/ /** number of input lines */ private final int numInputs; /** number of nodes */ private final int numAhahNodes; /** available energy. "learning rate" */ private final double learningRate; /** used to inititalize the weights */ private final double initWeightMag; /************** Internal State **************/ /** weight matrix */ private final double[][] ahahNodeWeightMatrix; /** AHAH node bias weights */ private final double[] ahahNodeBiasWeights; private final LRUCache lineIDLRUCache; /** * Constructor * * @param builder */ public Clusterer(ClustererBuilder builder) { this.numInputs = builder.getmaxInputSpike(); this.numAhahNodes = builder.getNumAhahNodes(); this.learningRate = builder.getLearningRate(); this.initWeightMag = builder.getInitWeightMag(); ahahNodeWeightMatrix = new double[numAhahNodes][numInputs]; ahahNodeBiasWeights = new double[numAhahNodes]; initWeightsRandom(); lineIDLRUCache = new LRUCache(builder.getmaxInputSpike()); } /** * initialize the weights to random values, scaled by the structure constant */ private void initWeightsRandom() { Random random = new Random(); for (int i = 0; i < ahahNodeWeightMatrix.length; i++) { for (int j = 0; j < ahahNodeWeightMatrix[0].length; j++) { ahahNodeWeightMatrix[i][j] = random.nextGaussian() * initWeightMag; } } } /** * Spikes come in here. A label is returned. * * @param spikes * @return Integer - A label */ @Override public Integer put(Set<String> spikes) { if (spikes.size() > this.numInputs) { throw new IllegalArgumentException("feature length cannot be greater than the number of inputs into the core!"); } // 1. compute activations double[] ahahNodeActivations = new double[this.numAhahNodes]; // this is the basis for the base-10 Integer signature, nodeActivation = y for (String lineId : spikes) { for (int j = 0; j < this.numAhahNodes; j++) { ahahNodeActivations[j] += ahahNodeWeightMatrix[j][lineIDLRUCache.put(lineId)]; } } // 2. bias activations. Bias inputs are all active (+1) so its equivalent to just adding bias weight for (int j = 0; j < this.numAhahNodes; j++) { ahahNodeActivations[j] += ahahNodeBiasWeights[j]; } // 3. get output AHAH output address. This performs pooling operation Integer signature = converter.getSignature(ahahNodeActivations); // 4. Update ahah nodes ahah(spikes, ahahNodeActivations); return signature; } /** * @param spikes * @param nodeActivations */ private void ahah(Set<String> spikes, double[] nodeActivations) { // 1. update nodeWeightMatrix for (String lineId : spikes) { for (int j = 0; j < nodeActivations.length; j++) { ahahNodeWeightMatrix[j][lineIDLRUCache.put(lineId)] += fy(nodeActivations[j]); } } // 2. update nodeBiasWeights to prevent the null state, most stable states are the ones that most stable split the state for (int j = 0; j < nodeActivations.length; j++) { ahahNodeBiasWeights[j] -= learningRate * nodeActivations[j]; // anti-hebbian learning } } /** * AHaH unsupervised update * * @param sumOfWeights (y) * @return */ private double fy(double y) { return learningRate * (Math.signum(y) - y); } /** * get a feature, given a signature * * @param signature - the signature * @param featureLength - the length of the features * @return - spikes corresponding to a given signature */ Set<String> reverseLookup(Integer signature) { // 1. determine node activations array, ex. 1,-1,-1,1,1,1 double[] nodeActivations = getNodeActivations(signature); // 2. gets something double[] inputLines = new double[ahahNodeWeightMatrix[0].length]; for (int i = 0; i < nodeActivations.length; i++) { for (int j = 0; j < inputLines.length; j++) { inputLines[j] += (nodeActivations[i] + ahahNodeBiasWeights[i]) * ahahNodeWeightMatrix[i][j]; } } // 3. create sorted input line activations List<InputLineActivation> inputLineActivations = new ArrayList<InputLineActivation>(); for (int i = 0; i < inputLines.length; i++) { inputLineActivations.add(new InputLineActivation(i, inputLines[i])); } Collections.sort(inputLineActivations); // double sum = 0; int cutoffIdx = 0; for (int i = 0; i < inputLineActivations.size(); i++) { if (inputLineActivations.get(i).getActivation() <= 0) { cutoffIdx = i; break; } } // 4. crop inputLineActivations List<InputLineActivation> croppedInputLineActivations = inputLineActivations.subList(0, cutoffIdx); // 5. create feature Set<String> spikes = new HashSet<String>(); for (InputLineActivation inputLineActivation : croppedInputLineActivations) { spikes.add(inputLineActivation.getInputId().toString()); } return spikes; } /** * Given a signature (base-10 int), get nodeActivations * * @param signature * @return */ double[] getNodeActivations(int signature) { // 1. convert base-10 int to binary String bitPattern = Integer.toBinaryString(signature); // 2. fill in missing zeros in front while (bitPattern.length() < numAhahNodes) { bitPattern = "0" + bitPattern; } // 3. determine node activations array, ex. 1,-1,-1,1,1,1 double[] nodeActivations = new double[numAhahNodes]; for (int i = 0; i < nodeActivations.length; i++) { if (bitPattern.charAt(i) == '1') { nodeActivations[i] = 1; } else { nodeActivations[i] = -1; } } return nodeActivations; } /** * Creates a String showing all the weights in matrix form * * @return - A String showing all the weights in matrix form */ String weightMatrixToString() { DecimalFormat df = new DecimalFormat("#0.000000"); StringBuilder sb = new StringBuilder(); for (int i = 0; i < ahahNodeWeightMatrix.length; i++) { for (int j = 0; j < ahahNodeWeightMatrix[i].length; j++) { sb.append((ahahNodeWeightMatrix[i][j] > 0.0 ? " " : "") + df.format(ahahNodeWeightMatrix[i][j]) + " : "); } sb.append("\n"); } return sb.toString(); } }
8,390
29.183453
140
java
AHaH
AHaH-master/ahah-clusterer/src/main/java/com/mancrd/ahah/clusterer/functional/ClustererDefaultValues.java
/** * Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]> * * M. Alexander Nugent Consulting Research License Agreement * Non-Commercial Academic Use Only * * This Software is proprietary. By installing, copying, or otherwise using this * Software, you agree to be bound by the terms of this license. If you do not agree, * do not install, copy, or use the Software. The Software is protected by copyright * and other intellectual property laws. * * You may use the Software for non-commercial academic purpose, subject to the following * restrictions. You may copy and use the Software for peer-review and methods verification * only. You may not create derivative works of the Software. You may not use or distribute * the Software or any derivative works in any form for commercial or non-commercial purposes. * * Violators will be prosecuted to the full extent of the law. * * All rights reserved. No warranty, explicit or implicit, provided. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.mancrd.ahah.clusterer.functional; /** * Defaults for AHaH clusterer */ public class ClustererDefaultValues { public static final double LEARNING_RATE = .0005; // i.e. alpha & beta public static final double INIT_WEIGHT_MAG = .01; public static final boolean PLASTICITY_ON = true; }
1,778
42.390244
94
java
AHaH
AHaH-master/ahah-clusterer/src/main/java/com/mancrd/ahah/clusterer/functional/ClustererBuilder.java
/** * Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]> * * M. Alexander Nugent Consulting Research License Agreement * Non-Commercial Academic Use Only * * This Software is proprietary. By installing, copying, or otherwise using this * Software, you agree to be bound by the terms of this license. If you do not agree, * do not install, copy, or use the Software. The Software is protected by copyright * and other intellectual property laws. * * You may use the Software for non-commercial academic purpose, subject to the following * restrictions. You may copy and use the Software for peer-review and methods verification * only. You may not create derivative works of the Software. You may not use or distribute * the Software or any derivative works in any form for commercial or non-commercial purposes. * * Violators will be prosecuted to the full extent of the law. * * All rights reserved. No warranty, explicit or implicit, provided. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.mancrd.ahah.clusterer.functional; import com.mancrd.ahah.clusterer.IClusterer; import com.mancrd.ahah.clusterer.syndata.RandomSpikeGeneratorDefaultValues; public class ClustererBuilder { private int maxInputSpikes = RandomSpikeGeneratorDefaultValues.MAX_INPUT_SPIKES; private int numAhahNodes = IClusterer.NUM_AHAH_NODES; private double learningRate = com.mancrd.ahah.clusterer.functional.ClustererDefaultValues.LEARNING_RATE; private double initWeightMag = com.mancrd.ahah.clusterer.functional.ClustererDefaultValues.INIT_WEIGHT_MAG; public ClustererBuilder numInputs(int numInputs) { this.maxInputSpikes = numInputs; return this; } public ClustererBuilder ahahNodes(int numAhahNodes) { this.numAhahNodes = numAhahNodes; return this; } public ClustererBuilder learningRate(double learningRate) { this.learningRate = learningRate; return this; } public ClustererBuilder maxInitWeight(double initWeightMag) { this.initWeightMag = initWeightMag; return this; } /** * return fully built object * * @return a Clusterer */ public Clusterer build() { return new Clusterer(this); } public int getmaxInputSpike() { return maxInputSpikes; } public int getNumAhahNodes() { return numAhahNodes; } public double getLearningRate() { return learningRate; } public double getInitWeightMag() { return initWeightMag; } }
2,922
29.447917
109
java
AHaH
AHaH-master/ahah-clusterer/src/main/java/com/mancrd/ahah/clusterer/functional/InputLineActivation.java
/** * Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]> * * M. Alexander Nugent Consulting Research License Agreement * Non-Commercial Academic Use Only * * This Software is proprietary. By installing, copying, or otherwise using this * Software, you agree to be bound by the terms of this license. If you do not agree, * do not install, copy, or use the Software. The Software is protected by copyright * and other intellectual property laws. * * You may use the Software for non-commercial academic purpose, subject to the following * restrictions. You may copy and use the Software for peer-review and methods verification * only. You may not create derivative works of the Software. You may not use or distribute * the Software or any derivative works in any form for commercial or non-commercial purposes. * * Violators will be prosecuted to the full extent of the law. * * All rights reserved. No warranty, explicit or implicit, provided. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.mancrd.ahah.clusterer.functional; /** * @author alexnugent */ final class InputLineActivation implements Comparable<InputLineActivation> { private final int inputId; private final double activation; /** * Constructor * * @param sensorId * @param activation */ InputLineActivation(int sensorId, double activation) { this.inputId = sensorId; this.activation = activation; } /** * @return the sensorId */ Integer getInputId() { return inputId; } /** * @return the activation */ double getActivation() { return activation; } @Override public int compareTo(InputLineActivation sensorLineActivation) { if (sensorLineActivation.getActivation() < this.getActivation()) { return -1; } else if (sensorLineActivation.getActivation() > this.getActivation()) { return 1; } return 0; } @Override public String toString() { return inputId + "(" + activation + ")"; } }
2,469
27.390805
94
java
AHaH
AHaH-master/ahah-combinatorial/src/main/java/com/mancrd/ahah/combinatorial/BinarySetConverter.java
/** * Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]> * * M. Alexander Nugent Consulting Research License Agreement * Non-Commercial Academic Use Only * * This Software is proprietary. By installing, copying, or otherwise using this * Software, you agree to be bound by the terms of this license. If you do not agree, * do not install, copy, or use the Software. The Software is protected by copyright * and other intellectual property laws. * * You may use the Software for non-commercial academic purpose, subject to the following * restrictions. You may copy and use the Software for peer-review and methods verification * only. You may not create derivative works of the Software. You may not use or distribute * the Software or any derivative works in any form for commercial or non-commercial purposes. * * Violators will be prosecuted to the full extent of the law. * * All rights reserved. No warranty, explicit or implicit, provided. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.mancrd.ahah.combinatorial; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import java.util.Random; /** * @author alexnugent */ public class BinarySetConverter { public static void main(String[] args) { int setSize = 8; boolean[] randomPath = getRandomPath(getNumEncodingBits(setSize)); System.out.println(binaryArrayToString(randomPath)); int[] set = getSet(setSize, randomPath); System.out.println(Arrays.toString(set)); } public static String binaryArrayToString(boolean[] p) { StringBuilder s = new StringBuilder(); for (int i = 0; i < p.length; i++) { if (p[i]) { s.append("1"); } else { s.append("0"); } } return s.toString(); } public static boolean[] getRandomPath(int size) { Random rand = new Random(); boolean[] rb = new boolean[size]; for (int i = 0; i < rb.length; i++) { rb[i] = rand.nextBoolean(); } return rb; } public static int[] getSet(int setSize, boolean[] b) { List<Integer> a = new LinkedList<Integer>(); for (int i = 0; i < setSize; i++) { a.add(i); } int[] set = new int[setSize]; int idx = 0; for (int i = 0; i < set.length; i++) { int numBits = (int) Math.ceil(logBase2(a.size())); int setIndx = getSetIndex(a.size(), Arrays.copyOfRange(b, idx, idx + numBits)); set[i] = a.get(setIndx); a.remove(setIndx); idx += numBits; } return set; } public static int getNumEncodingBits(int setSize) { int numBits = 0; for (int i = setSize; i > 0; i--) { numBits += (int) Math.ceil(logBase2(i)); } return numBits; } public static int getSetIndex(int setSize, boolean[] path) { double n = Math.ceil(logBase2(setSize)); if (path.length < n) { throw new RuntimeException("path[] length must exceed " + n + " for a setSize of " + setSize); } return (int) Math.round(setSize * booleanArrayToInt(path) / Math.pow(2, path.length)); } public static double logBase2(double x) { return Math.log(x) / Math.log(2); } static int booleanArrayToInt(boolean[] arr) { int n = 0; for (boolean b : arr) n = (n << 1) | (b ? 1 : 0); return n; } private static boolean[] toBinary(int number, int base) { final boolean[] ret = new boolean[base]; for (int i = 0; i < base; i++) { ret[base - 1 - i] = (1 << i & number) != 0; } return ret; } }
3,971
27.371429
100
java
AHaH
AHaH-master/ahah-combinatorial/src/main/java/com/mancrd/ahah/combinatorial/CountObject.java
/** * Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]> * * M. Alexander Nugent Consulting Research License Agreement * Non-Commercial Academic Use Only * * This Software is proprietary. By installing, copying, or otherwise using this * Software, you agree to be bound by the terms of this license. If you do not agree, * do not install, copy, or use the Software. The Software is protected by copyright * and other intellectual property laws. * * You may use the Software for non-commercial academic purpose, subject to the following * restrictions. You may copy and use the Software for peer-review and methods verification * only. You may not create derivative works of the Software. You may not use or distribute * the Software or any derivative works in any form for commercial or non-commercial purposes. * * Violators will be prosecuted to the full extent of the law. * * All rights reserved. No warranty, explicit or implicit, provided. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.mancrd.ahah.combinatorial; /** * @author alexnugent */ public class CountObject { private int count = 0; public void inc() { count++; } public int getCount() { return count; } }
1,690
33.510204
94
java
AHaH
AHaH-master/ahah-combinatorial/src/main/java/com/mancrd/ahah/combinatorial/StrikeSearch.java
/** * Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]> * * M. Alexander Nugent Consulting Research License Agreement * Non-Commercial Academic Use Only * * This Software is proprietary. By installing, copying, or otherwise using this * Software, you agree to be bound by the terms of this license. If you do not agree, * do not install, copy, or use the Software. The Software is protected by copyright * and other intellectual property laws. * * You may use the Software for non-commercial academic purpose, subject to the following * restrictions. You may copy and use the Software for peer-review and methods verification * only. You may not create derivative works of the Software. You may not use or distribute * the Software or any derivative works in any form for commercial or non-commercial purposes. * * Violators will be prosecuted to the full extent of the law. * * All rights reserved. No warranty, explicit or implicit, provided. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.mancrd.ahah.combinatorial; /** * @author alexnugent */ public class StrikeSearch extends Search { private final boolean[] register; private float lastValue = 0; private float bestValue = Float.MAX_VALUE; private float aveValue = 0; StrikeNode strikeNode; /** * exponential moving average of solution value. If solution is better than average, nodes get Hebbian reward. * smaller values result in integration over longer time window. If k = 1, average value becomes last value. */ private final float k = .4f; private final int prunePeriod = 10000; int sameCount = 0; int convergenceAttempts = 0; /** * Constructor * * @param valuator * @param maxSteps * @param alpha * @param beta */ public StrikeSearch(Valuator valuator, int maxSteps, float alpha, float beta) { this.valuator = valuator; this.register = new boolean[valuator.getMaxBitLength()]; this.maxSteps = maxSteps; this.strikeNode = new StrikeNode(); StrikeNode.set(alpha, beta); // static variable set for all future child nodes. strikeNode.read(register, 0); // initializes the register lastValue = aveValue = valuator.getConfigValue(register); // init the values } @Override public void run() { for (int i = 0; i < maxSteps; i++) { strikeNode.read(register, 0); float value = valuator.getConfigValue(register); if (value < aveValue) { strikeNode.write(true, register, 0); if (value < bestValue) { bestValue = value; } } if (i % prunePeriod == 0) { strikeNode.prune(); } aveValue = (1 - k) * aveValue + k * value; if (value == lastValue) { sameCount++; if (sameCount > 5) { convergenceAttempts = i - 5; return; } } else { sameCount = 0; } lastValue = value; } convergenceAttempts = maxSteps; } @Override public int getConvergenceAttempts() { return convergenceAttempts; } @Override public float getBestValue() { return bestValue; } public int getNumNodes() { return strikeNode.getNumNodes(); } }
3,662
27.84252
112
java
AHaH
AHaH-master/ahah-combinatorial/src/main/java/com/mancrd/ahah/combinatorial/Search.java
/** * Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]> * * M. Alexander Nugent Consulting Research License Agreement * Non-Commercial Academic Use Only * * This Software is proprietary. By installing, copying, or otherwise using this * Software, you agree to be bound by the terms of this license. If you do not agree, * do not install, copy, or use the Software. The Software is protected by copyright * and other intellectual property laws. * * You may use the Software for non-commercial academic purpose, subject to the following * restrictions. You may copy and use the Software for peer-review and methods verification * only. You may not create derivative works of the Software. You may not use or distribute * the Software or any derivative works in any form for commercial or non-commercial purposes. * * Violators will be prosecuted to the full extent of the law. * * All rights reserved. No warranty, explicit or implicit, provided. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.mancrd.ahah.combinatorial; /** * @author timmolter */ public abstract class Search { Valuator valuator; int maxSteps; public abstract void run(); public abstract int getConvergenceAttempts(); public abstract float getBestValue(); }
1,735
36.73913
94
java
AHaH
AHaH-master/ahah-combinatorial/src/main/java/com/mancrd/ahah/combinatorial/Valuator.java
/** * Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]> * * M. Alexander Nugent Consulting Research License Agreement * Non-Commercial Academic Use Only * * This Software is proprietary. By installing, copying, or otherwise using this * Software, you agree to be bound by the terms of this license. If you do not agree, * do not install, copy, or use the Software. The Software is protected by copyright * and other intellectual property laws. * * You may use the Software for non-commercial academic purpose, subject to the following * restrictions. You may copy and use the Software for peer-review and methods verification * only. You may not create derivative works of the Software. You may not use or distribute * the Software or any derivative works in any form for commercial or non-commercial purposes. * * Violators will be prosecuted to the full extent of the law. * * All rights reserved. No warranty, explicit or implicit, provided. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.mancrd.ahah.combinatorial; /** * @author alexnugent */ public interface Valuator { public float getConfigValue(boolean[] path); public int getMaxBitLength(); }
1,655
39.390244
94
java
AHaH
AHaH-master/ahah-combinatorial/src/main/java/com/mancrd/ahah/combinatorial/StrikeNode.java
/** * Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]> * * M. Alexander Nugent Consulting Research License Agreement * Non-Commercial Academic Use Only * * This Software is proprietary. By installing, copying, or otherwise using this * Software, you agree to be bound by the terms of this license. If you do not agree, * do not install, copy, or use the Software. The Software is protected by copyright * and other intellectual property laws. * * You may use the Software for non-commercial academic purpose, subject to the following * restrictions. You may copy and use the Software for peer-review and methods verification * only. You may not create derivative works of the Software. You may not use or distribute * the Software or any derivative works in any form for commercial or non-commercial purposes. * * Violators will be prosecuted to the full extent of the law. * * All rights reserved. No warranty, explicit or implicit, provided. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.mancrd.ahah.combinatorial; import java.util.Random; /** * @author alexnugent */ public class StrikeNode { protected static Random rand = new Random(); protected static float alpha; protected static float beta; protected static float alphaOverBeta; protected static float noise = .025f; protected static float prune = .01f; private StrikeNode up; private StrikeNode dwn; private double ktbit = 0; // i.e. the weight. private double y = 0; /** * Constructor */ public StrikeNode() { } public static void set(float alpha, float beta) { StrikeNode.alpha = alpha; StrikeNode.beta = beta; StrikeNode.alphaOverBeta = alpha / beta; } public void countChildren(CountObject count) { if (up != null) { count.inc(); up.countChildren(count); } if (dwn != null) { count.inc(); dwn.countChildren(count); } } public void prune() { if (Math.abs(ktbit) < alphaOverBeta * prune) { dwn = null; up = null; } else { if (up != null) { up.prune(); } if (dwn != null) { dwn.prune(); } } } public void write(boolean z, boolean[] register, int idx) { if (idx == register.length) { return; } if (z) { if (register[idx]) { ktbit += alpha; up.write(z, register, idx + 1); } else { ktbit -= alpha; dwn.write(z, register, idx + 1); } } else { if (register[idx]) { ktbit -= alpha; up.write(z, register, idx + 1); } else { ktbit += alpha; dwn.write(z, register, idx + 1); } } } public void read(boolean[] register, int idx) { if (idx == register.length) { return; } y = ktbit + rand.nextGaussian() * noise; if (y > 0) { register[idx] = true; if (up == null) { up = new StrikeNode(); } up.read(register, idx + 1); } else { register[idx] = false; if (dwn == null) { dwn = new StrikeNode(); } dwn.read(register, idx + 1); } ktbit -= beta * y; // anti-hebbian read } /** * How many nodes are in the tree below this node * * @return */ public int getNumNodes() { CountObject co = new CountObject(); countChildren(co); return co.getCount(); } }
3,869
22.313253
94
java
AHaH
AHaH-master/ahah-combinatorial/src/main/java/com/mancrd/ahah/combinatorial/RandomSearch.java
/** * Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]> * * M. Alexander Nugent Consulting Research License Agreement * Non-Commercial Academic Use Only * * This Software is proprietary. By installing, copying, or otherwise using this * Software, you agree to be bound by the terms of this license. If you do not agree, * do not install, copy, or use the Software. The Software is protected by copyright * and other intellectual property laws. * * You may use the Software for non-commercial academic purpose, subject to the following * restrictions. You may copy and use the Software for peer-review and methods verification * only. You may not create derivative works of the Software. You may not use or distribute * the Software or any derivative works in any form for commercial or non-commercial purposes. * * Violators will be prosecuted to the full extent of the law. * * All rights reserved. No warranty, explicit or implicit, provided. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.mancrd.ahah.combinatorial; import java.util.Random; public class RandomSearch extends Search { private final boolean[] register; private float bestValue = Float.MAX_VALUE; /** * Just randomly guesses bit patterns. No directed search. Used as a control to show that fractal flow fabric is performing a directed search. * * @param valuator * @param maxSteps */ public RandomSearch(Valuator valuator, int maxSteps) { this.valuator = valuator; this.register = new boolean[valuator.getMaxBitLength()]; this.maxSteps = maxSteps; setRegister(); } @Override public void run() { for (int i = 0; i < maxSteps; i++) { setRegister(); float value = valuator.getConfigValue(register); if (value < bestValue) { bestValue = value; } } } private void setRegister() { Random rand = new Random(); for (int i = 0; i < register.length; i++) { register[i] = rand.nextBoolean(); } } @Override public int getConvergenceAttempts() { return maxSteps; // for random search, all attempts are used } @Override public float getBestValue() { return bestValue; } }
2,669
28.021739
144
java
AHaH
AHaH-master/ahah-classifier/src/test/java/com/knowmtech/ahah/classifier/TestClassifierSerialization.java
/** * Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]> * * M. Alexander Nugent Consulting Research License Agreement * Non-Commercial Academic Use Only * * This Software is proprietary. By installing, copying, or otherwise using this * Software, you agree to be bound by the terms of this license. If you do not agree, * do not install, copy, or use the Software. The Software is protected by copyright * and other intellectual property laws. * * You may use the Software for non-commercial academic purpose, subject to the following * restrictions. You may copy and use the Software for peer-review and methods verification * only. You may not create derivative works of the Software. You may not use or distribute * the Software or any derivative works in any form for commercial or non-commercial purposes. * * Violators will be prosecuted to the full extent of the law. * * All rights reserved. No warranty, explicit or implicit, provided. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.knowmtech.ahah.classifier; import java.util.ArrayList; import java.util.List; import org.junit.Ignore; import com.mancrd.ahah.classifier.Classifier; import com.mancrd.ahah.classifier.ClassifierOutput; /** * @author timmolter */ @Ignore public class TestClassifierSerialization { public static void main(String[] args) { // create a classifier Classifier classifier = new Classifier("TestClassifierSerialization"); // put some data in it List<long[]> spikes = new ArrayList<long[]>(); spikes.add(new long[] { 8765865L, 65434349L }); ClassifierOutput classifierOutput = classifier.update(new String[] { "hi", "bye" }, spikes); System.out.println(classifierOutput.getTotalConfidence(0)); // save the classifier's state long writeTime = classifier.serializeClassifier(); System.out.println("writeTime= " + writeTime); // reopen the classifier classifier = new Classifier("TestClassifierSerialization"); // test that the data is still in it classifierOutput = classifier.update(new String[] { "hi", "bye" }, spikes); System.out.println(classifierOutput.getTotalConfidence(0)); } }
2,637
37.794118
96
java
AHaH
AHaH-master/ahah-classifier/src/test/java/com/knowmtech/ahah/classifier/TestClassificationEvaluator.java
/** * Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]> * * M. Alexander Nugent Consulting Research License Agreement * Non-Commercial Academic Use Only * * This Software is proprietary. By installing, copying, or otherwise using this * Software, you agree to be bound by the terms of this license. If you do not agree, * do not install, copy, or use the Software. The Software is protected by copyright * and other intellectual property laws. * * You may use the Software for non-commercial academic purpose, subject to the following * restrictions. You may copy and use the Software for peer-review and methods verification * only. You may not create derivative works of the Software. You may not use or distribute * the Software or any derivative works in any form for commercial or non-commercial purposes. * * Violators will be prosecuted to the full extent of the law. * * All rights reserved. No warranty, explicit or implicit, provided. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.knowmtech.ahah.classifier; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import org.junit.Test; import com.mancrd.ahah.classifier.ClassificationEvaluator; /** * @author timmolter */ public class TestClassificationEvaluator { @Test public void test0() { Set<String> allLabels = new HashSet<String>(); allLabels.add("t"); allLabels.add("f"); ClassificationEvaluator evaluator = new ClassificationEvaluator(allLabels); // t, t Set<String> trueLabels = new HashSet<String>(); trueLabels.add("t"); List<String> labels = new ArrayList<String>(); labels.add("t"); evaluator.update(trueLabels, labels); assertThat(evaluator.getAccuracyMicroAve(), is(equalTo(1.0))); // t, t trueLabels = new HashSet<String>(); trueLabels.add("t"); labels = new ArrayList<String>(); labels.add("t"); evaluator.update(trueLabels, labels); assertThat(evaluator.getAccuracyMicroAve(), is(equalTo(1.0))); // f, f trueLabels = new HashSet<String>(); trueLabels.add("f"); labels = new ArrayList<String>(); labels.add("f"); evaluator.update(trueLabels, labels); assertThat(evaluator.getAccuracyMicroAve(), is(equalTo(1.0))); // t, f trueLabels = new HashSet<String>(); trueLabels.add("t"); labels = new ArrayList<String>(); labels.add("f"); evaluator.update(trueLabels, labels); assertThat(evaluator.getAccuracyMicroAve(), is(equalTo(.75))); } }
3,149
32.157895
94
java
AHaH
AHaH-master/ahah-classifier/src/test/java/com/knowmtech/ahah/classifier/TestClassificationRate.java
/** * Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]> * * M. Alexander Nugent Consulting Research License Agreement * Non-Commercial Academic Use Only * * This Software is proprietary. By installing, copying, or otherwise using this * Software, you agree to be bound by the terms of this license. If you do not agree, * do not install, copy, or use the Software. The Software is protected by copyright * and other intellectual property laws. * * You may use the Software for non-commercial academic purpose, subject to the following * restrictions. You may copy and use the Software for peer-review and methods verification * only. You may not create derivative works of the Software. You may not use or distribute * the Software or any derivative works in any form for commercial or non-commercial purposes. * * Violators will be prosecuted to the full extent of the law. * * All rights reserved. No warranty, explicit or implicit, provided. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.knowmtech.ahah.classifier; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.junit.Test; import com.mancrd.ahah.classifier.ClassificationRate; /** * @author timmolter */ public class TestClassificationRate { @Test public void testClassificationRateSort() { ClassificationRate c1 = new ClassificationRate("RED"); c1.incTruePositiveCount(); c1.incTruePositiveCount(); c1.incTruePositiveCount(); c1.incFalsePositiveCount(); c1.incFalsePositiveCount(); ClassificationRate c2 = new ClassificationRate("BLUE"); c2.incTruePositiveCount(); c2.incTruePositiveCount(); c2.incTruePositiveCount(); c2.incFalsePositiveCount(); ClassificationRate c3 = new ClassificationRate("GREEN"); c3.incTruePositiveCount(); c3.incTruePositiveCount(); c3.incTruePositiveCount(); List<ClassificationRate> classificationRateList = new ArrayList<ClassificationRate>(); classificationRateList.add(c1); classificationRateList.add(c2); classificationRateList.add(c3); assertThat(classificationRateList.get(0).getLabel(), is(equalTo("RED"))); assertThat(classificationRateList.get(1).getLabel(), is(equalTo("BLUE"))); assertThat(classificationRateList.get(2).getLabel(), is(equalTo("GREEN"))); Collections.sort(classificationRateList); assertThat(classificationRateList.get(0).getLabel(), is(equalTo("GREEN"))); assertThat(classificationRateList.get(1).getLabel(), is(equalTo("BLUE"))); assertThat(classificationRateList.get(2).getLabel(), is(equalTo("RED"))); } }
3,229
37
94
java
AHaH
AHaH-master/ahah-classifier/src/test/java/com/knowmtech/ahah/classifier/map/TroveMapSerializeTest.java
/** * Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]> * * M. Alexander Nugent Consulting Research License Agreement * Non-Commercial Academic Use Only * * This Software is proprietary. By installing, copying, or otherwise using this * Software, you agree to be bound by the terms of this license. If you do not agree, * do not install, copy, or use the Software. The Software is protected by copyright * and other intellectual property laws. * * You may use the Software for non-commercial academic purpose, subject to the following * restrictions. You may copy and use the Software for peer-review and methods verification * only. You may not create derivative works of the Software. You may not use or distribute * the Software or any derivative works in any form for commercial or non-commercial purposes. * * Violators will be prosecuted to the full extent of the law. * * All rights reserved. No warranty, explicit or implicit, provided. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.knowmtech.ahah.classifier.map; import gnu.trove.map.hash.TIntFloatHashMap; import gnu.trove.map.hash.TLongObjectHashMap; import gnu.trove.procedure.TIntFloatProcedure; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.Arrays; import org.junit.Ignore; /** * @author alexnugent */ @Ignore public class TroveMapSerializeTest extends MapTest { private final TLongObjectHashMap<TIntFloatHashMap> map = new TLongObjectHashMap<TIntFloatHashMap>(); public static void main(String[] args) throws IOException, ClassNotFoundException { TroveMapSerializeTest troveMapTest = new TroveMapSerializeTest(); System.out.println(Arrays.toString(troveMapTest.test())); troveMapTest.write(); } private void write() throws IOException, ClassNotFoundException { long startTime = System.nanoTime(); FileOutputStream f = new FileOutputStream("serialize1.ser"); ObjectOutputStream out = new ObjectOutputStream(f); map.writeExternal(out); long writeTime = (System.nanoTime() - startTime) / 1000000000; System.out.println("writeTime= " + writeTime); TLongObjectHashMap<TIntFloatHashMap> map2 = new TLongObjectHashMap<TIntFloatHashMap>(); FileInputStream f2 = new FileInputStream("serialize1.ser"); ObjectInputStream in = new ObjectInputStream(f2); map2.readExternal(in); long readTime = (System.nanoTime() - writeTime) / 1000000000; System.out.println("readTime= " + writeTime); // for (int i = 0; i < 100; i++) { // TIntFloatHashMap innerMap = map2.get(i); // System.out.println(innerMap.toString()); // } } @Override void accumulate(long[] spikes) { TIntFloatHashMap activations = new TIntFloatHashMap(); TIntFloatProcedure procedure = new TroveProcedure(activations); for (int i = 0; i < spikes.length; i++) { TIntFloatHashMap labelMap = map.get(spikes[i]); labelMap.forEachEntry(procedure); } } @Override void put(long spikeId, int labelId, float w) { TIntFloatHashMap subMap = map.get(spikeId); if (subMap == null) { subMap = new TIntFloatHashMap(); map.put(spikeId, subMap); } subMap.put(labelId, w); } class TroveProcedure implements TIntFloatProcedure { TIntFloatHashMap activations; public TroveProcedure(TIntFloatHashMap activations) { this.activations = activations; } @Override public boolean execute(int key, float value) { float y = activations.get(key); y += value; activations.put(key, y); return true; } } }
4,154
30.961538
102
java
AHaH
AHaH-master/ahah-classifier/src/test/java/com/knowmtech/ahah/classifier/map/TroveMapTest.java
/** * Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]> * * M. Alexander Nugent Consulting Research License Agreement * Non-Commercial Academic Use Only * * This Software is proprietary. By installing, copying, or otherwise using this * Software, you agree to be bound by the terms of this license. If you do not agree, * do not install, copy, or use the Software. The Software is protected by copyright * and other intellectual property laws. * * You may use the Software for non-commercial academic purpose, subject to the following * restrictions. You may copy and use the Software for peer-review and methods verification * only. You may not create derivative works of the Software. You may not use or distribute * the Software or any derivative works in any form for commercial or non-commercial purposes. * * Violators will be prosecuted to the full extent of the law. * * All rights reserved. No warranty, explicit or implicit, provided. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.knowmtech.ahah.classifier.map; import gnu.trove.map.hash.TIntFloatHashMap; import gnu.trove.map.hash.TLongObjectHashMap; import gnu.trove.procedure.TIntFloatProcedure; import java.util.Arrays; import org.junit.Ignore; /** * @author alexnugent */ @Ignore public class TroveMapTest extends MapTest { private final TLongObjectHashMap<TIntFloatHashMap> map = new TLongObjectHashMap<TIntFloatHashMap>(); public static void main(String[] args) { TroveMapTest troveMapTest = new TroveMapTest(); System.out.println(Arrays.toString(troveMapTest.test())); } @Override void accumulate(long[] spikes) { TIntFloatHashMap activations = new TIntFloatHashMap(); TIntFloatProcedure procedure = new TroveProcedure(activations); for (int i = 0; i < spikes.length; i++) { TIntFloatHashMap labelMap = map.get(spikes[i]); labelMap.forEachEntry(procedure); } } @Override void put(long spikeId, int labelId, float w) { TIntFloatHashMap subMap = map.get(spikeId); if (subMap == null) { subMap = new TIntFloatHashMap(); map.put(spikeId, subMap); } subMap.put(labelId, w); } class TroveProcedure implements TIntFloatProcedure { TIntFloatHashMap activations; public TroveProcedure(TIntFloatHashMap activations) { this.activations = activations; } @Override public boolean execute(int key, float value) { float y = activations.get(key); y += value; activations.put(key, y); return true; } } }
3,013
29.444444
102
java
AHaH
AHaH-master/ahah-classifier/src/test/java/com/knowmtech/ahah/classifier/map/JavaMapTest.java
/** * Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]> * * M. Alexander Nugent Consulting Research License Agreement * Non-Commercial Academic Use Only * * This Software is proprietary. By installing, copying, or otherwise using this * Software, you agree to be bound by the terms of this license. If you do not agree, * do not install, copy, or use the Software. The Software is protected by copyright * and other intellectual property laws. * * You may use the Software for non-commercial academic purpose, subject to the following * restrictions. You may copy and use the Software for peer-review and methods verification * only. You may not create derivative works of the Software. You may not use or distribute * the Software or any derivative works in any form for commercial or non-commercial purposes. * * Violators will be prosecuted to the full extent of the law. * * All rights reserved. No warranty, explicit or implicit, provided. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.knowmtech.ahah.classifier.map; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import org.junit.Ignore; /** * @author alexnugent */ @Ignore public class JavaMapTest extends MapTest { private final Map<Long, Map<Integer, Float>> map = new HashMap<Long, Map<Integer, Float>>(); public static void main(String[] args) { JavaMapTest javaMapTest = new JavaMapTest(); System.out.println(Arrays.toString(javaMapTest.test())); } @Override void accumulate(long[] spikes) { Map<Integer, Float> activations = new HashMap<Integer, Float>(); for (int i = 0; i < spikes.length; i++) { Map<Integer, Float> labelMap = map.get(spikes[i]); for (Map.Entry<Integer, Float> entry : labelMap.entrySet()) { Float y = activations.get(entry.getKey()); if (y == null) { y = 0f; } y += entry.getValue(); activations.put(entry.getKey(), y); } } } @Override void put(long spikeId, int labelId, float w) { Map<Integer, Float> subMap = map.get(spikeId); if (subMap == null) { subMap = new HashMap<Integer, Float>(); map.put(spikeId, subMap); } subMap.put(labelId, w); } }
2,697
33.151899
94
java
AHaH
AHaH-master/ahah-classifier/src/test/java/com/knowmtech/ahah/classifier/map/MapTest.java
/** * Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]> * * M. Alexander Nugent Consulting Research License Agreement * Non-Commercial Academic Use Only * * This Software is proprietary. By installing, copying, or otherwise using this * Software, you agree to be bound by the terms of this license. If you do not agree, * do not install, copy, or use the Software. The Software is protected by copyright * and other intellectual property laws. * * You may use the Software for non-commercial academic purpose, subject to the following * restrictions. You may copy and use the Software for peer-review and methods verification * only. You may not create derivative works of the Software. You may not use or distribute * the Software or any derivative works in any form for commercial or non-commercial purposes. * * Violators will be prosecuted to the full extent of the law. * * All rights reserved. No warranty, explicit or implicit, provided. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.knowmtech.ahah.classifier.map; import java.util.Random; import org.junit.Ignore; /** * @author timmolter */ @Ignore public abstract class MapTest { final int spikeSetSize = 100000; final int labelSetSize = 500; final int spikePatternSize = 500; final int numGetAccumulates = 1000; long[] test() { long[] results = new long[4]; Runtime runtime = Runtime.getRuntime(); Random rand = new Random(); long startTime = System.nanoTime(); for (long spikeId = 0; spikeId < spikeSetSize; spikeId++) { for (int labelID = 0; labelID < labelSetSize; labelID++) { put(spikeId, labelID, rand.nextFloat()); } } results[0] = (System.nanoTime() - startTime) / 1000000000; startTime = System.nanoTime(); for (int i = 0; i < numGetAccumulates; i++) { accumulate(getRandomSpikes()); } results[1] = (System.nanoTime() - startTime) / 1000000000; results[2] = runtime.totalMemory() / 1000000; results[3] = runtime.freeMemory() / 1000000; return results; } long[] getRandomSpikes() { long[] spikes = new long[spikePatternSize]; for (int i = 0; i < spikes.length; i++) { spikes[i] = (long) (Math.random() * spikeSetSize); } return spikes; } abstract void accumulate(long[] spikes); abstract void put(long spikeId, int labelId, float w); }
2,838
32.4
94
java
AHaH
AHaH-master/ahah-classifier/src/main/java/com/mancrd/ahah/classifier/LinkWeightProcedure.java
/** * Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]> * * M. Alexander Nugent Consulting Research License Agreement * Non-Commercial Academic Use Only * * This Software is proprietary. By installing, copying, or otherwise using this * Software, you agree to be bound by the terms of this license. If you do not agree, * do not install, copy, or use the Software. The Software is protected by copyright * and other intellectual property laws. * * You may use the Software for non-commercial academic purpose, subject to the following * restrictions. You may copy and use the Software for peer-review and methods verification * only. You may not create derivative works of the Software. You may not use or distribute * the Software or any derivative works in any form for commercial or non-commercial purposes. * * Violators will be prosecuted to the full extent of the law. * * All rights reserved. No warranty, explicit or implicit, provided. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.mancrd.ahah.classifier; import gnu.trove.map.hash.TIntFloatHashMap; import gnu.trove.procedure.TIntFloatProcedure; import gnu.trove.procedure.TLongObjectProcedure; import java.util.Collections; import java.util.LinkedList; import java.util.List; import com.mancrd.ahah.commons.LinkWeight; /** * @author alexnugent */ public class LinkWeightProcedure implements TLongObjectProcedure<TIntFloatHashMap> { private final List<LinkWeight> linkWeights = new LinkedList<LinkWeight>(); @Override public boolean execute(long spike, TIntFloatHashMap submap) { LinkWeightProcedure2 linkWeightProcedure2 = new LinkWeightProcedure2(linkWeights, spike); submap.forEachEntry(linkWeightProcedure2); return false; } public List<LinkWeight> getSortedLinkWeights() { Collections.sort(linkWeights); return linkWeights; } } class LinkWeightProcedure2 implements TIntFloatProcedure { private final List<LinkWeight> linkWeights; private final long spike; public LinkWeightProcedure2(List<LinkWeight> linkWeights, long spike) { this.spike = spike; this.linkWeights = linkWeights; } @Override public boolean execute(int label, float weight) { linkWeights.add(new LinkWeight(label, label, weight)); return true; } }
2,753
33
94
java
AHaH
AHaH-master/ahah-classifier/src/main/java/com/mancrd/ahah/classifier/ClassificationEvaluator.java
/** * Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]> * * M. Alexander Nugent Consulting Research License Agreement * Non-Commercial Academic Use Only * * This Software is proprietary. By installing, copying, or otherwise using this * Software, you agree to be bound by the terms of this license. If you do not agree, * do not install, copy, or use the Software. The Software is protected by copyright * and other intellectual property laws. * * You may use the Software for non-commercial academic purpose, subject to the following * restrictions. You may copy and use the Software for peer-review and methods verification * only. You may not create derivative works of the Software. You may not use or distribute * the Software or any derivative works in any form for commercial or non-commercial purposes. * * Violators will be prosecuted to the full extent of the law. * * All rights reserved. No warranty, explicit or implicit, provided. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.mancrd.ahah.classifier; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; /** * Used to keep track of classification performance. * * @author alexnugent */ public class ClassificationEvaluator { /** score keeper for classifier classifications */ private final Map<String, ClassificationRate> classificationRateMap; private boolean isDeclared = false; public ClassificationEvaluator() { classificationRateMap = new HashMap<String, ClassificationRate>(); } /** * Constructor Must provide a set of labels that will be used for evaluation. Other labels will be ignored for evaluation. */ public ClassificationEvaluator(Set<String> labels) { classificationRateMap = new HashMap<String, ClassificationRate>(); declareLabels(labels); isDeclared = true; } /** * @param trueLabel: the actual (supervised) label. * @param label: the label given by the classifier. */ public void update(String trueLabel, String label) { Set<String> trueLabels = new HashSet<String>(); trueLabels.add(trueLabel); List<String> labels = new ArrayList<String>(); labels.add(label); update(trueLabels, labels); } /** * declare the labels that should be evaluated. * * @param labels */ private void declareLabels(Set<String> labels) { for (String label : labels) { if (label.length() == 0 || label.equalsIgnoreCase("")) { continue; } ClassificationRate classificationRate = classificationRateMap.get(label); if (classificationRate == null) { classificationRate = new ClassificationRate(label); classificationRateMap.put(label, classificationRate); } } } /** * Here's where results come in * * @param trueLabels: the supervised labels * @param labels: the labels given by the classifier. */ public void update(Set<String> trueLabels, List<String> labels) { if (isDeclared) { Set<String> allLabels = classificationRateMap.keySet(); for (String s : allLabels) { ClassificationRate classificationRate = classificationRateMap.get(s); if (classificationRate == null) { throw new RuntimeException("Label as not previously been declared"); } if (trueLabels.contains(s) && labels.contains(s)) {// TRUE POSITIVE classificationRate.incTruePositiveCount(); } else if (trueLabels.contains(s) && !labels.contains(s)) {// FALSE NEGATIVE classificationRate.incFalseNegativeCount(); } else if (!trueLabels.contains(s) && labels.contains(s)) {// FALSE POSITIVE classificationRate.incFalsePositiveCount(); } else if (!trueLabels.contains(s) && !labels.contains(s)) {// TRUE NEGATIVE classificationRate.incTrueNegativeCount(); } } } else { for (String trueLabel : trueLabels) { if (labels.contains(trueLabel)) {// true positive classificationRateMap.get(trueLabel).incTruePositiveCount(); } else {// false-negative classificationRateMap.get(trueLabel).incFalseNegativeCount(); } } for (String label : labels) { if (!trueLabels.contains(label)) {// false positive classificationRateMap.get(label).incFalsePositiveCount(); } } } } /** * calculates the classification rate for a single trueLabelId * * @param trueLabel * @return double - the classification for a single trueLabel. */ public ClassificationRate getClassificationRate(String trueLabel) { return classificationRateMap.get(trueLabel); } /** * @return micro-averaged F1 score. F1=2*TP/(2*TP+FP FN) */ public double getF1MicroAve() { int[] c = getCounts(); return 2 * ((double) c[0]) / (2 * c[0] + c[1] + c[3]); } /** * @return micro-averaged recall score. Recall=TP/(TP+FN) */ public double getRecallMicroAve() { int[] c = getCounts(); if (c[0] == 0) { return 0.0; } return (double) (c[0]) / (double) (c[0] + c[3]); } /** * @return micro-averaged precision score. Precision=TP/(TP+FP) */ public double getPrecisionMicroAve() { int[] c = getCounts(); if (c[0] == 0) { return 0.0; } return (double) (c[0]) / (double) (c[0] + c[1]); } /** * @return micro averaged accuracy. Accuracy=(TP+TN)/(TP+FP+TN+FN) */ public double getAccuracyMicroAve() { int[] c = getCounts(); return (double) (c[0] + c[2]) / (double) (c[0] + c[1] + c[2] + c[3]); } /** * @return macro-averaged F1 score. F1=TP/(2*TP+FP FN) */ public double getF1MacroAve() { double v = 0; for (ClassificationRate classificationRate : classificationRateMap.values()) { v += classificationRate.getF1(); } return v / classificationRateMap.size(); } /** * @return macro-averaged recall score. Recall=TP/(TP+FN) */ public double getRecallMacroAve() { double v = 0; for (ClassificationRate classificationRate : classificationRateMap.values()) { v += classificationRate.getRecall(); } return v / classificationRateMap.size(); } /** * @return macro-averaged precision score. Precision=TP/(TP+FP) */ public double getPrecisionMacroAve() { double v = 0; for (ClassificationRate classificationRate : classificationRateMap.values()) { v += classificationRate.getPrecision(); } return v / classificationRateMap.values().size(); } /** * @return macro averaged accuracy. Accuracy=(TP+TN)/(TP+FP+TN+FN) */ public double getAccuracyMacroAve() { double v = 0; for (ClassificationRate classificationRate : classificationRateMap.values()) { v += classificationRate.getAccuracy(); } return v / classificationRateMap.values().size(); } private int[] getCounts() { int totalTruePositiveCount = 0; int totalFalsePositiveCount = 0; int totalTrueNegativeCount = 0; int totalFalseNegativeCount = 0; for (ClassificationRate classificationRate : classificationRateMap.values()) { totalTruePositiveCount += classificationRate.getTruePositiveCount(); totalFalsePositiveCount += classificationRate.getFalsePositiveCount(); totalTrueNegativeCount += classificationRate.getTrueNegativeCount(); totalFalseNegativeCount += classificationRate.getFalseNegativeCount(); } int[] counts = { totalTruePositiveCount, totalFalsePositiveCount, totalTrueNegativeCount, totalFalseNegativeCount }; return counts; } /** * @return a List of all ClassificationRate objects holding data for each label. */ public List<ClassificationRate> getSortedClassificationRates() { List<ClassificationRate> classificationRateList = new ArrayList<ClassificationRate>(classificationRateMap.values()); Collections.sort(classificationRateList); return classificationRateList; } @Override public String toString() { DecimalFormat df = new DecimalFormat(".0000"); StringBuilder sb = new StringBuilder(); sb.append(System.getProperty("line.separator")); for (ClassificationRate classificationRate : getSortedClassificationRates()) { sb.append(classificationRate.toString()); sb.append(System.getProperty("line.separator")); } sb.append("OVERALL F1 (micro/macro) = " + df.format(getF1MicroAve()) + "/" + df.format(getF1MacroAve())); sb.append(System.getProperty("line.separator")); sb.append("OVERALL Precision (micro/macro) = " + df.format(getPrecisionMicroAve()) + "/" + df.format(getPrecisionMacroAve())); sb.append(System.getProperty("line.separator")); sb.append("OVERALL Recal (micro/macro) = " + df.format(getRecallMicroAve()) + "/" + df.format(getRecallMacroAve())); sb.append(System.getProperty("line.separator")); sb.append("OVERALL ACCURACY (micro/macro) = " + df.format(getAccuracyMicroAve()) + "/" + df.format(getAccuracyMacroAve())); sb.append(System.getProperty("line.separator")); return sb.toString(); } }
9,694
30.375405
130
java
AHaH
AHaH-master/ahah-classifier/src/main/java/com/mancrd/ahah/classifier/LinkWeightLabelProcedure.java
/** * Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]> * * M. Alexander Nugent Consulting Research License Agreement * Non-Commercial Academic Use Only * * This Software is proprietary. By installing, copying, or otherwise using this * Software, you agree to be bound by the terms of this license. If you do not agree, * do not install, copy, or use the Software. The Software is protected by copyright * and other intellectual property laws. * * You may use the Software for non-commercial academic purpose, subject to the following * restrictions. You may copy and use the Software for peer-review and methods verification * only. You may not create derivative works of the Software. You may not use or distribute * the Software or any derivative works in any form for commercial or non-commercial purposes. * * Violators will be prosecuted to the full extent of the law. * * All rights reserved. No warranty, explicit or implicit, provided. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.mancrd.ahah.classifier; import gnu.trove.map.hash.TIntFloatHashMap; import gnu.trove.procedure.TLongObjectProcedure; import java.util.LinkedList; import java.util.List; import com.mancrd.ahah.commons.LinkWeight; /** * @author alexnugent */ public class LinkWeightLabelProcedure implements TLongObjectProcedure<TIntFloatHashMap> { private final List<LinkWeight> linkWeights = new LinkedList<LinkWeight>(); int label; String labelString; public LinkWeightLabelProcedure(int label, String labelString) { this.labelString = labelString; this.label = label; } @Override public boolean execute(long spike, TIntFloatHashMap submap) { if (submap.contains(label)) { LinkWeight linkWeight = new LinkWeight(spike, label, submap.get(label)); linkWeight.setLabelString(labelString); linkWeights.add(linkWeight); } return true; } public List<LinkWeight> getLinkWeights() { return linkWeights; } }
2,445
32.972222
94
java
AHaH
AHaH-master/ahah-classifier/src/main/java/com/mancrd/ahah/classifier/ClassificationRate.java
/** * Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]> * * M. Alexander Nugent Consulting Research License Agreement * Non-Commercial Academic Use Only * * This Software is proprietary. By installing, copying, or otherwise using this * Software, you agree to be bound by the terms of this license. If you do not agree, * do not install, copy, or use the Software. The Software is protected by copyright * and other intellectual property laws. * * You may use the Software for non-commercial academic purpose, subject to the following * restrictions. You may copy and use the Software for peer-review and methods verification * only. You may not create derivative works of the Software. You may not use or distribute * the Software or any derivative works in any form for commercial or non-commercial purposes. * * Violators will be prosecuted to the full extent of the law. * * All rights reserved. No warranty, explicit or implicit, provided. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.mancrd.ahah.classifier; import java.text.DecimalFormat; /** * This class is used to hold performance evaluating statistics for classifications related to one class label. TP=TruePositive FP=FalsePositive * TN=TrueNegative FN=FalseNegative * * @author timmolter */ public class ClassificationRate implements Comparable<ClassificationRate> { private final String label; private int truePositiveCount; private int falsePositiveCount; private int falseNegativeCount; private int trueNegativeCount; /** * Constructor */ public ClassificationRate(String label) { this.label = label; truePositiveCount = 0; falsePositiveCount = 0; } public void incFalseNegativeCount() { falseNegativeCount++; } public void incTrueNegativeCount() { trueNegativeCount++; } public void incTruePositiveCount() { truePositiveCount++; } public void incFalsePositiveCount() { falsePositiveCount++; } public String getLabel() { return label; } /** * @return F1=TP/(2*TP+FP FN) */ public double getF1() { double f1 = 2 * ((getPrecision() * getRecall()) / (getPrecision() + getRecall())); if (Double.isNaN(f1)) { return 0; } else { return f1; } } /** * @return Recall=TP/(TP+FN) */ public double getRecall() { return (double) (truePositiveCount) / (double) (truePositiveCount + falseNegativeCount); } /** * @return Accuracy=(TP+TN)/(TP+FP+TN+FN) */ public double getAccuracy() { return (double) (truePositiveCount + trueNegativeCount) / (double) (truePositiveCount + falsePositiveCount + trueNegativeCount + falseNegativeCount); } /** * @return Precision=TP/(TP+FP) */ public double getPrecision() { return (double) (truePositiveCount) / (double) (truePositiveCount + falsePositiveCount); } @Override public int compareTo(ClassificationRate other) { if (other.getAccuracy() > getAccuracy()) { return 1; } else if (other.getAccuracy() < getAccuracy()) { return -1; } return 0; } public int getTruePositiveCount() { return truePositiveCount; } public void setTruePositiveCount(int truePositiveCount) { this.truePositiveCount = truePositiveCount; } public int getFalsePositiveCount() { return falsePositiveCount; } public void setFalsePositiveCount(int falsePositiveCount) { this.falsePositiveCount = falsePositiveCount; } public int getTotalCount() { return truePositiveCount + falsePositiveCount + trueNegativeCount + falseNegativeCount; } public int getFalseNegativeCount() { return falseNegativeCount; } public int getTrueNegativeCount() { return trueNegativeCount; } @Override public String toString() { DecimalFormat df = new DecimalFormat(".0000"); StringBuffer buf = new StringBuffer(); buf.append(label); buf.append(": "); buf.append("("); buf.append("TP=" + truePositiveCount + ","); buf.append("TN=" + trueNegativeCount + ","); buf.append("FP=" + falsePositiveCount + ","); buf.append("FN=" + falseNegativeCount + ","); buf.append("T=" + getTotalCount() + ","); buf.append("Ac=" + df.format(getAccuracy()) + ","); buf.append("Pr=" + df.format(getPrecision()) + ","); buf.append("Re=" + df.format(getRecall()) + ","); buf.append("F1=" + df.format(getF1()) + ")"); return buf.toString(); } }
4,927
24.801047
153
java
AHaH
AHaH-master/ahah-classifier/src/main/java/com/mancrd/ahah/classifier/ClassifierOutput.java
/** * Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]> * * M. Alexander Nugent Consulting Research License Agreement * Non-Commercial Academic Use Only * * This Software is proprietary. By installing, copying, or otherwise using this * Software, you agree to be bound by the terms of this license. If you do not agree, * do not install, copy, or use the Software. The Software is protected by copyright * and other intellectual property laws. * * You may use the Software for non-commercial academic purpose, subject to the following * restrictions. You may copy and use the Software for peer-review and methods verification * only. You may not create derivative works of the Software. You may not use or distribute * the Software or any derivative works in any form for commercial or non-commercial purposes. * * Violators will be prosecuted to the full extent of the law. * * All rights reserved. No warranty, explicit or implicit, provided. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.mancrd.ahah.classifier; import gnu.trove.map.hash.TIntFloatHashMap; import gnu.trove.map.hash.TIntObjectHashMap; import gnu.trove.procedure.TIntFloatProcedure; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; /** * This DTO encapsulates an activation map from a classifier and has convenience methods to get at the relevant data * * @author alexnugent */ public final class ClassifierOutput implements TIntFloatProcedure { /** the activation map */ private LabelOutput[] labelOutputs = null; private final TIntFloatHashMap labelActivationMap; /** * Constructor * * @param activations */ public ClassifierOutput() { labelActivationMap = new TIntFloatHashMap(); } public LabelOutput[] getLabelOutputs() { if (labelOutputs == null) { LabelOutputArrayProcedure labelOutputArrayProcedure = new LabelOutputArrayProcedure(labelActivationMap.size()); labelActivationMap.forEachEntry(labelOutputArrayProcedure); labelOutputs = labelOutputArrayProcedure.getLabelOutputs(); Arrays.sort(labelOutputs); } return labelOutputs; } public void translateLabels(TIntObjectHashMap<String> labelReverseMap) { if (getLabelOutputs() == null) { return; } for (int i = 0; i < getLabelOutputs().length; i++) { labelOutputs[i].setLabelstring(labelReverseMap.get(labelOutputs[i].getLabel())); } } /** * Returns the sum total activation for all labels in the output that exceed the given threshold. * * @param activationThreshold * @return */ public float getTotalConfidence(double confidenceThreshold) { float total = 0; for (int i = 0; i < getLabelOutputs().length; i++) { if (labelOutputs[i].getConfidence() < confidenceThreshold) { return total; } else { total += labelOutputs[i].getConfidence(); } } return total; } /** * Gets the Activation objects sorted by activation above a given confidence threshold * * @param activationThreshold * @return */ public List<LabelOutput> getSortedLabelOutputs(double confidenceThreshold) { List<LabelOutput> output = new ArrayList<LabelOutput>(); for (int i = 0; i < getLabelOutputs().length; i++) { if (labelOutputs[i].getConfidence() > confidenceThreshold) { output.add(labelOutputs[i]); } else { return output; } } return output; } /** * Gets the Activation objects sorted by activation above a given confidence threshold * * @param activationThreshold * @return */ public Set<LabelOutput> getLabelOutputSet(double confidenceThreshold) { Set<LabelOutput> output = new HashSet<LabelOutput>(); for (int i = 0; i < getLabelOutputs().length; i++) { if (labelOutputs[i].getConfidence() > confidenceThreshold) { output.add(labelOutputs[i]); } else { return output; } } return output; } /** * Gets the Activation objects sorted by activation above a given confidence threshold * * @param activationThreshold * @return */ public List<String> getSortedLabels(double confidenceThreshold) { List<String> output = new ArrayList<String>(); for (int i = 0; i < getLabelOutputs().length; i++) { if (labelOutputs[i].getConfidence() >= confidenceThreshold) { output.add(labelOutputs[i].getLabelstring()); } else { return output; } } return output; } /** * Gets the Activation objects sorted by activation above a given confidence threshold * * @param activationThreshold * @return */ public Set<String> getLabelSet(double confidenceThreshold) { Set<String> output = new HashSet<String>(); for (int i = 0; i < getLabelOutputs().length; i++) { if (labelOutputs[i].getConfidence() >= confidenceThreshold) { output.add(labelOutputs[i].getLabelstring()); } else { return output; } } return output; } /** * Gets the Activation objects sorted by activation above a given confidence threshold * * @param activationThreshold * @return */ public List<String> getSortedLabels() { List<String> output = new ArrayList<String>(); for (int i = 0; i < getLabelOutputs().length; i++) { output.add(labelOutputs[i].getLabelstring()); } return output; } /** * Returns the highest ranked label or best-guess label * * @return */ public LabelOutput getBestGuess() { if (getLabelOutputs() != null && getLabelOutputs().length > 0) { return labelOutputs[0]; } else return null; } public LabelOutput getLabelOutput(String label) { for (int i = 0; i < getLabelOutputs().length; i++) { if (labelOutputs[i].getLabelstring().equalsIgnoreCase(label)) { return labelOutputs[i]; } } return null; } /** * Returns the highest ranked label above the given confidence threshold * * @return */ public LabelOutput getBestGuessLabelOuputAboveThreshold(double confidenceThreshold) { LabelOutput output = getBestGuess(); if (output.getConfidence() >= confidenceThreshold) { return output; } else { return null; } } /** * Returns the highest ranked label above the given confidence threshold * * @return */ public String getBestGuessLabelAboveThreshold(double confidenceThreshold) { LabelOutput output = getBestGuess(); if (output.getConfidence() >= confidenceThreshold) { return output.getLabelstring(); } else { return null; } } @Override public boolean execute(int label, float weight) { if (!labelActivationMap.contains(label)) { labelActivationMap.put(label, weight); } else { float y = labelActivationMap.get(label); y += weight; labelActivationMap.put(label, y); } return true;// keep the itteration going } } class LabelOutputArrayProcedure implements TIntFloatProcedure { private final LabelOutput[] labelOutputs; private int idx = 0; public LabelOutputArrayProcedure(int size) { labelOutputs = new LabelOutput[size]; } public LabelOutput[] getLabelOutputs() { return labelOutputs; } @Override public boolean execute(int label, float y) { labelOutputs[idx] = new LabelOutput(label, y); idx++; return true; } }
7,991
25.729097
117
java
AHaH
AHaH-master/ahah-classifier/src/main/java/com/mancrd/ahah/classifier/DeleteLabelProcedure.java
/** * Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]> * * M. Alexander Nugent Consulting Research License Agreement * Non-Commercial Academic Use Only * * This Software is proprietary. By installing, copying, or otherwise using this * Software, you agree to be bound by the terms of this license. If you do not agree, * do not install, copy, or use the Software. The Software is protected by copyright * and other intellectual property laws. * * You may use the Software for non-commercial academic purpose, subject to the following * restrictions. You may copy and use the Software for peer-review and methods verification * only. You may not create derivative works of the Software. You may not use or distribute * the Software or any derivative works in any form for commercial or non-commercial purposes. * * Violators will be prosecuted to the full extent of the law. * * All rights reserved. No warranty, explicit or implicit, provided. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.mancrd.ahah.classifier; import gnu.trove.map.hash.TIntFloatHashMap; import gnu.trove.procedure.TLongObjectProcedure; /** * @author alexnugent */ public class DeleteLabelProcedure implements TLongObjectProcedure<TIntFloatHashMap> { int labelId; public DeleteLabelProcedure(int labelId) { this.labelId = labelId; } @Override public boolean execute(long spike, TIntFloatHashMap submap) { submap.remove(labelId); return true; } }
1,945
35.037037
94
java
AHaH
AHaH-master/ahah-classifier/src/main/java/com/mancrd/ahah/classifier/Classifier.java
/** * Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]> * * M. Alexander Nugent Consulting Research License Agreement * Non-Commercial Academic Use Only * * This Software is proprietary. By installing, copying, or otherwise using this * Software, you agree to be bound by the terms of this license. If you do not agree, * do not install, copy, or use the Software. The Software is protected by copyright * and other intellectual property laws. * * You may use the Software for non-commercial academic purpose, subject to the following * restrictions. You may copy and use the Software for peer-review and methods verification * only. You may not create derivative works of the Software. You may not use or distribute * the Software or any derivative works in any form for commercial or non-commercial purposes. * * Violators will be prosecuted to the full extent of the law. * * All rights reserved. No warranty, explicit or implicit, provided. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.mancrd.ahah.classifier; import gnu.trove.map.hash.TIntFloatHashMap; import gnu.trove.map.hash.TIntObjectHashMap; import gnu.trove.map.hash.TLongObjectHashMap; import gnu.trove.map.hash.TObjectIntHashMap; import gnu.trove.set.TIntSet; import gnu.trove.set.hash.TIntHashSet; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.LinkedList; import java.util.List; import java.util.Random; import com.mancrd.ahah.commons.LinkWeight; import com.mancrd.ahah.commons.utils.FileUtils; /** * This class learns to associate input spikes with input labels. It is capable of supervised and semi-supervised operation. * * @author alexnugent */ public class Classifier { private final static float STARTING_WEIGHT_MAGNITUDE = 1E-9f; // so small as to have no effect. private final TLongObjectHashMap<TIntFloatHashMap> weightMap; // input line --> (Label --> Weight) private final TIntObjectHashMap<String> labelReverseMap; private final TObjectIntHashMap<String> labelForwardMap; private final String classifierDBDir; public final static String LINK_SER_NAME = "link.ser"; public final static String FORWARD_SER_NAME = "forward.ser"; public final static String REVERSE_SER_NAME = "reverse.ser"; public final static String COUNTS_SER_NAME = "counts.ser"; private float learningRate = .1f; private boolean unsupervisedEnabled = false; private double unsupervisedConfidenceThreshold = 1; private final double bias = 0; Random random = new Random(); int numLabelsProcessed = 0; int numSpikesProcessed = 0; int numUpdates = 0; long totalClassificationTimeInNanoSeconds = 0L; /** * In-memory-only Classifier * <p> * Constructor */ public Classifier() { weightMap = new TLongObjectHashMap<TIntFloatHashMap>(); labelReverseMap = new TIntObjectHashMap<String>(); labelForwardMap = new TObjectIntHashMap<String>(); // spikeCounts = new TLongIntHashMap(); classifierDBDir = null; } /** * Constructor * * @param classifierDBDir * @param classifierName */ public Classifier(String classifierDBDir) { weightMap = new TLongObjectHashMap<TIntFloatHashMap>(); labelReverseMap = new TIntObjectHashMap<String>(); labelForwardMap = new TObjectIntHashMap<String>(); this.classifierDBDir = classifierDBDir; // load maps from File DB boolean dirExists = FileUtils.fileExists(classifierDBDir); if (dirExists) { deserializeClassifier(); } } /** * Convenience method. Calls update(String[] labels, List<long[]> spikes), after wrapping long[]. * * @param labels * @param spikes * @return */ public ClassifierOutput update(String[] labels, long[] spikes) { List<long[]> spikeList = new LinkedList<long[]>(); spikeList.add(spikes); return update(labels, spikeList); } /** * Given a set of trueLabels and an input pattern (spikes), it returns the labels based on a classification of the spikes before learning. The * classifier then learns. * * @param labels - The known true labels associated with the input Spikes. * @param spikes - a List of long[]s identifying each spike in the spike pattern. * @return - labels as Strings. */ public ClassifierOutput update(String[] labels, List<long[]> spikes) { numUpdates++; if (labels != null) { numLabelsProcessed += labels.length; } long classifiyStartTime = System.nanoTime(); int[] trueLabels = getLabelsAsInts(labels); ClassifierOutput classifierOutput = new ClassifierOutput(); int totalSpikes = 0; for (int i = 0; i < spikes.size(); i++) { numSpikesProcessed += spikes.get(i).length; for (int j = 0; j < spikes.get(i).length; j++) { addToActivation(spikes.get(i)[j], trueLabels, classifierOutput); } totalSpikes += spikes.get(i).length; } if (trueLabels != null && trueLabels.length > 0) { // learn labels // use trueLabels as true-positives TIntSet positiveLabels = new TIntHashSet(); positiveLabels.addAll(trueLabels); // use mistakes as true-negatives List<LabelOutput> labelOutputs = classifierOutput.getSortedLabelOutputs(0.0); TIntSet negativeLabels = new TIntHashSet(); for (LabelOutput labelOutput : labelOutputs) { if (!positiveLabels.contains(labelOutput.getLabel())) { negativeLabels.add(labelOutput.getLabel()); } } // learn learn(classifierOutput, positiveLabels, negativeLabels, spikes, totalSpikes); } else if (unsupervisedEnabled) { // unsupervised adaptation learn(classifierOutput, null, null, spikes, totalSpikes); } classifierOutput.translateLabels(labelReverseMap); totalClassificationTimeInNanoSeconds += System.nanoTime() - classifiyStartTime; return classifierOutput; } private int[] getLabelsAsInts(String[] labels) { if (labels == null) { return null; } int[] l = new int[labels.length]; for (int i = 0; i < l.length; i++) { l[i] = getLabelInt(labels[i]); } return l; } private int getLabelInt(String label) { if (labelForwardMap.contains(label)) { return labelForwardMap.get(label); } else { int i = labelForwardMap.size(); labelForwardMap.put(label, i); labelReverseMap.put(i, label); return i; } } private void addToActivation(long spike, int[] trueLabels, ClassifierOutput classifierOutput) { // 1. get the activations (Map<String, Double>) that have been activated in the past when this inputLine was active. TIntFloatHashMap subMap = weightMap.get(spike); if (subMap == null) {// create sub map if subMap = new TIntFloatHashMap(); weightMap.put(spike, subMap); } // add new links to true labels if they do already not exist. if (trueLabels != null) { for (int label : trueLabels) { if (!subMap.containsKey(label)) { getWeight(spike, label); // a call to this method will generate the link if it does not exist. } } } // update activations for all elements of submap subMap.forEachEntry(classifierOutput); } private void learn(ClassifierOutput classifierOutput, TIntSet positiveLabels, TIntSet negativeLabels, List<long[]> spikes, int totalSpikes) { // AHaH rule float lRate = learningRate / totalSpikes; // dynamic learning rate avoids having to parameter tweak. TotalSpikes should be constant anyway, so this is really a constant. for (LabelOutput labelOutput : classifierOutput.getLabelOutputs()) { float dW = 0.0f; if (positiveLabels != null && positiveLabels.contains(labelOutput.getLabel())) { // state (y) should be positive even if its not dW = lRate * (1 - labelOutput.getConfidence()); } else if (negativeLabels != null && negativeLabels.contains(labelOutput.getLabel())) { // state (y) should be negative even if its not dW = lRate * (-1 - labelOutput.getConfidence()); } else if (Math.abs(labelOutput.getConfidence()) > unsupervisedConfidenceThreshold) { dW = lRate * (Math.signum(labelOutput.getConfidence()) - labelOutput.getConfidence()); } if (dW != 0.0f) { if (dW > lRate) { dW = lRate; } else if (dW < -lRate) { dW = -lRate; } updateWeights(spikes, labelOutput.getLabel(), dW); } } } private void updateWeights(List<long[]> spikes, int label, float dW) { for (int i = 0; i < spikes.size(); i++) { for (int j = 0; j < spikes.get(i).length; j++) { weightMap.get(spikes.get(i)[j]).put(label, getWeight(spikes.get(i)[j], label) + dW); } } } /** * gets the weight and creates a new random weight if it does not exist. * * @param spike * @param label * @return */ private float getWeight(long spike, int label) { if (!weightMap.contains(spike)) { TIntFloatHashMap z = new TIntFloatHashMap(); float w = 2f * STARTING_WEIGHT_MAGNITUDE * (random.nextFloat() - .5f); z.put(label, w); weightMap.put(spike, z); return w; } else { TIntFloatHashMap z = weightMap.get(spike); if (!z.contains(label)) { float w = 2f * STARTING_WEIGHT_MAGNITUDE * (random.nextFloat() - .5f); z.put(label, w); return w; } else { return z.get(label); } } } public long deserializeClassifier() { long startTime = System.nanoTime(); FileInputStream fileInputStream = null; ObjectInputStream objectInputStream = null; // load maps from file try { fileInputStream = new FileInputStream(classifierDBDir + File.separatorChar + LINK_SER_NAME); objectInputStream = new ObjectInputStream(fileInputStream); weightMap.readExternal(objectInputStream); objectInputStream.close(); fileInputStream.close(); fileInputStream = new FileInputStream(classifierDBDir + File.separatorChar + FORWARD_SER_NAME); objectInputStream = new ObjectInputStream(fileInputStream); labelForwardMap.readExternal(objectInputStream); objectInputStream.close(); fileInputStream.close(); fileInputStream = new FileInputStream(classifierDBDir + File.separatorChar + REVERSE_SER_NAME); objectInputStream = new ObjectInputStream(fileInputStream); labelReverseMap.readExternal(objectInputStream); objectInputStream.close(); fileInputStream.close(); } catch (IOException e) { try { if (fileInputStream != null) { fileInputStream.close(); } } catch (IOException ex) { e.printStackTrace(); } try { if (objectInputStream != null) { objectInputStream.close(); } } catch (IOException ex) { e.printStackTrace(); } throw new ClassifierException("Problem deserializing classifier maps with given classifierDBDir: " + classifierDBDir, e); } catch (ClassNotFoundException e) { try { if (fileInputStream != null) { fileInputStream.close(); } } catch (IOException ex) { e.printStackTrace(); } try { if (objectInputStream != null) { objectInputStream.close(); } } catch (IOException ex) { e.printStackTrace(); } throw new ClassifierException("Problem deserializing classifier maps with given classifierDBDir: " + classifierDBDir, e); } long writeTime = (System.nanoTime() - startTime) / 1000000000; return writeTime; } public long serializeClassifier() { if (classifierDBDir == null) { throw new ClassifierException("This classifier instant is not meant to be serializable."); } long startTime = System.nanoTime(); FileOutputStream fileOutputStream = null; ObjectOutputStream objectOutputStream = null; try { File file = new File(classifierDBDir); if (!file.exists()) { file.mkdirs(); } // Path dir = Paths.get(classifierDBDir); // boolean dirExists = Files.exists(dir, LinkOption.NOFOLLOW_LINKS); // // if (!dirExists) { // // Files.createDirectory(dir); // Files.createDirectories(dir); // } // fileOutputStream = new FileOutputStream(dir.resolve(LINK_SER_NAME).toString()); fileOutputStream = new FileOutputStream(new File(classifierDBDir + File.separatorChar + LINK_SER_NAME)); objectOutputStream = new ObjectOutputStream(fileOutputStream); weightMap.writeExternal(objectOutputStream); objectOutputStream.close(); fileOutputStream.close(); // fileOutputStream = new FileOutputStream(dir.resolve(FORWARD_SER_NAME).toString()); fileOutputStream = new FileOutputStream(new File(classifierDBDir + File.separatorChar + FORWARD_SER_NAME)); objectOutputStream = new ObjectOutputStream(fileOutputStream); labelForwardMap.writeExternal(objectOutputStream); objectOutputStream.close(); fileOutputStream.close(); // fileOutputStream = new FileOutputStream(dir.resolve(REVERSE_SER_NAME).toString()); fileOutputStream = new FileOutputStream(new File(classifierDBDir + File.separatorChar + REVERSE_SER_NAME)); objectOutputStream = new ObjectOutputStream(fileOutputStream); labelReverseMap.writeExternal(objectOutputStream); objectOutputStream.close(); fileOutputStream.close(); } catch (IOException e) { e.printStackTrace(); try { if (fileOutputStream != null) { fileOutputStream.close(); } } catch (IOException ex) { e.printStackTrace(); } try { if (objectOutputStream != null) { objectOutputStream.close(); } } catch (IOException ex) { e.printStackTrace(); } throw new ClassifierException("Problem serializing classifier"); } long writeTime = (System.nanoTime() - startTime) / 1000000000; return writeTime; } public float getLearningRate() { return learningRate; } public void setLearningRate(float learningRate) { this.learningRate = learningRate; } public void setUnsupervisedEnabled(boolean unsupervisedEnabled) { this.unsupervisedEnabled = unsupervisedEnabled; } public int getNumLinks() { LinkMapCountProcedure linkMapCountProcedure = new LinkMapCountProcedure(); weightMap.forEachValue(linkMapCountProcedure); return linkMapCountProcedure.getNumLinks(); } public void setUnsupervisedConfidenceThreshold(double unsupervisedConfidenceThreshold) { this.unsupervisedConfidenceThreshold = unsupervisedConfidenceThreshold; } public long getTotalClassificationTimeInNanoSeconds() { return totalClassificationTimeInNanoSeconds; } public int getNumSpikesProcessed() { return numSpikesProcessed; } public int getNumUpdates() { return numUpdates; } public int getNumLabelsProcessed() { return numLabelsProcessed; } public void deleteLabel(String label) { DeleteLabelProcedure deleteLabelProcedure = new DeleteLabelProcedure(labelForwardMap.get(label)); weightMap.forEachEntry(deleteLabelProcedure); } public List<LinkWeight> getSortedLinkWeights() { LinkWeightProcedure linkWeightProcedure = new LinkWeightProcedure(); weightMap.forEachEntry(linkWeightProcedure); return linkWeightProcedure.getSortedLinkWeights(); } public List<LinkWeight> getLinkWeightsForLabel(String label) { if (!labelForwardMap.contains(label)) { return null; } LinkWeightLabelProcedure linkWeightLabelProcedure = new LinkWeightLabelProcedure(labelForwardMap.get(label), label); weightMap.forEachEntry(linkWeightLabelProcedure); return linkWeightLabelProcedure.getLinkWeights(); } public void setLinkWeightLabelString(List<LinkWeight> linkWeights) { for (LinkWeight linkWeight : linkWeights) { linkWeight.setLabelString(labelReverseMap.get(linkWeight.getLabel())); } } public int getNumUniqueLabels() { return labelForwardMap.size(); } }
16,760
30.446529
173
java
AHaH
AHaH-master/ahah-classifier/src/main/java/com/mancrd/ahah/classifier/Feature.java
/** * Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]> * * M. Alexander Nugent Consulting Research License Agreement * Non-Commercial Academic Use Only * * This Software is proprietary. By installing, copying, or otherwise using this * Software, you agree to be bound by the terms of this license. If you do not agree, * do not install, copy, or use the Software. The Software is protected by copyright * and other intellectual property laws. * * You may use the Software for non-commercial academic purpose, subject to the following * restrictions. You may copy and use the Software for peer-review and methods verification * only. You may not create derivative works of the Software. You may not use or distribute * the Software or any derivative works in any form for commercial or non-commercial purposes. * * Violators will be prosecuted to the full extent of the law. * * All rights reserved. No warranty, explicit or implicit, provided. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.mancrd.ahah.classifier; /** * A DTO that encapsulates a feature and its weight * * @author alexnugent */ final class Feature implements Comparable<Feature> { private final String featureUUID; private final double weight; /** * Constructor * * @param featureUUID * @param weight */ Feature(String featureUUID, double weight) { this.featureUUID = featureUUID; this.weight = weight; } String getFeatureUUID() { return featureUUID; } double getWeight() { return weight; } @Override public int compareTo(Feature other) { if (other.getWeight() > getWeight()) { return 1; } else if (other.getWeight() < getWeight()) { return -1; } return 0; } @Override public String toString() { return featureUUID + "(" + weight + ")"; } }
2,319
27.292683
94
java
AHaH
AHaH-master/ahah-classifier/src/main/java/com/mancrd/ahah/classifier/ClassifierException.java
/** * Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]> * * M. Alexander Nugent Consulting Research License Agreement * Non-Commercial Academic Use Only * * This Software is proprietary. By installing, copying, or otherwise using this * Software, you agree to be bound by the terms of this license. If you do not agree, * do not install, copy, or use the Software. The Software is protected by copyright * and other intellectual property laws. * * You may use the Software for non-commercial academic purpose, subject to the following * restrictions. You may copy and use the Software for peer-review and methods verification * only. You may not create derivative works of the Software. You may not use or distribute * the Software or any derivative works in any form for commercial or non-commercial purposes. * * Violators will be prosecuted to the full extent of the law. * * All rights reserved. No warranty, explicit or implicit, provided. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.mancrd.ahah.classifier; /** * @author timmolter */ public class ClassifierException extends RuntimeException { public ClassifierException(String message, Throwable cause) { super(message, cause); } public ClassifierException(String message) { super(message); } }
1,772
36.723404
94
java
AHaH
AHaH-master/ahah-classifier/src/main/java/com/mancrd/ahah/classifier/LabelOutput.java
/** * Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]> * * M. Alexander Nugent Consulting Research License Agreement * Non-Commercial Academic Use Only * * This Software is proprietary. By installing, copying, or otherwise using this * Software, you agree to be bound by the terms of this license. If you do not agree, * do not install, copy, or use the Software. The Software is protected by copyright * and other intellectual property laws. * * You may use the Software for non-commercial academic purpose, subject to the following * restrictions. You may copy and use the Software for peer-review and methods verification * only. You may not create derivative works of the Software. You may not use or distribute * the Software or any derivative works in any form for commercial or non-commercial purposes. * * Violators will be prosecuted to the full extent of the law. * * All rights reserved. No warranty, explicit or implicit, provided. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.mancrd.ahah.classifier; /** * A simple POJO holding a classification label and the corresponding activation * * @author timmolter */ public class LabelOutput implements Comparable<LabelOutput> { /** label */ private final int label; private String labelstring; /** activation value */ private final float confidence; /** * Constructor * * @param label */ public LabelOutput(int label, float confidence) { this.label = label; this.confidence = confidence; } // GETTERS & SETTERS ///////////////////// public int getLabel() { return label; } public float getConfidence() { return confidence; } // OVERRIDES ///////////////////// @Override public int compareTo(LabelOutput other) { if (other.getConfidence() > getConfidence()) { return 1; } else if (other.getConfidence() < getConfidence()) { return -1; } return 0; } @Override public String toString() { return labelstring + "(" + getConfidence() + ")"; } public String getLabelstring() { return labelstring; } public void setLabelstring(String labelstring) { this.labelstring = labelstring; } }
2,675
26.030303
94
java
AHaH
AHaH-master/ahah-classifier/src/main/java/com/mancrd/ahah/classifier/LinkMapCountProcedure.java
/** * Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]> * * M. Alexander Nugent Consulting Research License Agreement * Non-Commercial Academic Use Only * * This Software is proprietary. By installing, copying, or otherwise using this * Software, you agree to be bound by the terms of this license. If you do not agree, * do not install, copy, or use the Software. The Software is protected by copyright * and other intellectual property laws. * * You may use the Software for non-commercial academic purpose, subject to the following * restrictions. You may copy and use the Software for peer-review and methods verification * only. You may not create derivative works of the Software. You may not use or distribute * the Software or any derivative works in any form for commercial or non-commercial purposes. * * Violators will be prosecuted to the full extent of the law. * * All rights reserved. No warranty, explicit or implicit, provided. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.mancrd.ahah.classifier; import gnu.trove.map.hash.TIntFloatHashMap; import gnu.trove.procedure.TObjectProcedure; /** * @author alexnugent */ public class LinkMapCountProcedure implements TObjectProcedure<TIntFloatHashMap> { private int numLinks = 0; public int getNumLinks() { return numLinks; } @Override public boolean execute(TIntFloatHashMap subMap) { numLinks += subMap.size(); return true; } }
1,919
34.555556
94
java
AHaH
AHaH-master/ahah-model/src/main/java/com/mancrd/ahah/model/circuit/AHaH21CircuitBuilder.java
/** * Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]> * * M. Alexander Nugent Consulting Research License Agreement * Non-Commercial Academic Use Only * * This Software is proprietary. By installing, copying, or otherwise using this * Software, you agree to be bound by the terms of this license. If you do not agree, * do not install, copy, or use the Software. The Software is protected by copyright * and other intellectual property laws. * * You may use the Software for non-commercial academic purpose, subject to the following * restrictions. You may copy and use the Software for peer-review and methods verification * only. You may not create derivative works of the Software. You may not use or distribute * the Software or any derivative works in any form for commercial or non-commercial purposes. * * Violators will be prosecuted to the full extent of the law. * * All rights reserved. No warranty, explicit or implicit, provided. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.mancrd.ahah.model.circuit; /** * Builder for AHaH21Circuit */ public class AHaH21CircuitBuilder { public enum MemristorType { AgChalc, WOx, AIST, GST } private int numInputs; private int numBiasInputs; private double Vdd = .5; // Drain voltage private double Vss = -Vdd; // Source voltage private double readPeriod = 1E-6; // seconds private double writePeriod = 1E-6; // seconds private MemristorType memristorType = MemristorType.AgChalc; // seconds /** * return fully built object * * @return a AHaH21Circuit */ public AHaH21Circuit build() { return new AHaH21Circuit(this); } public AHaH21CircuitBuilder numInputs(int numInputs) { this.numInputs = numInputs; return this; } public AHaH21CircuitBuilder numBiasInputs(int numBiasInputs) { this.numBiasInputs = numBiasInputs; return this; } public AHaH21CircuitBuilder Vdd(double Vdd) { this.Vdd = Vdd; return this; } public AHaH21CircuitBuilder Vss(double Vss) { this.Vss = Vss; return this; } public AHaH21CircuitBuilder readPeriod(double readPeriod) { this.readPeriod = readPeriod; return this; } public AHaH21CircuitBuilder writePeriod(double writePeriod) { this.writePeriod = writePeriod; return this; } public AHaH21CircuitBuilder memristorType(MemristorType memristorType) { this.memristorType = memristorType; return this; } public int getNumInputs() { return numInputs; } public int getNumBiasInputs() { return numBiasInputs; } public double getVss() { return Vss; } public double getVdd() { return Vdd; } public double getReadPeriod() { return readPeriod; } public double getWritePeriod() { return writePeriod; } public MemristorType getMemristorType() { return memristorType; } }
3,347
23.8
94
java
AHaH
AHaH-master/ahah-model/src/main/java/com/mancrd/ahah/model/circuit/AHaH21Circuit.java
/** * Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]> * * M. Alexander Nugent Consulting Research License Agreement * Non-Commercial Academic Use Only * * This Software is proprietary. By installing, copying, or otherwise using this * Software, you agree to be bound by the terms of this license. If you do not agree, * do not install, copy, or use the Software. The Software is protected by copyright * and other intellectual property laws. * * You may use the Software for non-commercial academic purpose, subject to the following * restrictions. You may copy and use the Software for peer-review and methods verification * only. You may not create derivative works of the Software. You may not use or distribute * the Software or any derivative works in any form for commercial or non-commercial purposes. * * Violators will be prosecuted to the full extent of the law. * * All rights reserved. No warranty, explicit or implicit, provided. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.mancrd.ahah.model.circuit; import java.util.Set; import com.mancrd.ahah.model.circuit.mss.AgChalcMemristor; import com.mancrd.ahah.model.circuit.mss.AgInSbTeMemristor; import com.mancrd.ahah.model.circuit.mss.GSTMemristor; import com.mancrd.ahah.model.circuit.mss.MSSMemristor; import com.mancrd.ahah.model.circuit.mss.PdWO3WMemristor; /** * This class represents the AHaH 2-1 Circuit Model */ public class AHaH21Circuit { private final int numBiasInputs; private final int numInputs; private final double Vdd; private final double Vss; private final double readPeriod; // seconds private final double writePeriod; // seconds private final MSSMemristor[] memristorsA; // memristor array for A side private final MSSMemristor[] memristorsB; // memristor array for B side /** runtime variables */ private double Vy = 0; // output voltage /** * Constructor * * @param aHaH21CircuitBuilder */ public AHaH21Circuit(AHaH21CircuitBuilder aHaH21CircuitBuilder) { this.numInputs = aHaH21CircuitBuilder.getNumInputs(); this.numBiasInputs = aHaH21CircuitBuilder.getNumBiasInputs(); this.Vdd = aHaH21CircuitBuilder.getVdd(); this.Vss = aHaH21CircuitBuilder.getVss(); this.readPeriod = aHaH21CircuitBuilder.getReadPeriod(); this.writePeriod = aHaH21CircuitBuilder.getWritePeriod(); memristorsA = new MSSMemristor[numInputs + numBiasInputs]; memristorsB = new MSSMemristor[numInputs + numBiasInputs]; for (int i = 0; i < numInputs + numBiasInputs; i++) { switch (aHaH21CircuitBuilder.getMemristorType()) { case AgChalc: memristorsA[i] = new AgChalcMemristor(.1 * Math.random()); memristorsB[i] = new AgChalcMemristor(.1 * Math.random()); break; case WOx: memristorsA[i] = new PdWO3WMemristor(.1 * Math.random()); memristorsB[i] = new PdWO3WMemristor(.1 * Math.random()); break; case AIST: memristorsA[i] = new AgInSbTeMemristor(.1 * Math.random()); memristorsB[i] = new AgInSbTeMemristor(.1 * Math.random()); break; case GST: memristorsA[i] = new GSTMemristor(.1 * Math.random()); memristorsB[i] = new GSTMemristor(.1 * Math.random()); break; default: break; } } } public double getSpikeInputWeightMagnitudeSum(Set<Integer> inputSpikes) { double s = 0; for (Integer idx : inputSpikes) { s += getWeightConjugate(idx); } for (int idx = numInputs; idx < numInputs + numBiasInputs; idx++) { s += getWeightConjugate(idx); } return s; } public double getSpikeInputWeightSum(Set<Integer> inputSpikes) { double s = 0; for (Integer idx : inputSpikes) { s += getWeight(idx); } for (int idx = numInputs; idx < numInputs + numBiasInputs; idx++) { s += getWeight(idx); } return s; } public double getWeightConjugate(int index) { return (Vdd * memristorsA[index].getConductance() - Vss * memristorsB[index].getConductance()); } public double getWeight(int index) { return (Vdd * memristorsA[index].getConductance() + Vss * memristorsB[index].getConductance()); } /** * provides unsupervised or supervised AntiHebbian (read) and Hebbian (write) learning. * * @param inputSpikes a list of input lines that are active. * @param superviseSignal +1 or -1 for supervised. 0 for unsupervised * @return */ public double update(Set<Integer> inputSpikes, int superviseSignal) { read(inputSpikes); write(inputSpikes, superviseSignal); return Vy; } private double read(Set<Integer> inputSpikes) { // Compute Output Voltage----> double conductanceA = 0.0; double conductanceB = 0.0; for (Integer idx : inputSpikes) { conductanceA += memristorsA[idx].getConductance(); conductanceB += memristorsB[idx].getConductance(); } for (int i = 0; i < numBiasInputs; i++) { conductanceA += memristorsA[numInputs + i].getConductance(); conductanceB += memristorsB[numInputs + i].getConductance(); } // get output voltage. KCL at Node y. Vy = (Vdd * conductanceA + Vss * conductanceB) / (conductanceA + conductanceB); // Update Memristors----> // input weights for (int i = 0; i < numInputs; i++) { if (inputSpikes.contains(i)) {// non-floating active inputs memristorsA[i].dG(Vdd - Vy, readPeriod); memristorsB[i].dG(Vy - Vss, readPeriod); } else {// floating inputs memristorsA[i].dG(0, readPeriod); memristorsB[i].dG(0, readPeriod); } } // bias weights. polarity is reversed for (int i = 0; i < numBiasInputs; i++) { memristorsA[numInputs + i].dG(-(Vdd - Vy), readPeriod); memristorsB[numInputs + i].dG(-(Vy - Vss), readPeriod); } return Vy; } private void write(Set<Integer> inputSpikes, int supervisedSignal) { if (supervisedSignal == 1 || (Vy > 0 && supervisedSignal == 0)) { // evaluation was positive. Decay negative losers. Hebbian. // B side inputs weights for (int i = 0; i < numInputs; i++) { if (inputSpikes.contains(i)) { // non-floating active inputs. memristorsB[i].dG(-(Vdd - Vss), writePeriod); } else {// floating inputs memristorsB[i].dG(0, writePeriod); } // A side input weights. Rewarded by not being decayed. memristorsA[i].dG(0, writePeriod); // all floating } // bias weights, A and B side. for (int i = 0; i < numBiasInputs; i++) { memristorsB[numInputs + i].dG(Vdd - Vss, writePeriod); // write. polarity is reversed from input weights memristorsA[numInputs + i].dG(0, writePeriod); // floating } } else if (supervisedSignal == -1 || (Vy < 0 && supervisedSignal == 0)) { // evaluation was negative. Decay positive losers. Hebbian // A side input weights for (int i = 0; i < numInputs; i++) { if (inputSpikes.contains(i)) { // non-floating active inputs. memristorsA[i].dG(-(Vdd - Vss), writePeriod); } else {// floating inputs memristorsA[i].dG(0, writePeriod); } } // B side input weights. Rewarded by not being decayed for (int i = 0; i < numInputs; i++) { memristorsB[i].dG(0, writePeriod);// all floating } // Bias weights, A and B sides for (int i = 0; i < numBiasInputs; i++) { memristorsA[numInputs + i].dG(Vdd - Vss, writePeriod); // write. Polarity is reversed from input weights memristorsB[numInputs + i].dG(0, writePeriod); // floating } } } public double getVdd() { return Vdd; } public double getVss() { return Vss; } public double getReadPeriod() { return readPeriod; } public double getWritePeriod() { return writePeriod; } public MSSMemristor[] getMemristorsA() { return memristorsA; } public MSSMemristor[] getMemristorsB() { return memristorsB; } }
8,539
29.830325
112
java
AHaH
AHaH-master/ahah-model/src/main/java/com/mancrd/ahah/model/circuit/driver/Triangle.java
/** * Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]> * * M. Alexander Nugent Consulting Research License Agreement * Non-Commercial Academic Use Only * * This Software is proprietary. By installing, copying, or otherwise using this * Software, you agree to be bound by the terms of this license. If you do not agree, * do not install, copy, or use the Software. The Software is protected by copyright * and other intellectual property laws. * * You may use the Software for non-commercial academic purpose, subject to the following * restrictions. You may copy and use the Software for peer-review and methods verification * only. You may not create derivative works of the Software. You may not use or distribute * the Software or any derivative works in any form for commercial or non-commercial purposes. * * Violators will be prosecuted to the full extent of the law. * * All rights reserved. No warranty, explicit or implicit, provided. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.mancrd.ahah.model.circuit.driver; /** * @author timmolter */ public class Triangle extends Driver { /** * Constructor * * @param name * @param dcOffset * @param phase * @param amplitude * @param frequency */ public Triangle(String name, double dcOffset, double phase, double amplitude, double frequency) { super(name, dcOffset, phase, amplitude, frequency); } @Override public double getSignal(double time) { double T = 1 / frequency; double remainderTime = (time + phase) % T; // up phase if (0 <= (remainderTime) && (remainderTime) * T < .25 / frequency * T) { return 4 * frequency * amplitude * (remainderTime) + dcOffset; } // up phase else if (.75 / frequency * T <= (remainderTime) * T && (remainderTime) * T < 1.0 / frequency * T) { return 4 * frequency * amplitude * (remainderTime) - 4 * amplitude + dcOffset; } // down phase else { return -4 * frequency * amplitude * (remainderTime) + 2 * amplitude + dcOffset; } } }
2,527
33.630137
103
java
AHaH
AHaH-master/ahah-model/src/main/java/com/mancrd/ahah/model/circuit/driver/Driver.java
/** * Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]> * * M. Alexander Nugent Consulting Research License Agreement * Non-Commercial Academic Use Only * * This Software is proprietary. By installing, copying, or otherwise using this * Software, you agree to be bound by the terms of this license. If you do not agree, * do not install, copy, or use the Software. The Software is protected by copyright * and other intellectual property laws. * * You may use the Software for non-commercial academic purpose, subject to the following * restrictions. You may copy and use the Software for peer-review and methods verification * only. You may not create derivative works of the Software. You may not use or distribute * the Software or any derivative works in any form for commercial or non-commercial purposes. * * Violators will be prosecuted to the full extent of the law. * * All rights reserved. No warranty, explicit or implicit, provided. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.mancrd.ahah.model.circuit.driver; /** * @author timmolter */ public abstract class Driver { protected final String id; protected final double dcOffset; protected final double phase; protected final double amplitude; protected final double frequency; /** * Constructor * * @param id * @param dcOffset * @param phase * @param amplitude * @param frequency */ public Driver(String id, double dcOffset, double phase, double amplitude, double frequency) { this.id = id; this.dcOffset = dcOffset; this.phase = phase; this.amplitude = amplitude; this.frequency = frequency; } public String getId() { return id; } public double getDcOffset() { return dcOffset; } public double getPhase() { return phase; } public double getAmplitude() { return amplitude; } public double getFrequency() { return frequency; } public abstract double getSignal(double time); }
2,454
26.897727
95
java