id
int32
0
165k
repo
stringlengths
7
58
path
stringlengths
12
218
func_name
stringlengths
3
140
original_string
stringlengths
73
34.1k
language
stringclasses
1 value
code
stringlengths
73
34.1k
code_tokens
list
docstring
stringlengths
3
16k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
105
339
17,100
Swagger2Markup/swagger2markup
src/main/java/io/github/swagger2markup/internal/utils/ExamplesUtil.java
ExamplesUtil.exampleMapForProperties
private static Map<String, Object> exampleMapForProperties(Map<String, Property> properties, Map<String, Model> definitions, DocumentResolver definitionDocumentResolver, MarkupDocBuilder markupDocBuilder, Map<String, Integer> refStack) { Map<String, Object> exampleMap = new LinkedHashMap<>(); if (properties != null) { for (Map.Entry<String, Property> property : properties.entrySet()) { Object exampleObject = property.getValue().getExample(); if (exampleObject == null) { if (property.getValue() instanceof RefProperty) { exampleObject = generateExampleForRefModel(true, ((RefProperty) property.getValue()).getSimpleRef(), definitions, definitionDocumentResolver, markupDocBuilder, refStack); } else if (property.getValue() instanceof ArrayProperty) { exampleObject = generateExampleForArrayProperty((ArrayProperty) property.getValue(), definitions, definitionDocumentResolver, markupDocBuilder, refStack); } else if (property.getValue() instanceof MapProperty) { exampleObject = generateExampleForMapProperty((MapProperty) property.getValue(), markupDocBuilder); } if (exampleObject == null) { Property valueProperty = property.getValue(); exampleObject = PropertyAdapter.generateExample(valueProperty, markupDocBuilder); } } exampleMap.put(property.getKey(), exampleObject); } } return exampleMap; }
java
private static Map<String, Object> exampleMapForProperties(Map<String, Property> properties, Map<String, Model> definitions, DocumentResolver definitionDocumentResolver, MarkupDocBuilder markupDocBuilder, Map<String, Integer> refStack) { Map<String, Object> exampleMap = new LinkedHashMap<>(); if (properties != null) { for (Map.Entry<String, Property> property : properties.entrySet()) { Object exampleObject = property.getValue().getExample(); if (exampleObject == null) { if (property.getValue() instanceof RefProperty) { exampleObject = generateExampleForRefModel(true, ((RefProperty) property.getValue()).getSimpleRef(), definitions, definitionDocumentResolver, markupDocBuilder, refStack); } else if (property.getValue() instanceof ArrayProperty) { exampleObject = generateExampleForArrayProperty((ArrayProperty) property.getValue(), definitions, definitionDocumentResolver, markupDocBuilder, refStack); } else if (property.getValue() instanceof MapProperty) { exampleObject = generateExampleForMapProperty((MapProperty) property.getValue(), markupDocBuilder); } if (exampleObject == null) { Property valueProperty = property.getValue(); exampleObject = PropertyAdapter.generateExample(valueProperty, markupDocBuilder); } } exampleMap.put(property.getKey(), exampleObject); } } return exampleMap; }
[ "private", "static", "Map", "<", "String", ",", "Object", ">", "exampleMapForProperties", "(", "Map", "<", "String", ",", "Property", ">", "properties", ",", "Map", "<", "String", ",", "Model", ">", "definitions", ",", "DocumentResolver", "definitionDocumentResolver", ",", "MarkupDocBuilder", "markupDocBuilder", ",", "Map", "<", "String", ",", "Integer", ">", "refStack", ")", "{", "Map", "<", "String", ",", "Object", ">", "exampleMap", "=", "new", "LinkedHashMap", "<>", "(", ")", ";", "if", "(", "properties", "!=", "null", ")", "{", "for", "(", "Map", ".", "Entry", "<", "String", ",", "Property", ">", "property", ":", "properties", ".", "entrySet", "(", ")", ")", "{", "Object", "exampleObject", "=", "property", ".", "getValue", "(", ")", ".", "getExample", "(", ")", ";", "if", "(", "exampleObject", "==", "null", ")", "{", "if", "(", "property", ".", "getValue", "(", ")", "instanceof", "RefProperty", ")", "{", "exampleObject", "=", "generateExampleForRefModel", "(", "true", ",", "(", "(", "RefProperty", ")", "property", ".", "getValue", "(", ")", ")", ".", "getSimpleRef", "(", ")", ",", "definitions", ",", "definitionDocumentResolver", ",", "markupDocBuilder", ",", "refStack", ")", ";", "}", "else", "if", "(", "property", ".", "getValue", "(", ")", "instanceof", "ArrayProperty", ")", "{", "exampleObject", "=", "generateExampleForArrayProperty", "(", "(", "ArrayProperty", ")", "property", ".", "getValue", "(", ")", ",", "definitions", ",", "definitionDocumentResolver", ",", "markupDocBuilder", ",", "refStack", ")", ";", "}", "else", "if", "(", "property", ".", "getValue", "(", ")", "instanceof", "MapProperty", ")", "{", "exampleObject", "=", "generateExampleForMapProperty", "(", "(", "MapProperty", ")", "property", ".", "getValue", "(", ")", ",", "markupDocBuilder", ")", ";", "}", "if", "(", "exampleObject", "==", "null", ")", "{", "Property", "valueProperty", "=", "property", ".", "getValue", "(", ")", ";", "exampleObject", "=", "PropertyAdapter", ".", "generateExample", "(", "valueProperty", ",", "markupDocBuilder", ")", ";", "}", "}", "exampleMap", ".", "put", "(", "property", ".", "getKey", "(", ")", ",", "exampleObject", ")", ";", "}", "}", "return", "exampleMap", ";", "}" ]
Generates a map of examples from a map of properties. If defined examples are found, those are used. Otherwise, examples are generated from the type. @param properties the map of properties @param definitions the map of definitions @param markupDocBuilder the markup builder @param refStack map to detect cyclic references @return a Map of examples
[ "Generates", "a", "map", "of", "examples", "from", "a", "map", "of", "properties", ".", "If", "defined", "examples", "are", "found", "those", "are", "used", ".", "Otherwise", "examples", "are", "generated", "from", "the", "type", "." ]
da83465f19a2f8a0f1fba873b5762bca8587896b
https://github.com/Swagger2Markup/swagger2markup/blob/da83465f19a2f8a0f1fba873b5762bca8587896b/src/main/java/io/github/swagger2markup/internal/utils/ExamplesUtil.java#L278-L300
17,101
Swagger2Markup/swagger2markup
src/main/java/io/github/swagger2markup/internal/utils/ExamplesUtil.java
ExamplesUtil.generateExampleForArrayProperty
private static Object[] generateExampleForArrayProperty(ArrayProperty value, Map<String, Model> definitions, DocumentResolver definitionDocumentResolver, MarkupDocBuilder markupDocBuilder, Map<String, Integer> refStack) { Property property = value.getItems(); return getExample(property, definitions, definitionDocumentResolver, markupDocBuilder, refStack); }
java
private static Object[] generateExampleForArrayProperty(ArrayProperty value, Map<String, Model> definitions, DocumentResolver definitionDocumentResolver, MarkupDocBuilder markupDocBuilder, Map<String, Integer> refStack) { Property property = value.getItems(); return getExample(property, definitions, definitionDocumentResolver, markupDocBuilder, refStack); }
[ "private", "static", "Object", "[", "]", "generateExampleForArrayProperty", "(", "ArrayProperty", "value", ",", "Map", "<", "String", ",", "Model", ">", "definitions", ",", "DocumentResolver", "definitionDocumentResolver", ",", "MarkupDocBuilder", "markupDocBuilder", ",", "Map", "<", "String", ",", "Integer", ">", "refStack", ")", "{", "Property", "property", "=", "value", ".", "getItems", "(", ")", ";", "return", "getExample", "(", "property", ",", "definitions", ",", "definitionDocumentResolver", ",", "markupDocBuilder", ",", "refStack", ")", ";", "}" ]
Generates examples from an ArrayProperty @param value ArrayProperty @param definitions map of definitions @param markupDocBuilder the markup builder @return array of Object
[ "Generates", "examples", "from", "an", "ArrayProperty" ]
da83465f19a2f8a0f1fba873b5762bca8587896b
https://github.com/Swagger2Markup/swagger2markup/blob/da83465f19a2f8a0f1fba873b5762bca8587896b/src/main/java/io/github/swagger2markup/internal/utils/ExamplesUtil.java#L334-L337
17,102
Swagger2Markup/swagger2markup
src/main/java/io/github/swagger2markup/internal/utils/ExamplesUtil.java
ExamplesUtil.getExample
private static Object[] getExample( Property property, Map<String, Model> definitions, DocumentResolver definitionDocumentResolver, MarkupDocBuilder markupDocBuilder, Map<String, Integer> refStack) { if (property.getExample() != null) { return new Object[]{property.getExample()}; } else if (property instanceof ArrayProperty) { return new Object[]{generateExampleForArrayProperty((ArrayProperty) property, definitions, definitionDocumentResolver, markupDocBuilder, refStack)}; } else if (property instanceof RefProperty) { return new Object[]{generateExampleForRefModel(true, ((RefProperty) property).getSimpleRef(), definitions, definitionDocumentResolver, markupDocBuilder, refStack)}; } else { return new Object[]{PropertyAdapter.generateExample(property, markupDocBuilder)}; } }
java
private static Object[] getExample( Property property, Map<String, Model> definitions, DocumentResolver definitionDocumentResolver, MarkupDocBuilder markupDocBuilder, Map<String, Integer> refStack) { if (property.getExample() != null) { return new Object[]{property.getExample()}; } else if (property instanceof ArrayProperty) { return new Object[]{generateExampleForArrayProperty((ArrayProperty) property, definitions, definitionDocumentResolver, markupDocBuilder, refStack)}; } else if (property instanceof RefProperty) { return new Object[]{generateExampleForRefModel(true, ((RefProperty) property).getSimpleRef(), definitions, definitionDocumentResolver, markupDocBuilder, refStack)}; } else { return new Object[]{PropertyAdapter.generateExample(property, markupDocBuilder)}; } }
[ "private", "static", "Object", "[", "]", "getExample", "(", "Property", "property", ",", "Map", "<", "String", ",", "Model", ">", "definitions", ",", "DocumentResolver", "definitionDocumentResolver", ",", "MarkupDocBuilder", "markupDocBuilder", ",", "Map", "<", "String", ",", "Integer", ">", "refStack", ")", "{", "if", "(", "property", ".", "getExample", "(", ")", "!=", "null", ")", "{", "return", "new", "Object", "[", "]", "{", "property", ".", "getExample", "(", ")", "}", ";", "}", "else", "if", "(", "property", "instanceof", "ArrayProperty", ")", "{", "return", "new", "Object", "[", "]", "{", "generateExampleForArrayProperty", "(", "(", "ArrayProperty", ")", "property", ",", "definitions", ",", "definitionDocumentResolver", ",", "markupDocBuilder", ",", "refStack", ")", "}", ";", "}", "else", "if", "(", "property", "instanceof", "RefProperty", ")", "{", "return", "new", "Object", "[", "]", "{", "generateExampleForRefModel", "(", "true", ",", "(", "(", "RefProperty", ")", "property", ")", ".", "getSimpleRef", "(", ")", ",", "definitions", ",", "definitionDocumentResolver", ",", "markupDocBuilder", ",", "refStack", ")", "}", ";", "}", "else", "{", "return", "new", "Object", "[", "]", "{", "PropertyAdapter", ".", "generateExample", "(", "property", ",", "markupDocBuilder", ")", "}", ";", "}", "}" ]
Get example from a property @param property Property @param definitions map of definitions @param definitionDocumentResolver DocumentResolver @param markupDocBuilder the markup builder @param refStack reference stack @return array of Object
[ "Get", "example", "from", "a", "property" ]
da83465f19a2f8a0f1fba873b5762bca8587896b
https://github.com/Swagger2Markup/swagger2markup/blob/da83465f19a2f8a0f1fba873b5762bca8587896b/src/main/java/io/github/swagger2markup/internal/utils/ExamplesUtil.java#L349-L364
17,103
Swagger2Markup/swagger2markup
src/main/java/io/github/swagger2markup/internal/utils/ExamplesUtil.java
ExamplesUtil.generateStringExample
public static String generateStringExample(String format, List<String> enumValues) { if (enumValues == null || enumValues.isEmpty()) { if (format == null) { return "string"; } else { switch (format) { case "byte": return "Ynl0ZQ=="; case "date": return "1970-01-01"; case "date-time": return "1970-01-01T00:00:00Z"; case "email": return "email@example.com"; case "password": return "secret"; case "uuid": return "f81d4fae-7dec-11d0-a765-00a0c91e6bf6"; default: return "string"; } } } else { return enumValues.get(0); } }
java
public static String generateStringExample(String format, List<String> enumValues) { if (enumValues == null || enumValues.isEmpty()) { if (format == null) { return "string"; } else { switch (format) { case "byte": return "Ynl0ZQ=="; case "date": return "1970-01-01"; case "date-time": return "1970-01-01T00:00:00Z"; case "email": return "email@example.com"; case "password": return "secret"; case "uuid": return "f81d4fae-7dec-11d0-a765-00a0c91e6bf6"; default: return "string"; } } } else { return enumValues.get(0); } }
[ "public", "static", "String", "generateStringExample", "(", "String", "format", ",", "List", "<", "String", ">", "enumValues", ")", "{", "if", "(", "enumValues", "==", "null", "||", "enumValues", ".", "isEmpty", "(", ")", ")", "{", "if", "(", "format", "==", "null", ")", "{", "return", "\"string\"", ";", "}", "else", "{", "switch", "(", "format", ")", "{", "case", "\"byte\"", ":", "return", "\"Ynl0ZQ==\"", ";", "case", "\"date\"", ":", "return", "\"1970-01-01\"", ";", "case", "\"date-time\"", ":", "return", "\"1970-01-01T00:00:00Z\"", ";", "case", "\"email\"", ":", "return", "\"email@example.com\"", ";", "case", "\"password\"", ":", "return", "\"secret\"", ";", "case", "\"uuid\"", ":", "return", "\"f81d4fae-7dec-11d0-a765-00a0c91e6bf6\"", ";", "default", ":", "return", "\"string\"", ";", "}", "}", "}", "else", "{", "return", "enumValues", ".", "get", "(", "0", ")", ";", "}", "}" ]
Generates examples for string properties or parameters with given format @param format the format of the string property @param enumValues the enum values @return example
[ "Generates", "examples", "for", "string", "properties", "or", "parameters", "with", "given", "format" ]
da83465f19a2f8a0f1fba873b5762bca8587896b
https://github.com/Swagger2Markup/swagger2markup/blob/da83465f19a2f8a0f1fba873b5762bca8587896b/src/main/java/io/github/swagger2markup/internal/utils/ExamplesUtil.java#L373-L398
17,104
Swagger2Markup/swagger2markup
src/main/java/io/github/swagger2markup/internal/utils/ExamplesUtil.java
ExamplesUtil.generateIntegerExample
public static Integer generateIntegerExample(List<Integer> enumValues) { if (enumValues == null || enumValues.isEmpty()) { return 0; } else { return enumValues.get(0); } }
java
public static Integer generateIntegerExample(List<Integer> enumValues) { if (enumValues == null || enumValues.isEmpty()) { return 0; } else { return enumValues.get(0); } }
[ "public", "static", "Integer", "generateIntegerExample", "(", "List", "<", "Integer", ">", "enumValues", ")", "{", "if", "(", "enumValues", "==", "null", "||", "enumValues", ".", "isEmpty", "(", ")", ")", "{", "return", "0", ";", "}", "else", "{", "return", "enumValues", ".", "get", "(", "0", ")", ";", "}", "}" ]
Generates examples for integer properties - if there are enums, it uses first enum value, returns 0 otherwise. @param enumValues the enum values @return example
[ "Generates", "examples", "for", "integer", "properties", "-", "if", "there", "are", "enums", "it", "uses", "first", "enum", "value", "returns", "0", "otherwise", "." ]
da83465f19a2f8a0f1fba873b5762bca8587896b
https://github.com/Swagger2Markup/swagger2markup/blob/da83465f19a2f8a0f1fba873b5762bca8587896b/src/main/java/io/github/swagger2markup/internal/utils/ExamplesUtil.java#L406-L412
17,105
Swagger2Markup/swagger2markup
src/main/java/io/github/swagger2markup/internal/utils/PathUtils.java
PathUtils.getOperationMap
private static Map<HttpMethod, Operation> getOperationMap(Path path) { Map<HttpMethod, Operation> result = new LinkedHashMap<>(); if (path.getGet() != null) { result.put(HttpMethod.GET, path.getGet()); } if (path.getPut() != null) { result.put(HttpMethod.PUT, path.getPut()); } if (path.getPost() != null) { result.put(HttpMethod.POST, path.getPost()); } if (path.getDelete() != null) { result.put(HttpMethod.DELETE, path.getDelete()); } if (path.getPatch() != null) { result.put(HttpMethod.PATCH, path.getPatch()); } if (path.getHead() != null) { result.put(HttpMethod.HEAD, path.getHead()); } if (path.getOptions() != null) { result.put(HttpMethod.OPTIONS, path.getOptions()); } return result; }
java
private static Map<HttpMethod, Operation> getOperationMap(Path path) { Map<HttpMethod, Operation> result = new LinkedHashMap<>(); if (path.getGet() != null) { result.put(HttpMethod.GET, path.getGet()); } if (path.getPut() != null) { result.put(HttpMethod.PUT, path.getPut()); } if (path.getPost() != null) { result.put(HttpMethod.POST, path.getPost()); } if (path.getDelete() != null) { result.put(HttpMethod.DELETE, path.getDelete()); } if (path.getPatch() != null) { result.put(HttpMethod.PATCH, path.getPatch()); } if (path.getHead() != null) { result.put(HttpMethod.HEAD, path.getHead()); } if (path.getOptions() != null) { result.put(HttpMethod.OPTIONS, path.getOptions()); } return result; }
[ "private", "static", "Map", "<", "HttpMethod", ",", "Operation", ">", "getOperationMap", "(", "Path", "path", ")", "{", "Map", "<", "HttpMethod", ",", "Operation", ">", "result", "=", "new", "LinkedHashMap", "<>", "(", ")", ";", "if", "(", "path", ".", "getGet", "(", ")", "!=", "null", ")", "{", "result", ".", "put", "(", "HttpMethod", ".", "GET", ",", "path", ".", "getGet", "(", ")", ")", ";", "}", "if", "(", "path", ".", "getPut", "(", ")", "!=", "null", ")", "{", "result", ".", "put", "(", "HttpMethod", ".", "PUT", ",", "path", ".", "getPut", "(", ")", ")", ";", "}", "if", "(", "path", ".", "getPost", "(", ")", "!=", "null", ")", "{", "result", ".", "put", "(", "HttpMethod", ".", "POST", ",", "path", ".", "getPost", "(", ")", ")", ";", "}", "if", "(", "path", ".", "getDelete", "(", ")", "!=", "null", ")", "{", "result", ".", "put", "(", "HttpMethod", ".", "DELETE", ",", "path", ".", "getDelete", "(", ")", ")", ";", "}", "if", "(", "path", ".", "getPatch", "(", ")", "!=", "null", ")", "{", "result", ".", "put", "(", "HttpMethod", ".", "PATCH", ",", "path", ".", "getPatch", "(", ")", ")", ";", "}", "if", "(", "path", ".", "getHead", "(", ")", "!=", "null", ")", "{", "result", ".", "put", "(", "HttpMethod", ".", "HEAD", ",", "path", ".", "getHead", "(", ")", ")", ";", "}", "if", "(", "path", ".", "getOptions", "(", ")", "!=", "null", ")", "{", "result", ".", "put", "(", "HttpMethod", ".", "OPTIONS", ",", "path", ".", "getOptions", "(", ")", ")", ";", "}", "return", "result", ";", "}" ]
Returns the operations of a path as a map which preserves the insertion order. @param path the path @return the operations of a path as a map
[ "Returns", "the", "operations", "of", "a", "path", "as", "a", "map", "which", "preserves", "the", "insertion", "order", "." ]
da83465f19a2f8a0f1fba873b5762bca8587896b
https://github.com/Swagger2Markup/swagger2markup/blob/da83465f19a2f8a0f1fba873b5762bca8587896b/src/main/java/io/github/swagger2markup/internal/utils/PathUtils.java#L33-L59
17,106
Swagger2Markup/swagger2markup
src/main/java/io/github/swagger2markup/internal/utils/PathUtils.java
PathUtils.toPathOperationsList
public static List<PathOperation> toPathOperationsList(Map<String, Path> paths, String host, String basePath, Comparator<PathOperation> comparator) { List<PathOperation> pathOperations = new ArrayList<>(); paths.forEach((relativePath, path) -> pathOperations.addAll(toPathOperationsList(host + basePath + relativePath, path))); if (comparator != null) { pathOperations.sort(comparator); } return pathOperations; }
java
public static List<PathOperation> toPathOperationsList(Map<String, Path> paths, String host, String basePath, Comparator<PathOperation> comparator) { List<PathOperation> pathOperations = new ArrayList<>(); paths.forEach((relativePath, path) -> pathOperations.addAll(toPathOperationsList(host + basePath + relativePath, path))); if (comparator != null) { pathOperations.sort(comparator); } return pathOperations; }
[ "public", "static", "List", "<", "PathOperation", ">", "toPathOperationsList", "(", "Map", "<", "String", ",", "Path", ">", "paths", ",", "String", "host", ",", "String", "basePath", ",", "Comparator", "<", "PathOperation", ">", "comparator", ")", "{", "List", "<", "PathOperation", ">", "pathOperations", "=", "new", "ArrayList", "<>", "(", ")", ";", "paths", ".", "forEach", "(", "(", "relativePath", ",", "path", ")", "->", "pathOperations", ".", "addAll", "(", "toPathOperationsList", "(", "host", "+", "basePath", "+", "relativePath", ",", "path", ")", ")", ")", ";", "if", "(", "comparator", "!=", "null", ")", "{", "pathOperations", ".", "sort", "(", "comparator", ")", ";", "}", "return", "pathOperations", ";", "}" ]
Converts the Swagger paths into a list of PathOperations. @param paths the Swagger paths @param host the host of all paths @param basePath the basePath of all paths @param comparator the comparator to use. @return the path operations
[ "Converts", "the", "Swagger", "paths", "into", "a", "list", "of", "PathOperations", "." ]
da83465f19a2f8a0f1fba873b5762bca8587896b
https://github.com/Swagger2Markup/swagger2markup/blob/da83465f19a2f8a0f1fba873b5762bca8587896b/src/main/java/io/github/swagger2markup/internal/utils/PathUtils.java#L70-L82
17,107
Swagger2Markup/swagger2markup
src/main/java/io/github/swagger2markup/internal/utils/PathUtils.java
PathUtils.toPathOperationsList
public static List<PathOperation> toPathOperationsList(String path, Path pathModel) { List<PathOperation> pathOperations = new ArrayList<>(); getOperationMap(pathModel).forEach((httpMethod, operation) -> pathOperations.add(new PathOperation(httpMethod, path, operation))); return pathOperations; }
java
public static List<PathOperation> toPathOperationsList(String path, Path pathModel) { List<PathOperation> pathOperations = new ArrayList<>(); getOperationMap(pathModel).forEach((httpMethod, operation) -> pathOperations.add(new PathOperation(httpMethod, path, operation))); return pathOperations; }
[ "public", "static", "List", "<", "PathOperation", ">", "toPathOperationsList", "(", "String", "path", ",", "Path", "pathModel", ")", "{", "List", "<", "PathOperation", ">", "pathOperations", "=", "new", "ArrayList", "<>", "(", ")", ";", "getOperationMap", "(", "pathModel", ")", ".", "forEach", "(", "(", "httpMethod", ",", "operation", ")", "->", "pathOperations", ".", "add", "(", "new", "PathOperation", "(", "httpMethod", ",", "path", ",", "operation", ")", ")", ")", ";", "return", "pathOperations", ";", "}" ]
Converts a Swagger path into a PathOperation. @param path the path @param pathModel the Swagger Path model @return the path operations
[ "Converts", "a", "Swagger", "path", "into", "a", "PathOperation", "." ]
da83465f19a2f8a0f1fba873b5762bca8587896b
https://github.com/Swagger2Markup/swagger2markup/blob/da83465f19a2f8a0f1fba873b5762bca8587896b/src/main/java/io/github/swagger2markup/internal/utils/PathUtils.java#L91-L96
17,108
Swagger2Markup/swagger2markup
src/main/java/io/github/swagger2markup/model/PathOperation.java
PathOperation.getTitle
public String getTitle() { String operationName = operation.getSummary(); if (isBlank(operationName)) { operationName = getMethod().toString() + " " + getPath(); } return operationName; }
java
public String getTitle() { String operationName = operation.getSummary(); if (isBlank(operationName)) { operationName = getMethod().toString() + " " + getPath(); } return operationName; }
[ "public", "String", "getTitle", "(", ")", "{", "String", "operationName", "=", "operation", ".", "getSummary", "(", ")", ";", "if", "(", "isBlank", "(", "operationName", ")", ")", "{", "operationName", "=", "getMethod", "(", ")", ".", "toString", "(", ")", "+", "\" \"", "+", "getPath", "(", ")", ";", "}", "return", "operationName", ";", "}" ]
Returns the display title for an operation @return the operation title
[ "Returns", "the", "display", "title", "for", "an", "operation" ]
da83465f19a2f8a0f1fba873b5762bca8587896b
https://github.com/Swagger2Markup/swagger2markup/blob/da83465f19a2f8a0f1fba873b5762bca8587896b/src/main/java/io/github/swagger2markup/model/PathOperation.java#L49-L55
17,109
Swagger2Markup/swagger2markup
src/main/java/io/github/swagger2markup/internal/document/OverviewDocument.java
OverviewDocument.apply
@Override public MarkupDocBuilder apply(MarkupDocBuilder markupDocBuilder, OverviewDocument.Parameters params) { Swagger swagger = params.swagger; Info info = swagger.getInfo(); buildDocumentTitle(markupDocBuilder, info.getTitle()); applyOverviewDocumentExtension(new Context(Position.DOCUMENT_BEFORE, markupDocBuilder)); buildOverviewTitle(markupDocBuilder, labels.getLabel(Labels.OVERVIEW)); applyOverviewDocumentExtension(new Context(Position.DOCUMENT_BEGIN, markupDocBuilder)); buildDescriptionParagraph(markupDocBuilder, info.getDescription()); buildVersionInfoSection(markupDocBuilder, info); buildContactInfoSection(markupDocBuilder, info.getContact()); buildLicenseInfoSection(markupDocBuilder, info); buildUriSchemeSection(markupDocBuilder, swagger); buildTagsSection(markupDocBuilder, swagger.getTags()); buildConsumesSection(markupDocBuilder, swagger.getConsumes()); buildProducesSection(markupDocBuilder, swagger.getProduces()); buildExternalDocsSection(markupDocBuilder, swagger.getExternalDocs()); applyOverviewDocumentExtension(new Context(Position.DOCUMENT_END, markupDocBuilder)); applyOverviewDocumentExtension(new Context(Position.DOCUMENT_AFTER, markupDocBuilder)); return markupDocBuilder; }
java
@Override public MarkupDocBuilder apply(MarkupDocBuilder markupDocBuilder, OverviewDocument.Parameters params) { Swagger swagger = params.swagger; Info info = swagger.getInfo(); buildDocumentTitle(markupDocBuilder, info.getTitle()); applyOverviewDocumentExtension(new Context(Position.DOCUMENT_BEFORE, markupDocBuilder)); buildOverviewTitle(markupDocBuilder, labels.getLabel(Labels.OVERVIEW)); applyOverviewDocumentExtension(new Context(Position.DOCUMENT_BEGIN, markupDocBuilder)); buildDescriptionParagraph(markupDocBuilder, info.getDescription()); buildVersionInfoSection(markupDocBuilder, info); buildContactInfoSection(markupDocBuilder, info.getContact()); buildLicenseInfoSection(markupDocBuilder, info); buildUriSchemeSection(markupDocBuilder, swagger); buildTagsSection(markupDocBuilder, swagger.getTags()); buildConsumesSection(markupDocBuilder, swagger.getConsumes()); buildProducesSection(markupDocBuilder, swagger.getProduces()); buildExternalDocsSection(markupDocBuilder, swagger.getExternalDocs()); applyOverviewDocumentExtension(new Context(Position.DOCUMENT_END, markupDocBuilder)); applyOverviewDocumentExtension(new Context(Position.DOCUMENT_AFTER, markupDocBuilder)); return markupDocBuilder; }
[ "@", "Override", "public", "MarkupDocBuilder", "apply", "(", "MarkupDocBuilder", "markupDocBuilder", ",", "OverviewDocument", ".", "Parameters", "params", ")", "{", "Swagger", "swagger", "=", "params", ".", "swagger", ";", "Info", "info", "=", "swagger", ".", "getInfo", "(", ")", ";", "buildDocumentTitle", "(", "markupDocBuilder", ",", "info", ".", "getTitle", "(", ")", ")", ";", "applyOverviewDocumentExtension", "(", "new", "Context", "(", "Position", ".", "DOCUMENT_BEFORE", ",", "markupDocBuilder", ")", ")", ";", "buildOverviewTitle", "(", "markupDocBuilder", ",", "labels", ".", "getLabel", "(", "Labels", ".", "OVERVIEW", ")", ")", ";", "applyOverviewDocumentExtension", "(", "new", "Context", "(", "Position", ".", "DOCUMENT_BEGIN", ",", "markupDocBuilder", ")", ")", ";", "buildDescriptionParagraph", "(", "markupDocBuilder", ",", "info", ".", "getDescription", "(", ")", ")", ";", "buildVersionInfoSection", "(", "markupDocBuilder", ",", "info", ")", ";", "buildContactInfoSection", "(", "markupDocBuilder", ",", "info", ".", "getContact", "(", ")", ")", ";", "buildLicenseInfoSection", "(", "markupDocBuilder", ",", "info", ")", ";", "buildUriSchemeSection", "(", "markupDocBuilder", ",", "swagger", ")", ";", "buildTagsSection", "(", "markupDocBuilder", ",", "swagger", ".", "getTags", "(", ")", ")", ";", "buildConsumesSection", "(", "markupDocBuilder", ",", "swagger", ".", "getConsumes", "(", ")", ")", ";", "buildProducesSection", "(", "markupDocBuilder", ",", "swagger", ".", "getProduces", "(", ")", ")", ";", "buildExternalDocsSection", "(", "markupDocBuilder", ",", "swagger", ".", "getExternalDocs", "(", ")", ")", ";", "applyOverviewDocumentExtension", "(", "new", "Context", "(", "Position", ".", "DOCUMENT_END", ",", "markupDocBuilder", ")", ")", ";", "applyOverviewDocumentExtension", "(", "new", "Context", "(", "Position", ".", "DOCUMENT_AFTER", ",", "markupDocBuilder", ")", ")", ";", "return", "markupDocBuilder", ";", "}" ]
Builds the overview MarkupDocument. @return the overview MarkupDocument
[ "Builds", "the", "overview", "MarkupDocument", "." ]
da83465f19a2f8a0f1fba873b5762bca8587896b
https://github.com/Swagger2Markup/swagger2markup/blob/da83465f19a2f8a0f1fba873b5762bca8587896b/src/main/java/io/github/swagger2markup/internal/document/OverviewDocument.java#L68-L88
17,110
Swagger2Markup/swagger2markup
src/main/java/io/github/swagger2markup/internal/document/OverviewDocument.java
OverviewDocument.applyOverviewDocumentExtension
private void applyOverviewDocumentExtension(Context context) { extensionRegistry.getOverviewDocumentExtensions().forEach(extension -> extension.apply(context)); }
java
private void applyOverviewDocumentExtension(Context context) { extensionRegistry.getOverviewDocumentExtensions().forEach(extension -> extension.apply(context)); }
[ "private", "void", "applyOverviewDocumentExtension", "(", "Context", "context", ")", "{", "extensionRegistry", ".", "getOverviewDocumentExtensions", "(", ")", ".", "forEach", "(", "extension", "->", "extension", ".", "apply", "(", "context", ")", ")", ";", "}" ]
Apply extension context to all OverviewContentExtension @param context context
[ "Apply", "extension", "context", "to", "all", "OverviewContentExtension" ]
da83465f19a2f8a0f1fba873b5762bca8587896b
https://github.com/Swagger2Markup/swagger2markup/blob/da83465f19a2f8a0f1fba873b5762bca8587896b/src/main/java/io/github/swagger2markup/internal/document/OverviewDocument.java#L155-L157
17,111
Swagger2Markup/swagger2markup
src/main/java/io/github/swagger2markup/internal/document/DefinitionsDocument.java
DefinitionsDocument.apply
@Override public MarkupDocBuilder apply(MarkupDocBuilder markupDocBuilder, DefinitionsDocument.Parameters params) { Map<String, Model> definitions = params.definitions; if (MapUtils.isNotEmpty(definitions)) { applyDefinitionsDocumentExtension(new Context(Position.DOCUMENT_BEFORE, markupDocBuilder)); buildDefinitionsTitle(markupDocBuilder, labels.getLabel(Labels.DEFINITIONS)); applyDefinitionsDocumentExtension(new Context(Position.DOCUMENT_BEGIN, markupDocBuilder)); buildDefinitionsSection(markupDocBuilder, definitions); applyDefinitionsDocumentExtension(new Context(Position.DOCUMENT_END, markupDocBuilder)); applyDefinitionsDocumentExtension(new Context(Position.DOCUMENT_AFTER, markupDocBuilder)); } return markupDocBuilder; }
java
@Override public MarkupDocBuilder apply(MarkupDocBuilder markupDocBuilder, DefinitionsDocument.Parameters params) { Map<String, Model> definitions = params.definitions; if (MapUtils.isNotEmpty(definitions)) { applyDefinitionsDocumentExtension(new Context(Position.DOCUMENT_BEFORE, markupDocBuilder)); buildDefinitionsTitle(markupDocBuilder, labels.getLabel(Labels.DEFINITIONS)); applyDefinitionsDocumentExtension(new Context(Position.DOCUMENT_BEGIN, markupDocBuilder)); buildDefinitionsSection(markupDocBuilder, definitions); applyDefinitionsDocumentExtension(new Context(Position.DOCUMENT_END, markupDocBuilder)); applyDefinitionsDocumentExtension(new Context(Position.DOCUMENT_AFTER, markupDocBuilder)); } return markupDocBuilder; }
[ "@", "Override", "public", "MarkupDocBuilder", "apply", "(", "MarkupDocBuilder", "markupDocBuilder", ",", "DefinitionsDocument", ".", "Parameters", "params", ")", "{", "Map", "<", "String", ",", "Model", ">", "definitions", "=", "params", ".", "definitions", ";", "if", "(", "MapUtils", ".", "isNotEmpty", "(", "definitions", ")", ")", "{", "applyDefinitionsDocumentExtension", "(", "new", "Context", "(", "Position", ".", "DOCUMENT_BEFORE", ",", "markupDocBuilder", ")", ")", ";", "buildDefinitionsTitle", "(", "markupDocBuilder", ",", "labels", ".", "getLabel", "(", "Labels", ".", "DEFINITIONS", ")", ")", ";", "applyDefinitionsDocumentExtension", "(", "new", "Context", "(", "Position", ".", "DOCUMENT_BEGIN", ",", "markupDocBuilder", ")", ")", ";", "buildDefinitionsSection", "(", "markupDocBuilder", ",", "definitions", ")", ";", "applyDefinitionsDocumentExtension", "(", "new", "Context", "(", "Position", ".", "DOCUMENT_END", ",", "markupDocBuilder", ")", ")", ";", "applyDefinitionsDocumentExtension", "(", "new", "Context", "(", "Position", ".", "DOCUMENT_AFTER", ",", "markupDocBuilder", ")", ")", ";", "}", "return", "markupDocBuilder", ";", "}" ]
Builds the definitions MarkupDocument. @return the definitions MarkupDocument
[ "Builds", "the", "definitions", "MarkupDocument", "." ]
da83465f19a2f8a0f1fba873b5762bca8587896b
https://github.com/Swagger2Markup/swagger2markup/blob/da83465f19a2f8a0f1fba873b5762bca8587896b/src/main/java/io/github/swagger2markup/internal/document/DefinitionsDocument.java#L79-L91
17,112
Swagger2Markup/swagger2markup
src/main/java/io/github/swagger2markup/internal/document/DefinitionsDocument.java
DefinitionsDocument.applyDefinitionsDocumentExtension
private void applyDefinitionsDocumentExtension(Context context) { extensionRegistry.getDefinitionsDocumentExtensions().forEach(extension -> extension.apply(context)); }
java
private void applyDefinitionsDocumentExtension(Context context) { extensionRegistry.getDefinitionsDocumentExtensions().forEach(extension -> extension.apply(context)); }
[ "private", "void", "applyDefinitionsDocumentExtension", "(", "Context", "context", ")", "{", "extensionRegistry", ".", "getDefinitionsDocumentExtensions", "(", ")", ".", "forEach", "(", "extension", "->", "extension", ".", "apply", "(", "context", ")", ")", ";", "}" ]
Apply extension context to all DefinitionsContentExtension @param context context
[ "Apply", "extension", "context", "to", "all", "DefinitionsContentExtension" ]
da83465f19a2f8a0f1fba873b5762bca8587896b
https://github.com/Swagger2Markup/swagger2markup/blob/da83465f19a2f8a0f1fba873b5762bca8587896b/src/main/java/io/github/swagger2markup/internal/document/DefinitionsDocument.java#L112-L114
17,113
Swagger2Markup/swagger2markup
src/main/java/io/github/swagger2markup/internal/document/DefinitionsDocument.java
DefinitionsDocument.buildDefinition
private void buildDefinition(MarkupDocBuilder markupDocBuilder, String definitionName, Model model) { if (logger.isDebugEnabled()) { logger.debug("Definition processed : '{}'", definitionName); } if (config.isSeparatedDefinitionsEnabled()) { MarkupDocBuilder defDocBuilder = copyMarkupDocBuilder(markupDocBuilder); applyDefinitionComponent(defDocBuilder, definitionName, model); Path definitionFile = context.getOutputPath().resolve(definitionDocumentNameResolver.apply(definitionName)); defDocBuilder.writeToFileWithoutExtension(definitionFile, StandardCharsets.UTF_8); if (logger.isDebugEnabled()) { logger.debug("Separate definition file produced : '{}'", definitionFile); } definitionRef(markupDocBuilder, definitionName); } else { applyDefinitionComponent(markupDocBuilder, definitionName, model); } }
java
private void buildDefinition(MarkupDocBuilder markupDocBuilder, String definitionName, Model model) { if (logger.isDebugEnabled()) { logger.debug("Definition processed : '{}'", definitionName); } if (config.isSeparatedDefinitionsEnabled()) { MarkupDocBuilder defDocBuilder = copyMarkupDocBuilder(markupDocBuilder); applyDefinitionComponent(defDocBuilder, definitionName, model); Path definitionFile = context.getOutputPath().resolve(definitionDocumentNameResolver.apply(definitionName)); defDocBuilder.writeToFileWithoutExtension(definitionFile, StandardCharsets.UTF_8); if (logger.isDebugEnabled()) { logger.debug("Separate definition file produced : '{}'", definitionFile); } definitionRef(markupDocBuilder, definitionName); } else { applyDefinitionComponent(markupDocBuilder, definitionName, model); } }
[ "private", "void", "buildDefinition", "(", "MarkupDocBuilder", "markupDocBuilder", ",", "String", "definitionName", ",", "Model", "model", ")", "{", "if", "(", "logger", ".", "isDebugEnabled", "(", ")", ")", "{", "logger", ".", "debug", "(", "\"Definition processed : '{}'\"", ",", "definitionName", ")", ";", "}", "if", "(", "config", ".", "isSeparatedDefinitionsEnabled", "(", ")", ")", "{", "MarkupDocBuilder", "defDocBuilder", "=", "copyMarkupDocBuilder", "(", "markupDocBuilder", ")", ";", "applyDefinitionComponent", "(", "defDocBuilder", ",", "definitionName", ",", "model", ")", ";", "Path", "definitionFile", "=", "context", ".", "getOutputPath", "(", ")", ".", "resolve", "(", "definitionDocumentNameResolver", ".", "apply", "(", "definitionName", ")", ")", ";", "defDocBuilder", ".", "writeToFileWithoutExtension", "(", "definitionFile", ",", "StandardCharsets", ".", "UTF_8", ")", ";", "if", "(", "logger", ".", "isDebugEnabled", "(", ")", ")", "{", "logger", ".", "debug", "(", "\"Separate definition file produced : '{}'\"", ",", "definitionFile", ")", ";", "}", "definitionRef", "(", "markupDocBuilder", ",", "definitionName", ")", ";", "}", "else", "{", "applyDefinitionComponent", "(", "markupDocBuilder", ",", "definitionName", ",", "model", ")", ";", "}", "}" ]
Generate definition files depending on the generation mode @param definitionName definition name to process @param model definition model to process
[ "Generate", "definition", "files", "depending", "on", "the", "generation", "mode" ]
da83465f19a2f8a0f1fba873b5762bca8587896b
https://github.com/Swagger2Markup/swagger2markup/blob/da83465f19a2f8a0f1fba873b5762bca8587896b/src/main/java/io/github/swagger2markup/internal/document/DefinitionsDocument.java#L122-L140
17,114
Swagger2Markup/swagger2markup
src/main/java/io/github/swagger2markup/internal/document/DefinitionsDocument.java
DefinitionsDocument.applyDefinitionComponent
private void applyDefinitionComponent(MarkupDocBuilder markupDocBuilder, String definitionName, Model model) { definitionComponent.apply(markupDocBuilder, DefinitionComponent.parameters( definitionName, model, 2)); }
java
private void applyDefinitionComponent(MarkupDocBuilder markupDocBuilder, String definitionName, Model model) { definitionComponent.apply(markupDocBuilder, DefinitionComponent.parameters( definitionName, model, 2)); }
[ "private", "void", "applyDefinitionComponent", "(", "MarkupDocBuilder", "markupDocBuilder", ",", "String", "definitionName", ",", "Model", "model", ")", "{", "definitionComponent", ".", "apply", "(", "markupDocBuilder", ",", "DefinitionComponent", ".", "parameters", "(", "definitionName", ",", "model", ",", "2", ")", ")", ";", "}" ]
Builds a concrete definition @param markupDocBuilder the markupDocBuilder do use for output @param definitionName the name of the definition @param model the Swagger Model of the definition
[ "Builds", "a", "concrete", "definition" ]
da83465f19a2f8a0f1fba873b5762bca8587896b
https://github.com/Swagger2Markup/swagger2markup/blob/da83465f19a2f8a0f1fba873b5762bca8587896b/src/main/java/io/github/swagger2markup/internal/document/DefinitionsDocument.java#L159-L164
17,115
Swagger2Markup/swagger2markup
src/main/java/io/github/swagger2markup/internal/document/DefinitionsDocument.java
DefinitionsDocument.definitionRef
private void definitionRef(MarkupDocBuilder markupDocBuilder, String definitionName) { buildDefinitionTitle(markupDocBuilder, crossReference(markupDocBuilder, definitionDocumentResolverDefault.apply(definitionName), definitionName, definitionName), "ref-" + definitionName); }
java
private void definitionRef(MarkupDocBuilder markupDocBuilder, String definitionName) { buildDefinitionTitle(markupDocBuilder, crossReference(markupDocBuilder, definitionDocumentResolverDefault.apply(definitionName), definitionName, definitionName), "ref-" + definitionName); }
[ "private", "void", "definitionRef", "(", "MarkupDocBuilder", "markupDocBuilder", ",", "String", "definitionName", ")", "{", "buildDefinitionTitle", "(", "markupDocBuilder", ",", "crossReference", "(", "markupDocBuilder", ",", "definitionDocumentResolverDefault", ".", "apply", "(", "definitionName", ")", ",", "definitionName", ",", "definitionName", ")", ",", "\"ref-\"", "+", "definitionName", ")", ";", "}" ]
Builds a cross-reference to a separated definition file. @param definitionName definition name to target
[ "Builds", "a", "cross", "-", "reference", "to", "a", "separated", "definition", "file", "." ]
da83465f19a2f8a0f1fba873b5762bca8587896b
https://github.com/Swagger2Markup/swagger2markup/blob/da83465f19a2f8a0f1fba873b5762bca8587896b/src/main/java/io/github/swagger2markup/internal/document/DefinitionsDocument.java#L171-L173
17,116
Swagger2Markup/swagger2markup
src/main/java/io/github/swagger2markup/internal/document/DefinitionsDocument.java
DefinitionsDocument.buildDefinitionTitle
private void buildDefinitionTitle(MarkupDocBuilder markupDocBuilder, String title, String anchor) { markupDocBuilder.sectionTitleWithAnchorLevel2(title, anchor); }
java
private void buildDefinitionTitle(MarkupDocBuilder markupDocBuilder, String title, String anchor) { markupDocBuilder.sectionTitleWithAnchorLevel2(title, anchor); }
[ "private", "void", "buildDefinitionTitle", "(", "MarkupDocBuilder", "markupDocBuilder", ",", "String", "title", ",", "String", "anchor", ")", "{", "markupDocBuilder", ".", "sectionTitleWithAnchorLevel2", "(", "title", ",", "anchor", ")", ";", "}" ]
Builds definition title @param markupDocBuilder the markupDocBuilder do use for output @param title definition title @param anchor optional anchor (null => auto-generate from title)
[ "Builds", "definition", "title" ]
da83465f19a2f8a0f1fba873b5762bca8587896b
https://github.com/Swagger2Markup/swagger2markup/blob/da83465f19a2f8a0f1fba873b5762bca8587896b/src/main/java/io/github/swagger2markup/internal/document/DefinitionsDocument.java#L182-L184
17,117
Swagger2Markup/swagger2markup
src/main/java/io/github/swagger2markup/internal/adapter/ParameterAdapter.java
ParameterAdapter.generateExample
public static Object generateExample(AbstractSerializableParameter<?> parameter) { switch (parameter.getType()) { case "integer": return 0; case "number": return 0.0; case "boolean": return true; case "string": return ExamplesUtil.generateStringExample(parameter.getFormat(), parameter.getEnum()); default: return parameter.getType(); } }
java
public static Object generateExample(AbstractSerializableParameter<?> parameter) { switch (parameter.getType()) { case "integer": return 0; case "number": return 0.0; case "boolean": return true; case "string": return ExamplesUtil.generateStringExample(parameter.getFormat(), parameter.getEnum()); default: return parameter.getType(); } }
[ "public", "static", "Object", "generateExample", "(", "AbstractSerializableParameter", "<", "?", ">", "parameter", ")", "{", "switch", "(", "parameter", ".", "getType", "(", ")", ")", "{", "case", "\"integer\"", ":", "return", "0", ";", "case", "\"number\"", ":", "return", "0.0", ";", "case", "\"boolean\"", ":", "return", "true", ";", "case", "\"string\"", ":", "return", "ExamplesUtil", ".", "generateStringExample", "(", "parameter", ".", "getFormat", "(", ")", ",", "parameter", ".", "getEnum", "(", ")", ")", ";", "default", ":", "return", "parameter", ".", "getType", "(", ")", ";", "}", "}" ]
Generate a default example value for parameter. @param parameter parameter @return a generated example for the parameter
[ "Generate", "a", "default", "example", "value", "for", "parameter", "." ]
da83465f19a2f8a0f1fba873b5762bca8587896b
https://github.com/Swagger2Markup/swagger2markup/blob/da83465f19a2f8a0f1fba873b5762bca8587896b/src/main/java/io/github/swagger2markup/internal/adapter/ParameterAdapter.java#L85-L98
17,118
Swagger2Markup/swagger2markup
src/main/java/io/github/swagger2markup/internal/adapter/ParameterAdapter.java
ParameterAdapter.getType
private Type getType(Map<String, Model> definitions, DocumentResolver definitionDocumentResolver) { Validate.notNull(parameter, "parameter must not be null!"); Type type = null; if (parameter instanceof BodyParameter) { BodyParameter bodyParameter = (BodyParameter) parameter; Model model = bodyParameter.getSchema(); if (model != null) { type = ModelUtils.getType(model, definitions, definitionDocumentResolver); } else { type = new BasicType("string", bodyParameter.getName()); } } else if (parameter instanceof AbstractSerializableParameter) { AbstractSerializableParameter serializableParameter = (AbstractSerializableParameter) parameter; @SuppressWarnings("unchecked") List<String> enums = serializableParameter.getEnum(); if (CollectionUtils.isNotEmpty(enums)) { type = new EnumType(serializableParameter.getName(), enums); } else { type = new BasicType(serializableParameter.getType(), serializableParameter.getName(), serializableParameter.getFormat()); } if (serializableParameter.getType().equals("array")) { String collectionFormat = serializableParameter.getCollectionFormat(); type = new ArrayType(serializableParameter.getName(), new PropertyAdapter(serializableParameter.getItems()).getType(definitionDocumentResolver), collectionFormat); } } else if (parameter instanceof RefParameter) { String refName = ((RefParameter) parameter).getSimpleRef(); type = new RefType(definitionDocumentResolver.apply(refName), new ObjectType(refName, null /* FIXME, not used for now */)); } return type; }
java
private Type getType(Map<String, Model> definitions, DocumentResolver definitionDocumentResolver) { Validate.notNull(parameter, "parameter must not be null!"); Type type = null; if (parameter instanceof BodyParameter) { BodyParameter bodyParameter = (BodyParameter) parameter; Model model = bodyParameter.getSchema(); if (model != null) { type = ModelUtils.getType(model, definitions, definitionDocumentResolver); } else { type = new BasicType("string", bodyParameter.getName()); } } else if (parameter instanceof AbstractSerializableParameter) { AbstractSerializableParameter serializableParameter = (AbstractSerializableParameter) parameter; @SuppressWarnings("unchecked") List<String> enums = serializableParameter.getEnum(); if (CollectionUtils.isNotEmpty(enums)) { type = new EnumType(serializableParameter.getName(), enums); } else { type = new BasicType(serializableParameter.getType(), serializableParameter.getName(), serializableParameter.getFormat()); } if (serializableParameter.getType().equals("array")) { String collectionFormat = serializableParameter.getCollectionFormat(); type = new ArrayType(serializableParameter.getName(), new PropertyAdapter(serializableParameter.getItems()).getType(definitionDocumentResolver), collectionFormat); } } else if (parameter instanceof RefParameter) { String refName = ((RefParameter) parameter).getSimpleRef(); type = new RefType(definitionDocumentResolver.apply(refName), new ObjectType(refName, null /* FIXME, not used for now */)); } return type; }
[ "private", "Type", "getType", "(", "Map", "<", "String", ",", "Model", ">", "definitions", ",", "DocumentResolver", "definitionDocumentResolver", ")", "{", "Validate", ".", "notNull", "(", "parameter", ",", "\"parameter must not be null!\"", ")", ";", "Type", "type", "=", "null", ";", "if", "(", "parameter", "instanceof", "BodyParameter", ")", "{", "BodyParameter", "bodyParameter", "=", "(", "BodyParameter", ")", "parameter", ";", "Model", "model", "=", "bodyParameter", ".", "getSchema", "(", ")", ";", "if", "(", "model", "!=", "null", ")", "{", "type", "=", "ModelUtils", ".", "getType", "(", "model", ",", "definitions", ",", "definitionDocumentResolver", ")", ";", "}", "else", "{", "type", "=", "new", "BasicType", "(", "\"string\"", ",", "bodyParameter", ".", "getName", "(", ")", ")", ";", "}", "}", "else", "if", "(", "parameter", "instanceof", "AbstractSerializableParameter", ")", "{", "AbstractSerializableParameter", "serializableParameter", "=", "(", "AbstractSerializableParameter", ")", "parameter", ";", "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "List", "<", "String", ">", "enums", "=", "serializableParameter", ".", "getEnum", "(", ")", ";", "if", "(", "CollectionUtils", ".", "isNotEmpty", "(", "enums", ")", ")", "{", "type", "=", "new", "EnumType", "(", "serializableParameter", ".", "getName", "(", ")", ",", "enums", ")", ";", "}", "else", "{", "type", "=", "new", "BasicType", "(", "serializableParameter", ".", "getType", "(", ")", ",", "serializableParameter", ".", "getName", "(", ")", ",", "serializableParameter", ".", "getFormat", "(", ")", ")", ";", "}", "if", "(", "serializableParameter", ".", "getType", "(", ")", ".", "equals", "(", "\"array\"", ")", ")", "{", "String", "collectionFormat", "=", "serializableParameter", ".", "getCollectionFormat", "(", ")", ";", "type", "=", "new", "ArrayType", "(", "serializableParameter", ".", "getName", "(", ")", ",", "new", "PropertyAdapter", "(", "serializableParameter", ".", "getItems", "(", ")", ")", ".", "getType", "(", "definitionDocumentResolver", ")", ",", "collectionFormat", ")", ";", "}", "}", "else", "if", "(", "parameter", "instanceof", "RefParameter", ")", "{", "String", "refName", "=", "(", "(", "RefParameter", ")", "parameter", ")", ".", "getSimpleRef", "(", ")", ";", "type", "=", "new", "RefType", "(", "definitionDocumentResolver", ".", "apply", "(", "refName", ")", ",", "new", "ObjectType", "(", "refName", ",", "null", "/* FIXME, not used for now */", ")", ")", ";", "}", "return", "type", ";", "}" ]
Retrieves the type of a parameter, or otherwise null @param definitionDocumentResolver the definition document resolver @return the type of the parameter, or otherwise null
[ "Retrieves", "the", "type", "of", "a", "parameter", "or", "otherwise", "null" ]
da83465f19a2f8a0f1fba873b5762bca8587896b
https://github.com/Swagger2Markup/swagger2markup/blob/da83465f19a2f8a0f1fba873b5762bca8587896b/src/main/java/io/github/swagger2markup/internal/adapter/ParameterAdapter.java#L163-L198
17,119
Swagger2Markup/swagger2markup
src/main/java/io/github/swagger2markup/internal/adapter/ParameterAdapter.java
ParameterAdapter.getDefaultValue
public Optional<Object> getDefaultValue() { Validate.notNull(parameter, "parameter must not be null!"); if (parameter instanceof AbstractSerializableParameter) { AbstractSerializableParameter serializableParameter = (AbstractSerializableParameter) parameter; return Optional.ofNullable(serializableParameter.getDefaultValue()); } return Optional.empty(); }
java
public Optional<Object> getDefaultValue() { Validate.notNull(parameter, "parameter must not be null!"); if (parameter instanceof AbstractSerializableParameter) { AbstractSerializableParameter serializableParameter = (AbstractSerializableParameter) parameter; return Optional.ofNullable(serializableParameter.getDefaultValue()); } return Optional.empty(); }
[ "public", "Optional", "<", "Object", ">", "getDefaultValue", "(", ")", "{", "Validate", ".", "notNull", "(", "parameter", ",", "\"parameter must not be null!\"", ")", ";", "if", "(", "parameter", "instanceof", "AbstractSerializableParameter", ")", "{", "AbstractSerializableParameter", "serializableParameter", "=", "(", "AbstractSerializableParameter", ")", "parameter", ";", "return", "Optional", ".", "ofNullable", "(", "serializableParameter", ".", "getDefaultValue", "(", ")", ")", ";", "}", "return", "Optional", ".", "empty", "(", ")", ";", "}" ]
Retrieves the default value of a parameter @return the default value of the parameter
[ "Retrieves", "the", "default", "value", "of", "a", "parameter" ]
da83465f19a2f8a0f1fba873b5762bca8587896b
https://github.com/Swagger2Markup/swagger2markup/blob/da83465f19a2f8a0f1fba873b5762bca8587896b/src/main/java/io/github/swagger2markup/internal/adapter/ParameterAdapter.java#L205-L212
17,120
haifengl/smile
plot/src/main/java/smile/plot/SparseMatrixPlot.java
SparseMatrixPlot.plot
public static PlotCanvas plot(SparseMatrix sparse) { double[] lowerBound = {0, 0}; double[] upperBound = {sparse.ncols(), sparse.nrows()}; PlotCanvas canvas = new PlotCanvas(lowerBound, upperBound, false); canvas.add(new SparseMatrixPlot(sparse)); canvas.getAxis(0).setLabelVisible(false); canvas.getAxis(0).setGridVisible(false); canvas.getAxis(1).setLabelVisible(false); canvas.getAxis(1).setGridVisible(false); return canvas; }
java
public static PlotCanvas plot(SparseMatrix sparse) { double[] lowerBound = {0, 0}; double[] upperBound = {sparse.ncols(), sparse.nrows()}; PlotCanvas canvas = new PlotCanvas(lowerBound, upperBound, false); canvas.add(new SparseMatrixPlot(sparse)); canvas.getAxis(0).setLabelVisible(false); canvas.getAxis(0).setGridVisible(false); canvas.getAxis(1).setLabelVisible(false); canvas.getAxis(1).setGridVisible(false); return canvas; }
[ "public", "static", "PlotCanvas", "plot", "(", "SparseMatrix", "sparse", ")", "{", "double", "[", "]", "lowerBound", "=", "{", "0", ",", "0", "}", ";", "double", "[", "]", "upperBound", "=", "{", "sparse", ".", "ncols", "(", ")", ",", "sparse", ".", "nrows", "(", ")", "}", ";", "PlotCanvas", "canvas", "=", "new", "PlotCanvas", "(", "lowerBound", ",", "upperBound", ",", "false", ")", ";", "canvas", ".", "add", "(", "new", "SparseMatrixPlot", "(", "sparse", ")", ")", ";", "canvas", ".", "getAxis", "(", "0", ")", ".", "setLabelVisible", "(", "false", ")", ";", "canvas", ".", "getAxis", "(", "0", ")", ".", "setGridVisible", "(", "false", ")", ";", "canvas", ".", "getAxis", "(", "1", ")", ".", "setLabelVisible", "(", "false", ")", ";", "canvas", ".", "getAxis", "(", "1", ")", ".", "setGridVisible", "(", "false", ")", ";", "return", "canvas", ";", "}" ]
Create a sparse matrix plot canvas. @param sparse a sparse matrix.
[ "Create", "a", "sparse", "matrix", "plot", "canvas", "." ]
e27e43e90fbaacce3f99d30120cf9dd6a764c33d
https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/plot/src/main/java/smile/plot/SparseMatrixPlot.java#L286-L298
17,121
haifengl/smile
plot/src/main/java/smile/plot/BaseGrid.java
BaseGrid.setFrameVisible
public BaseGrid setFrameVisible(boolean v) { for (int i = 0; i < axis.length; i++) { axis[i].setGridVisible(v); } return this; }
java
public BaseGrid setFrameVisible(boolean v) { for (int i = 0; i < axis.length; i++) { axis[i].setGridVisible(v); } return this; }
[ "public", "BaseGrid", "setFrameVisible", "(", "boolean", "v", ")", "{", "for", "(", "int", "i", "=", "0", ";", "i", "<", "axis", ".", "length", ";", "i", "++", ")", "{", "axis", "[", "i", "]", ".", "setGridVisible", "(", "v", ")", ";", "}", "return", "this", ";", "}" ]
Set if the frame visible.
[ "Set", "if", "the", "frame", "visible", "." ]
e27e43e90fbaacce3f99d30120cf9dd6a764c33d
https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/plot/src/main/java/smile/plot/BaseGrid.java#L93-L98
17,122
haifengl/smile
plot/src/main/java/smile/plot/BaseGrid.java
BaseGrid.setAxisLabel
public BaseGrid setAxisLabel(String... axisLabels) { if (axisLabels.length != base.getDimension()) { throw new IllegalArgumentException("Axis label size don't match base dimension."); } for (int i = 0; i < axisLabels.length; i++) { axis[i].setAxisLabel(axisLabels[i]); } return this; }
java
public BaseGrid setAxisLabel(String... axisLabels) { if (axisLabels.length != base.getDimension()) { throw new IllegalArgumentException("Axis label size don't match base dimension."); } for (int i = 0; i < axisLabels.length; i++) { axis[i].setAxisLabel(axisLabels[i]); } return this; }
[ "public", "BaseGrid", "setAxisLabel", "(", "String", "...", "axisLabels", ")", "{", "if", "(", "axisLabels", ".", "length", "!=", "base", ".", "getDimension", "(", ")", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Axis label size don't match base dimension.\"", ")", ";", "}", "for", "(", "int", "i", "=", "0", ";", "i", "<", "axisLabels", ".", "length", ";", "i", "++", ")", "{", "axis", "[", "i", "]", ".", "setAxisLabel", "(", "axisLabels", "[", "i", "]", ")", ";", "}", "return", "this", ";", "}" ]
Set axis labels.
[ "Set", "axis", "labels", "." ]
e27e43e90fbaacce3f99d30120cf9dd6a764c33d
https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/plot/src/main/java/smile/plot/BaseGrid.java#L117-L127
17,123
haifengl/smile
plot/src/main/java/smile/plot/BaseGrid.java
BaseGrid.getAxisLabel
public String[] getAxisLabel() { String[] array = new String[axis.length]; for (int i = 0; i < array.length; i++) { array[i] = axis[i].getAxisLabel(); } return array; }
java
public String[] getAxisLabel() { String[] array = new String[axis.length]; for (int i = 0; i < array.length; i++) { array[i] = axis[i].getAxisLabel(); } return array; }
[ "public", "String", "[", "]", "getAxisLabel", "(", ")", "{", "String", "[", "]", "array", "=", "new", "String", "[", "axis", ".", "length", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "array", ".", "length", ";", "i", "++", ")", "{", "array", "[", "i", "]", "=", "axis", "[", "i", "]", ".", "getAxisLabel", "(", ")", ";", "}", "return", "array", ";", "}" ]
Get axis label.
[ "Get", "axis", "label", "." ]
e27e43e90fbaacce3f99d30120cf9dd6a764c33d
https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/plot/src/main/java/smile/plot/BaseGrid.java#L132-L138
17,124
haifengl/smile
plot/src/main/java/smile/plot/BaseGrid.java
BaseGrid.paint
public void paint(Graphics g) { for (int i = 0; i < axis.length; i++) { axis[i].paint(g); } }
java
public void paint(Graphics g) { for (int i = 0; i < axis.length; i++) { axis[i].paint(g); } }
[ "public", "void", "paint", "(", "Graphics", "g", ")", "{", "for", "(", "int", "i", "=", "0", ";", "i", "<", "axis", ".", "length", ";", "i", "++", ")", "{", "axis", "[", "i", "]", ".", "paint", "(", "g", ")", ";", "}", "}" ]
Draw the grid.
[ "Draw", "the", "grid", "." ]
e27e43e90fbaacce3f99d30120cf9dd6a764c33d
https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/plot/src/main/java/smile/plot/BaseGrid.java#L169-L173
17,125
haifengl/smile
core/src/main/java/smile/association/ARM.java
ARM.learn
public long learn(double confidence, PrintStream out) { long n = 0; ttree = fim.buildTotalSupportTree(); for (int i = 0; i < ttree.root.children.length; i++) { if (ttree.root.children[i] != null) { int[] itemset = {ttree.root.children[i].id}; n += learn(out, null, itemset, i, ttree.root.children[i], confidence); } } return n; }
java
public long learn(double confidence, PrintStream out) { long n = 0; ttree = fim.buildTotalSupportTree(); for (int i = 0; i < ttree.root.children.length; i++) { if (ttree.root.children[i] != null) { int[] itemset = {ttree.root.children[i].id}; n += learn(out, null, itemset, i, ttree.root.children[i], confidence); } } return n; }
[ "public", "long", "learn", "(", "double", "confidence", ",", "PrintStream", "out", ")", "{", "long", "n", "=", "0", ";", "ttree", "=", "fim", ".", "buildTotalSupportTree", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "ttree", ".", "root", ".", "children", ".", "length", ";", "i", "++", ")", "{", "if", "(", "ttree", ".", "root", ".", "children", "[", "i", "]", "!=", "null", ")", "{", "int", "[", "]", "itemset", "=", "{", "ttree", ".", "root", ".", "children", "[", "i", "]", ".", "id", "}", ";", "n", "+=", "learn", "(", "out", ",", "null", ",", "itemset", ",", "i", ",", "ttree", ".", "root", ".", "children", "[", "i", "]", ",", "confidence", ")", ";", "}", "}", "return", "n", ";", "}" ]
Mines the association rules. The discovered rules will be printed out to the provided stream. @param confidence the confidence threshold for association rules. @return the number of discovered association rules.
[ "Mines", "the", "association", "rules", ".", "The", "discovered", "rules", "will", "be", "printed", "out", "to", "the", "provided", "stream", "." ]
e27e43e90fbaacce3f99d30120cf9dd6a764c33d
https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/core/src/main/java/smile/association/ARM.java#L111-L121
17,126
haifengl/smile
core/src/main/java/smile/association/ARM.java
ARM.learn
public List<AssociationRule> learn(double confidence) { List<AssociationRule> list = new ArrayList<>(); ttree = fim.buildTotalSupportTree(); for (int i = 0; i < ttree.root.children.length; i++) { if (ttree.root.children[i] != null) { int[] itemset = {ttree.root.children[i].id}; learn(null, list, itemset, i, ttree.root.children[i], confidence); } } return list; }
java
public List<AssociationRule> learn(double confidence) { List<AssociationRule> list = new ArrayList<>(); ttree = fim.buildTotalSupportTree(); for (int i = 0; i < ttree.root.children.length; i++) { if (ttree.root.children[i] != null) { int[] itemset = {ttree.root.children[i].id}; learn(null, list, itemset, i, ttree.root.children[i], confidence); } } return list; }
[ "public", "List", "<", "AssociationRule", ">", "learn", "(", "double", "confidence", ")", "{", "List", "<", "AssociationRule", ">", "list", "=", "new", "ArrayList", "<>", "(", ")", ";", "ttree", "=", "fim", ".", "buildTotalSupportTree", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "ttree", ".", "root", ".", "children", ".", "length", ";", "i", "++", ")", "{", "if", "(", "ttree", ".", "root", ".", "children", "[", "i", "]", "!=", "null", ")", "{", "int", "[", "]", "itemset", "=", "{", "ttree", ".", "root", ".", "children", "[", "i", "]", ".", "id", "}", ";", "learn", "(", "null", ",", "list", ",", "itemset", ",", "i", ",", "ttree", ".", "root", ".", "children", "[", "i", "]", ",", "confidence", ")", ";", "}", "}", "return", "list", ";", "}" ]
Mines the association rules. The discovered frequent rules will be returned in a list. @param confidence the confidence threshold for association rules.
[ "Mines", "the", "association", "rules", ".", "The", "discovered", "frequent", "rules", "will", "be", "returned", "in", "a", "list", "." ]
e27e43e90fbaacce3f99d30120cf9dd6a764c33d
https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/core/src/main/java/smile/association/ARM.java#L127-L137
17,127
haifengl/smile
core/src/main/java/smile/association/ARM.java
ARM.learn
private long learn(PrintStream out, List<AssociationRule> list, int[] itemset, int size, Node node, double confidence) { long n = 0; if (node.children == null) { return n; } for (int i = 0; i < size; i++) { if (node.children[i] != null) { int[] newItemset = FPGrowth.insert(itemset, node.children[i].id); // Generate ARs for current large itemset n += learn(out, list, newItemset, node.children[i].support, confidence); // Continue generation process n += learn(out, list, newItemset, i, node.children[i], confidence); } } return n; }
java
private long learn(PrintStream out, List<AssociationRule> list, int[] itemset, int size, Node node, double confidence) { long n = 0; if (node.children == null) { return n; } for (int i = 0; i < size; i++) { if (node.children[i] != null) { int[] newItemset = FPGrowth.insert(itemset, node.children[i].id); // Generate ARs for current large itemset n += learn(out, list, newItemset, node.children[i].support, confidence); // Continue generation process n += learn(out, list, newItemset, i, node.children[i], confidence); } } return n; }
[ "private", "long", "learn", "(", "PrintStream", "out", ",", "List", "<", "AssociationRule", ">", "list", ",", "int", "[", "]", "itemset", ",", "int", "size", ",", "Node", "node", ",", "double", "confidence", ")", "{", "long", "n", "=", "0", ";", "if", "(", "node", ".", "children", "==", "null", ")", "{", "return", "n", ";", "}", "for", "(", "int", "i", "=", "0", ";", "i", "<", "size", ";", "i", "++", ")", "{", "if", "(", "node", ".", "children", "[", "i", "]", "!=", "null", ")", "{", "int", "[", "]", "newItemset", "=", "FPGrowth", ".", "insert", "(", "itemset", ",", "node", ".", "children", "[", "i", "]", ".", "id", ")", ";", "// Generate ARs for current large itemset", "n", "+=", "learn", "(", "out", ",", "list", ",", "newItemset", ",", "node", ".", "children", "[", "i", "]", ".", "support", ",", "confidence", ")", ";", "// Continue generation process", "n", "+=", "learn", "(", "out", ",", "list", ",", "newItemset", ",", "i", ",", "node", ".", "children", "[", "i", "]", ",", "confidence", ")", ";", "}", "}", "return", "n", ";", "}" ]
Generates association rules from a T-tree. @param itemset the label for a T-tree node as generated sofar. @param size the size of the current array level in the T-tree. @param node the current node in the T-tree. @param confidence the confidence threshold for association rules.
[ "Generates", "association", "rules", "from", "a", "T", "-", "tree", "." ]
e27e43e90fbaacce3f99d30120cf9dd6a764c33d
https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/core/src/main/java/smile/association/ARM.java#L146-L163
17,128
haifengl/smile
core/src/main/java/smile/association/ARM.java
ARM.learn
private long learn(PrintStream out, List<AssociationRule> list, int[] itemset, int support, double confidence) { long n = 0; // Determine combinations int[][] combinations = getPowerSet(itemset); // Loop through combinations for (int i = 0; i < combinations.length; i++) { // Find complement of combination in given itemSet int[] complement = getComplement(combinations[i], itemset); // If complement is not empty generate rule if (complement != null) { double arc = getConfidence(combinations[i], support); if (arc >= confidence) { double supp = (double) support / fim.size(); AssociationRule ar = new AssociationRule(combinations[i], complement, supp, arc); n++; if (out != null) { out.println(ar); } if (list != null) { list.add(ar); } } } } return n; }
java
private long learn(PrintStream out, List<AssociationRule> list, int[] itemset, int support, double confidence) { long n = 0; // Determine combinations int[][] combinations = getPowerSet(itemset); // Loop through combinations for (int i = 0; i < combinations.length; i++) { // Find complement of combination in given itemSet int[] complement = getComplement(combinations[i], itemset); // If complement is not empty generate rule if (complement != null) { double arc = getConfidence(combinations[i], support); if (arc >= confidence) { double supp = (double) support / fim.size(); AssociationRule ar = new AssociationRule(combinations[i], complement, supp, arc); n++; if (out != null) { out.println(ar); } if (list != null) { list.add(ar); } } } } return n; }
[ "private", "long", "learn", "(", "PrintStream", "out", ",", "List", "<", "AssociationRule", ">", "list", ",", "int", "[", "]", "itemset", ",", "int", "support", ",", "double", "confidence", ")", "{", "long", "n", "=", "0", ";", "// Determine combinations", "int", "[", "]", "[", "]", "combinations", "=", "getPowerSet", "(", "itemset", ")", ";", "// Loop through combinations", "for", "(", "int", "i", "=", "0", ";", "i", "<", "combinations", ".", "length", ";", "i", "++", ")", "{", "// Find complement of combination in given itemSet", "int", "[", "]", "complement", "=", "getComplement", "(", "combinations", "[", "i", "]", ",", "itemset", ")", ";", "// If complement is not empty generate rule", "if", "(", "complement", "!=", "null", ")", "{", "double", "arc", "=", "getConfidence", "(", "combinations", "[", "i", "]", ",", "support", ")", ";", "if", "(", "arc", ">=", "confidence", ")", "{", "double", "supp", "=", "(", "double", ")", "support", "/", "fim", ".", "size", "(", ")", ";", "AssociationRule", "ar", "=", "new", "AssociationRule", "(", "combinations", "[", "i", "]", ",", "complement", ",", "supp", ",", "arc", ")", ";", "n", "++", ";", "if", "(", "out", "!=", "null", ")", "{", "out", ".", "println", "(", "ar", ")", ";", "}", "if", "(", "list", "!=", "null", ")", "{", "list", ".", "add", "(", "ar", ")", ";", "}", "}", "}", "}", "return", "n", ";", "}" ]
Generates all association rules for a given item set. @param itemset the given frequent item set. @param support the associated support value for the item set. @param confidence the confidence threshold for association rules.
[ "Generates", "all", "association", "rules", "for", "a", "given", "item", "set", "." ]
e27e43e90fbaacce3f99d30120cf9dd6a764c33d
https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/core/src/main/java/smile/association/ARM.java#L171-L200
17,129
haifengl/smile
core/src/main/java/smile/association/ARM.java
ARM.getComplement
private static int[] getComplement(int[] subset, int[] fullset) { int size = fullset.length - subset.length; // Returns null if no complement if (size < 1) { return null; } // Otherwsise define combination array and determine complement int[] complement = new int[size]; int index = 0; for (int i = 0; i < fullset.length; i++) { int item = fullset[i]; boolean member = false; for (int j = 0; j < subset.length; j++) { if (item == subset[j]) { member = true; break; } } if (!member) { complement[index++] = item; } } return complement; }
java
private static int[] getComplement(int[] subset, int[] fullset) { int size = fullset.length - subset.length; // Returns null if no complement if (size < 1) { return null; } // Otherwsise define combination array and determine complement int[] complement = new int[size]; int index = 0; for (int i = 0; i < fullset.length; i++) { int item = fullset[i]; boolean member = false; for (int j = 0; j < subset.length; j++) { if (item == subset[j]) { member = true; break; } } if (!member) { complement[index++] = item; } } return complement; }
[ "private", "static", "int", "[", "]", "getComplement", "(", "int", "[", "]", "subset", ",", "int", "[", "]", "fullset", ")", "{", "int", "size", "=", "fullset", ".", "length", "-", "subset", ".", "length", ";", "// Returns null if no complement", "if", "(", "size", "<", "1", ")", "{", "return", "null", ";", "}", "// Otherwsise define combination array and determine complement", "int", "[", "]", "complement", "=", "new", "int", "[", "size", "]", ";", "int", "index", "=", "0", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "fullset", ".", "length", ";", "i", "++", ")", "{", "int", "item", "=", "fullset", "[", "i", "]", ";", "boolean", "member", "=", "false", ";", "for", "(", "int", "j", "=", "0", ";", "j", "<", "subset", ".", "length", ";", "j", "++", ")", "{", "if", "(", "item", "==", "subset", "[", "j", "]", ")", "{", "member", "=", "true", ";", "break", ";", "}", "}", "if", "(", "!", "member", ")", "{", "complement", "[", "index", "++", "]", "=", "item", ";", "}", "}", "return", "complement", ";", "}" ]
Returns the complement of subset.
[ "Returns", "the", "complement", "of", "subset", "." ]
e27e43e90fbaacce3f99d30120cf9dd6a764c33d
https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/core/src/main/java/smile/association/ARM.java#L215-L243
17,130
haifengl/smile
core/src/main/java/smile/association/ARM.java
ARM.getPowerSet
private static int[][] getPowerSet(int[] set) { int[][] sets = new int[getPowerSetSize(set.length)][]; getPowerSet(set, 0, null, sets, 0); return sets; }
java
private static int[][] getPowerSet(int[] set) { int[][] sets = new int[getPowerSetSize(set.length)][]; getPowerSet(set, 0, null, sets, 0); return sets; }
[ "private", "static", "int", "[", "]", "[", "]", "getPowerSet", "(", "int", "[", "]", "set", ")", "{", "int", "[", "]", "[", "]", "sets", "=", "new", "int", "[", "getPowerSetSize", "(", "set", ".", "length", ")", "]", "[", "", "]", ";", "getPowerSet", "(", "set", ",", "0", ",", "null", ",", "sets", ",", "0", ")", ";", "return", "sets", ";", "}" ]
Returns all possible subsets except null and full set.
[ "Returns", "all", "possible", "subsets", "except", "null", "and", "full", "set", "." ]
e27e43e90fbaacce3f99d30120cf9dd6a764c33d
https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/core/src/main/java/smile/association/ARM.java#L248-L252
17,131
haifengl/smile
core/src/main/java/smile/association/ARM.java
ARM.getPowerSet
private static int getPowerSet(int[] set, int inputIndex, int[] sofar, int[][] sets, int outputIndex) { for (int i = inputIndex; i < set.length; i++) { int n = sofar == null ? 0 : sofar.length; if (n < set.length-1) { int[] subset = new int[n + 1]; subset[n] = set[i]; if (sofar != null) { System.arraycopy(sofar, 0, subset, 0, n); } sets[outputIndex] = subset; outputIndex = getPowerSet(set, i + 1, subset, sets, outputIndex + 1); } } return outputIndex; }
java
private static int getPowerSet(int[] set, int inputIndex, int[] sofar, int[][] sets, int outputIndex) { for (int i = inputIndex; i < set.length; i++) { int n = sofar == null ? 0 : sofar.length; if (n < set.length-1) { int[] subset = new int[n + 1]; subset[n] = set[i]; if (sofar != null) { System.arraycopy(sofar, 0, subset, 0, n); } sets[outputIndex] = subset; outputIndex = getPowerSet(set, i + 1, subset, sets, outputIndex + 1); } } return outputIndex; }
[ "private", "static", "int", "getPowerSet", "(", "int", "[", "]", "set", ",", "int", "inputIndex", ",", "int", "[", "]", "sofar", ",", "int", "[", "]", "[", "]", "sets", ",", "int", "outputIndex", ")", "{", "for", "(", "int", "i", "=", "inputIndex", ";", "i", "<", "set", ".", "length", ";", "i", "++", ")", "{", "int", "n", "=", "sofar", "==", "null", "?", "0", ":", "sofar", ".", "length", ";", "if", "(", "n", "<", "set", ".", "length", "-", "1", ")", "{", "int", "[", "]", "subset", "=", "new", "int", "[", "n", "+", "1", "]", ";", "subset", "[", "n", "]", "=", "set", "[", "i", "]", ";", "if", "(", "sofar", "!=", "null", ")", "{", "System", ".", "arraycopy", "(", "sofar", ",", "0", ",", "subset", ",", "0", ",", "n", ")", ";", "}", "sets", "[", "outputIndex", "]", "=", "subset", ";", "outputIndex", "=", "getPowerSet", "(", "set", ",", "i", "+", "1", ",", "subset", ",", "sets", ",", "outputIndex", "+", "1", ")", ";", "}", "}", "return", "outputIndex", ";", "}" ]
Recursively calculates all possible subsets. @param set the input item set. @param inputIndex the index within the input set marking current element under consideration (0 at start). @param sofar the current combination determined sofar during the recursion (null at start). @param sets the power set to store all combinations when recursion ends. @param outputIndex the current location in the output set. @return revised output index.
[ "Recursively", "calculates", "all", "possible", "subsets", "." ]
e27e43e90fbaacce3f99d30120cf9dd6a764c33d
https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/core/src/main/java/smile/association/ARM.java#L265-L281
17,132
haifengl/smile
math/src/main/java/smile/math/special/Beta.java
Beta.incompleteFractionSummation
private static double incompleteFractionSummation(double alpha, double beta, double x) { final int MAXITER = 500; final double EPS = 3.0E-7; double aplusb = alpha + beta; double aplus1 = alpha + 1.0; double aminus1 = alpha - 1.0; double c = 1.0; double d = 1.0 - aplusb * x / aplus1; if (Math.abs(d) < FPMIN) { d = FPMIN; } d = 1.0 / d; double h = d; double aa = 0.0; double del = 0.0; int i = 1, i2 = 0; boolean test = true; while (test) { i2 = 2 * i; aa = i * (beta - i) * x / ((aminus1 + i2) * (alpha + i2)); d = 1.0 + aa * d; if (Math.abs(d) < FPMIN) { d = FPMIN; } c = 1.0 + aa / c; if (Math.abs(c) < FPMIN) { c = FPMIN; } d = 1.0 / d; h *= d * c; aa = -(alpha + i) * (aplusb + i) * x / ((alpha + i2) * (aplus1 + i2)); d = 1.0 + aa * d; if (Math.abs(d) < FPMIN) { d = FPMIN; } c = 1.0 + aa / c; if (Math.abs(c) < FPMIN) { c = FPMIN; } d = 1.0 / d; del = d * c; h *= del; i++; if (Math.abs(del - 1.0) < EPS) { test = false; } if (i > MAXITER) { test = false; logger.error("Beta.incompleteFractionSummation: Maximum number of iterations wes exceeded"); } } return h; }
java
private static double incompleteFractionSummation(double alpha, double beta, double x) { final int MAXITER = 500; final double EPS = 3.0E-7; double aplusb = alpha + beta; double aplus1 = alpha + 1.0; double aminus1 = alpha - 1.0; double c = 1.0; double d = 1.0 - aplusb * x / aplus1; if (Math.abs(d) < FPMIN) { d = FPMIN; } d = 1.0 / d; double h = d; double aa = 0.0; double del = 0.0; int i = 1, i2 = 0; boolean test = true; while (test) { i2 = 2 * i; aa = i * (beta - i) * x / ((aminus1 + i2) * (alpha + i2)); d = 1.0 + aa * d; if (Math.abs(d) < FPMIN) { d = FPMIN; } c = 1.0 + aa / c; if (Math.abs(c) < FPMIN) { c = FPMIN; } d = 1.0 / d; h *= d * c; aa = -(alpha + i) * (aplusb + i) * x / ((alpha + i2) * (aplus1 + i2)); d = 1.0 + aa * d; if (Math.abs(d) < FPMIN) { d = FPMIN; } c = 1.0 + aa / c; if (Math.abs(c) < FPMIN) { c = FPMIN; } d = 1.0 / d; del = d * c; h *= del; i++; if (Math.abs(del - 1.0) < EPS) { test = false; } if (i > MAXITER) { test = false; logger.error("Beta.incompleteFractionSummation: Maximum number of iterations wes exceeded"); } } return h; }
[ "private", "static", "double", "incompleteFractionSummation", "(", "double", "alpha", ",", "double", "beta", ",", "double", "x", ")", "{", "final", "int", "MAXITER", "=", "500", ";", "final", "double", "EPS", "=", "3.0E-7", ";", "double", "aplusb", "=", "alpha", "+", "beta", ";", "double", "aplus1", "=", "alpha", "+", "1.0", ";", "double", "aminus1", "=", "alpha", "-", "1.0", ";", "double", "c", "=", "1.0", ";", "double", "d", "=", "1.0", "-", "aplusb", "*", "x", "/", "aplus1", ";", "if", "(", "Math", ".", "abs", "(", "d", ")", "<", "FPMIN", ")", "{", "d", "=", "FPMIN", ";", "}", "d", "=", "1.0", "/", "d", ";", "double", "h", "=", "d", ";", "double", "aa", "=", "0.0", ";", "double", "del", "=", "0.0", ";", "int", "i", "=", "1", ",", "i2", "=", "0", ";", "boolean", "test", "=", "true", ";", "while", "(", "test", ")", "{", "i2", "=", "2", "*", "i", ";", "aa", "=", "i", "*", "(", "beta", "-", "i", ")", "*", "x", "/", "(", "(", "aminus1", "+", "i2", ")", "*", "(", "alpha", "+", "i2", ")", ")", ";", "d", "=", "1.0", "+", "aa", "*", "d", ";", "if", "(", "Math", ".", "abs", "(", "d", ")", "<", "FPMIN", ")", "{", "d", "=", "FPMIN", ";", "}", "c", "=", "1.0", "+", "aa", "/", "c", ";", "if", "(", "Math", ".", "abs", "(", "c", ")", "<", "FPMIN", ")", "{", "c", "=", "FPMIN", ";", "}", "d", "=", "1.0", "/", "d", ";", "h", "*=", "d", "*", "c", ";", "aa", "=", "-", "(", "alpha", "+", "i", ")", "*", "(", "aplusb", "+", "i", ")", "*", "x", "/", "(", "(", "alpha", "+", "i2", ")", "*", "(", "aplus1", "+", "i2", ")", ")", ";", "d", "=", "1.0", "+", "aa", "*", "d", ";", "if", "(", "Math", ".", "abs", "(", "d", ")", "<", "FPMIN", ")", "{", "d", "=", "FPMIN", ";", "}", "c", "=", "1.0", "+", "aa", "/", "c", ";", "if", "(", "Math", ".", "abs", "(", "c", ")", "<", "FPMIN", ")", "{", "c", "=", "FPMIN", ";", "}", "d", "=", "1.0", "/", "d", ";", "del", "=", "d", "*", "c", ";", "h", "*=", "del", ";", "i", "++", ";", "if", "(", "Math", ".", "abs", "(", "del", "-", "1.0", ")", "<", "EPS", ")", "{", "test", "=", "false", ";", "}", "if", "(", "i", ">", "MAXITER", ")", "{", "test", "=", "false", ";", "logger", ".", "error", "(", "\"Beta.incompleteFractionSummation: Maximum number of iterations wes exceeded\"", ")", ";", "}", "}", "return", "h", ";", "}" ]
Incomplete fraction summation used in the method regularizedIncompleteBeta using a modified Lentz's method.
[ "Incomplete", "fraction", "summation", "used", "in", "the", "method", "regularizedIncompleteBeta", "using", "a", "modified", "Lentz", "s", "method", "." ]
e27e43e90fbaacce3f99d30120cf9dd6a764c33d
https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/math/src/main/java/smile/math/special/Beta.java#L86-L139
17,133
haifengl/smile
core/src/main/java/smile/manifold/TSNE.java
TSNE.expd
private double[][] expd(double[][] D, double perplexity, double tol) { int n = D.length; double[][] P = new double[n][n]; double[] DiSum = Math.rowSums(D); int nprocs = MulticoreExecutor.getThreadPoolSize(); int chunk = n / nprocs; List<PerplexityTask> tasks = new ArrayList<>(); for (int i = 0; i < nprocs; i++) { int start = i * chunk; int end = i == nprocs-1 ? n : (i+1) * chunk; PerplexityTask task = new PerplexityTask(start, end, D, P, DiSum, perplexity, tol); tasks.add(task); } try { MulticoreExecutor.run(tasks); } catch (Exception e) { logger.error("t-SNE Gaussian kernel width search task fails: {}", e); } return P; }
java
private double[][] expd(double[][] D, double perplexity, double tol) { int n = D.length; double[][] P = new double[n][n]; double[] DiSum = Math.rowSums(D); int nprocs = MulticoreExecutor.getThreadPoolSize(); int chunk = n / nprocs; List<PerplexityTask> tasks = new ArrayList<>(); for (int i = 0; i < nprocs; i++) { int start = i * chunk; int end = i == nprocs-1 ? n : (i+1) * chunk; PerplexityTask task = new PerplexityTask(start, end, D, P, DiSum, perplexity, tol); tasks.add(task); } try { MulticoreExecutor.run(tasks); } catch (Exception e) { logger.error("t-SNE Gaussian kernel width search task fails: {}", e); } return P; }
[ "private", "double", "[", "]", "[", "]", "expd", "(", "double", "[", "]", "[", "]", "D", ",", "double", "perplexity", ",", "double", "tol", ")", "{", "int", "n", "=", "D", ".", "length", ";", "double", "[", "]", "[", "]", "P", "=", "new", "double", "[", "n", "]", "[", "n", "]", ";", "double", "[", "]", "DiSum", "=", "Math", ".", "rowSums", "(", "D", ")", ";", "int", "nprocs", "=", "MulticoreExecutor", ".", "getThreadPoolSize", "(", ")", ";", "int", "chunk", "=", "n", "/", "nprocs", ";", "List", "<", "PerplexityTask", ">", "tasks", "=", "new", "ArrayList", "<>", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "nprocs", ";", "i", "++", ")", "{", "int", "start", "=", "i", "*", "chunk", ";", "int", "end", "=", "i", "==", "nprocs", "-", "1", "?", "n", ":", "(", "i", "+", "1", ")", "*", "chunk", ";", "PerplexityTask", "task", "=", "new", "PerplexityTask", "(", "start", ",", "end", ",", "D", ",", "P", ",", "DiSum", ",", "perplexity", ",", "tol", ")", ";", "tasks", ".", "add", "(", "task", ")", ";", "}", "try", "{", "MulticoreExecutor", ".", "run", "(", "tasks", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "logger", ".", "error", "(", "\"t-SNE Gaussian kernel width search task fails: {}\"", ",", "e", ")", ";", "}", "return", "P", ";", "}" ]
Compute the Gaussian kernel (search the width for given perplexity.
[ "Compute", "the", "Gaussian", "kernel", "(", "search", "the", "width", "for", "given", "perplexity", "." ]
e27e43e90fbaacce3f99d30120cf9dd6a764c33d
https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/core/src/main/java/smile/manifold/TSNE.java#L278-L300
17,134
haifengl/smile
core/src/main/java/smile/neighbor/KDTree.java
KDTree.buildNode
private Node buildNode(int begin, int end) { int d = keys[0].length; // Allocate the node Node node = new Node(); // Fill in basic info node.count = end - begin; node.index = begin; // Calculate the bounding box double[] lowerBound = new double[d]; double[] upperBound = new double[d]; for (int i = 0; i < d; i++) { lowerBound[i] = keys[index[begin]][i]; upperBound[i] = keys[index[begin]][i]; } for (int i = begin + 1; i < end; i++) { for (int j = 0; j < d; j++) { double c = keys[index[i]][j]; if (lowerBound[j] > c) { lowerBound[j] = c; } if (upperBound[j] < c) { upperBound[j] = c; } } } // Calculate bounding box stats double maxRadius = -1; for (int i = 0; i < d; i++) { double radius = (upperBound[i] - lowerBound[i]) / 2; if (radius > maxRadius) { maxRadius = radius; node.split = i; node.cutoff = (upperBound[i] + lowerBound[i]) / 2; } } // If the max spread is 0, make this a leaf node if (maxRadius == 0) { node.lower = node.upper = null; return node; } // Partition the dataset around the midpoint in this dimension. The // partitioning is done in-place by iterating from left-to-right and // right-to-left in the same way that partioning is done in quicksort. int i1 = begin, i2 = end - 1, size = 0; while (i1 <= i2) { boolean i1Good = (keys[index[i1]][node.split] < node.cutoff); boolean i2Good = (keys[index[i2]][node.split] >= node.cutoff); if (!i1Good && !i2Good) { int temp = index[i1]; index[i1] = index[i2]; index[i2] = temp; i1Good = i2Good = true; } if (i1Good) { i1++; size++; } if (i2Good) { i2--; } } // Create the child nodes node.lower = buildNode(begin, begin + size); node.upper = buildNode(begin + size, end); return node; }
java
private Node buildNode(int begin, int end) { int d = keys[0].length; // Allocate the node Node node = new Node(); // Fill in basic info node.count = end - begin; node.index = begin; // Calculate the bounding box double[] lowerBound = new double[d]; double[] upperBound = new double[d]; for (int i = 0; i < d; i++) { lowerBound[i] = keys[index[begin]][i]; upperBound[i] = keys[index[begin]][i]; } for (int i = begin + 1; i < end; i++) { for (int j = 0; j < d; j++) { double c = keys[index[i]][j]; if (lowerBound[j] > c) { lowerBound[j] = c; } if (upperBound[j] < c) { upperBound[j] = c; } } } // Calculate bounding box stats double maxRadius = -1; for (int i = 0; i < d; i++) { double radius = (upperBound[i] - lowerBound[i]) / 2; if (radius > maxRadius) { maxRadius = radius; node.split = i; node.cutoff = (upperBound[i] + lowerBound[i]) / 2; } } // If the max spread is 0, make this a leaf node if (maxRadius == 0) { node.lower = node.upper = null; return node; } // Partition the dataset around the midpoint in this dimension. The // partitioning is done in-place by iterating from left-to-right and // right-to-left in the same way that partioning is done in quicksort. int i1 = begin, i2 = end - 1, size = 0; while (i1 <= i2) { boolean i1Good = (keys[index[i1]][node.split] < node.cutoff); boolean i2Good = (keys[index[i2]][node.split] >= node.cutoff); if (!i1Good && !i2Good) { int temp = index[i1]; index[i1] = index[i2]; index[i2] = temp; i1Good = i2Good = true; } if (i1Good) { i1++; size++; } if (i2Good) { i2--; } } // Create the child nodes node.lower = buildNode(begin, begin + size); node.upper = buildNode(begin + size, end); return node; }
[ "private", "Node", "buildNode", "(", "int", "begin", ",", "int", "end", ")", "{", "int", "d", "=", "keys", "[", "0", "]", ".", "length", ";", "// Allocate the node", "Node", "node", "=", "new", "Node", "(", ")", ";", "// Fill in basic info", "node", ".", "count", "=", "end", "-", "begin", ";", "node", ".", "index", "=", "begin", ";", "// Calculate the bounding box", "double", "[", "]", "lowerBound", "=", "new", "double", "[", "d", "]", ";", "double", "[", "]", "upperBound", "=", "new", "double", "[", "d", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "d", ";", "i", "++", ")", "{", "lowerBound", "[", "i", "]", "=", "keys", "[", "index", "[", "begin", "]", "]", "[", "i", "]", ";", "upperBound", "[", "i", "]", "=", "keys", "[", "index", "[", "begin", "]", "]", "[", "i", "]", ";", "}", "for", "(", "int", "i", "=", "begin", "+", "1", ";", "i", "<", "end", ";", "i", "++", ")", "{", "for", "(", "int", "j", "=", "0", ";", "j", "<", "d", ";", "j", "++", ")", "{", "double", "c", "=", "keys", "[", "index", "[", "i", "]", "]", "[", "j", "]", ";", "if", "(", "lowerBound", "[", "j", "]", ">", "c", ")", "{", "lowerBound", "[", "j", "]", "=", "c", ";", "}", "if", "(", "upperBound", "[", "j", "]", "<", "c", ")", "{", "upperBound", "[", "j", "]", "=", "c", ";", "}", "}", "}", "// Calculate bounding box stats", "double", "maxRadius", "=", "-", "1", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "d", ";", "i", "++", ")", "{", "double", "radius", "=", "(", "upperBound", "[", "i", "]", "-", "lowerBound", "[", "i", "]", ")", "/", "2", ";", "if", "(", "radius", ">", "maxRadius", ")", "{", "maxRadius", "=", "radius", ";", "node", ".", "split", "=", "i", ";", "node", ".", "cutoff", "=", "(", "upperBound", "[", "i", "]", "+", "lowerBound", "[", "i", "]", ")", "/", "2", ";", "}", "}", "// If the max spread is 0, make this a leaf node", "if", "(", "maxRadius", "==", "0", ")", "{", "node", ".", "lower", "=", "node", ".", "upper", "=", "null", ";", "return", "node", ";", "}", "// Partition the dataset around the midpoint in this dimension. The", "// partitioning is done in-place by iterating from left-to-right and", "// right-to-left in the same way that partioning is done in quicksort.", "int", "i1", "=", "begin", ",", "i2", "=", "end", "-", "1", ",", "size", "=", "0", ";", "while", "(", "i1", "<=", "i2", ")", "{", "boolean", "i1Good", "=", "(", "keys", "[", "index", "[", "i1", "]", "]", "[", "node", ".", "split", "]", "<", "node", ".", "cutoff", ")", ";", "boolean", "i2Good", "=", "(", "keys", "[", "index", "[", "i2", "]", "]", "[", "node", ".", "split", "]", ">=", "node", ".", "cutoff", ")", ";", "if", "(", "!", "i1Good", "&&", "!", "i2Good", ")", "{", "int", "temp", "=", "index", "[", "i1", "]", ";", "index", "[", "i1", "]", "=", "index", "[", "i2", "]", ";", "index", "[", "i2", "]", "=", "temp", ";", "i1Good", "=", "i2Good", "=", "true", ";", "}", "if", "(", "i1Good", ")", "{", "i1", "++", ";", "size", "++", ";", "}", "if", "(", "i2Good", ")", "{", "i2", "--", ";", "}", "}", "// Create the child nodes", "node", ".", "lower", "=", "buildNode", "(", "begin", ",", "begin", "+", "size", ")", ";", "node", ".", "upper", "=", "buildNode", "(", "begin", "+", "size", ",", "end", ")", ";", "return", "node", ";", "}" ]
Build a k-d tree from the given set of dataset.
[ "Build", "a", "k", "-", "d", "tree", "from", "the", "given", "set", "of", "dataset", "." ]
e27e43e90fbaacce3f99d30120cf9dd6a764c33d
https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/core/src/main/java/smile/neighbor/KDTree.java#L157-L235
17,135
haifengl/smile
core/src/main/java/smile/neighbor/KDTree.java
KDTree.search
private void search(double[] q, Node node, Neighbor<double[], E> neighbor) { if (node.isLeaf()) { // look at all the instances in this leaf for (int idx = node.index; idx < node.index + node.count; idx++) { if (q == keys[index[idx]] && identicalExcluded) { continue; } double distance = Math.squaredDistance(q, keys[index[idx]]); if (distance < neighbor.distance) { neighbor.key = keys[index[idx]]; neighbor.value = data[index[idx]]; neighbor.index = index[idx]; neighbor.distance = distance; } } } else { Node nearer, further; double diff = q[node.split] - node.cutoff; if (diff < 0) { nearer = node.lower; further = node.upper; } else { nearer = node.upper; further = node.lower; } search(q, nearer, neighbor); // now look in further half if (neighbor.distance >= diff * diff) { search(q, further, neighbor); } } }
java
private void search(double[] q, Node node, Neighbor<double[], E> neighbor) { if (node.isLeaf()) { // look at all the instances in this leaf for (int idx = node.index; idx < node.index + node.count; idx++) { if (q == keys[index[idx]] && identicalExcluded) { continue; } double distance = Math.squaredDistance(q, keys[index[idx]]); if (distance < neighbor.distance) { neighbor.key = keys[index[idx]]; neighbor.value = data[index[idx]]; neighbor.index = index[idx]; neighbor.distance = distance; } } } else { Node nearer, further; double diff = q[node.split] - node.cutoff; if (diff < 0) { nearer = node.lower; further = node.upper; } else { nearer = node.upper; further = node.lower; } search(q, nearer, neighbor); // now look in further half if (neighbor.distance >= diff * diff) { search(q, further, neighbor); } } }
[ "private", "void", "search", "(", "double", "[", "]", "q", ",", "Node", "node", ",", "Neighbor", "<", "double", "[", "]", ",", "E", ">", "neighbor", ")", "{", "if", "(", "node", ".", "isLeaf", "(", ")", ")", "{", "// look at all the instances in this leaf", "for", "(", "int", "idx", "=", "node", ".", "index", ";", "idx", "<", "node", ".", "index", "+", "node", ".", "count", ";", "idx", "++", ")", "{", "if", "(", "q", "==", "keys", "[", "index", "[", "idx", "]", "]", "&&", "identicalExcluded", ")", "{", "continue", ";", "}", "double", "distance", "=", "Math", ".", "squaredDistance", "(", "q", ",", "keys", "[", "index", "[", "idx", "]", "]", ")", ";", "if", "(", "distance", "<", "neighbor", ".", "distance", ")", "{", "neighbor", ".", "key", "=", "keys", "[", "index", "[", "idx", "]", "]", ";", "neighbor", ".", "value", "=", "data", "[", "index", "[", "idx", "]", "]", ";", "neighbor", ".", "index", "=", "index", "[", "idx", "]", ";", "neighbor", ".", "distance", "=", "distance", ";", "}", "}", "}", "else", "{", "Node", "nearer", ",", "further", ";", "double", "diff", "=", "q", "[", "node", ".", "split", "]", "-", "node", ".", "cutoff", ";", "if", "(", "diff", "<", "0", ")", "{", "nearer", "=", "node", ".", "lower", ";", "further", "=", "node", ".", "upper", ";", "}", "else", "{", "nearer", "=", "node", ".", "upper", ";", "further", "=", "node", ".", "lower", ";", "}", "search", "(", "q", ",", "nearer", ",", "neighbor", ")", ";", "// now look in further half", "if", "(", "neighbor", ".", "distance", ">=", "diff", "*", "diff", ")", "{", "search", "(", "q", ",", "further", ",", "neighbor", ")", ";", "}", "}", "}" ]
Returns the nearest neighbors of the given target starting from the give tree node. @param q the query key. @param node the root of subtree. @param neighbor the current nearest neighbor.
[ "Returns", "the", "nearest", "neighbors", "of", "the", "given", "target", "starting", "from", "the", "give", "tree", "node", "." ]
e27e43e90fbaacce3f99d30120cf9dd6a764c33d
https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/core/src/main/java/smile/neighbor/KDTree.java#L260-L294
17,136
haifengl/smile
core/src/main/java/smile/neighbor/KDTree.java
KDTree.search
private void search(double[] q, Node node, double radius, List<Neighbor<double[], E>> neighbors) { if (node.isLeaf()) { // look at all the instances in this leaf for (int idx = node.index; idx < node.index + node.count; idx++) { if (q == keys[index[idx]] && identicalExcluded) { continue; } double distance = Math.distance(q, keys[index[idx]]); if (distance <= radius) { neighbors.add(new Neighbor<>(keys[index[idx]], data[index[idx]], index[idx], distance)); } } } else { Node nearer, further; double diff = q[node.split] - node.cutoff; if (diff < 0) { nearer = node.lower; further = node.upper; } else { nearer = node.upper; further = node.lower; } search(q, nearer, radius, neighbors); // now look in further half if (radius >= Math.abs(diff)) { search(q, further, radius, neighbors); } } }
java
private void search(double[] q, Node node, double radius, List<Neighbor<double[], E>> neighbors) { if (node.isLeaf()) { // look at all the instances in this leaf for (int idx = node.index; idx < node.index + node.count; idx++) { if (q == keys[index[idx]] && identicalExcluded) { continue; } double distance = Math.distance(q, keys[index[idx]]); if (distance <= radius) { neighbors.add(new Neighbor<>(keys[index[idx]], data[index[idx]], index[idx], distance)); } } } else { Node nearer, further; double diff = q[node.split] - node.cutoff; if (diff < 0) { nearer = node.lower; further = node.upper; } else { nearer = node.upper; further = node.lower; } search(q, nearer, radius, neighbors); // now look in further half if (radius >= Math.abs(diff)) { search(q, further, radius, neighbors); } } }
[ "private", "void", "search", "(", "double", "[", "]", "q", ",", "Node", "node", ",", "double", "radius", ",", "List", "<", "Neighbor", "<", "double", "[", "]", ",", "E", ">", ">", "neighbors", ")", "{", "if", "(", "node", ".", "isLeaf", "(", ")", ")", "{", "// look at all the instances in this leaf", "for", "(", "int", "idx", "=", "node", ".", "index", ";", "idx", "<", "node", ".", "index", "+", "node", ".", "count", ";", "idx", "++", ")", "{", "if", "(", "q", "==", "keys", "[", "index", "[", "idx", "]", "]", "&&", "identicalExcluded", ")", "{", "continue", ";", "}", "double", "distance", "=", "Math", ".", "distance", "(", "q", ",", "keys", "[", "index", "[", "idx", "]", "]", ")", ";", "if", "(", "distance", "<=", "radius", ")", "{", "neighbors", ".", "add", "(", "new", "Neighbor", "<>", "(", "keys", "[", "index", "[", "idx", "]", "]", ",", "data", "[", "index", "[", "idx", "]", "]", ",", "index", "[", "idx", "]", ",", "distance", ")", ")", ";", "}", "}", "}", "else", "{", "Node", "nearer", ",", "further", ";", "double", "diff", "=", "q", "[", "node", ".", "split", "]", "-", "node", ".", "cutoff", ";", "if", "(", "diff", "<", "0", ")", "{", "nearer", "=", "node", ".", "lower", ";", "further", "=", "node", ".", "upper", ";", "}", "else", "{", "nearer", "=", "node", ".", "upper", ";", "further", "=", "node", ".", "lower", ";", "}", "search", "(", "q", ",", "nearer", ",", "radius", ",", "neighbors", ")", ";", "// now look in further half", "if", "(", "radius", ">=", "Math", ".", "abs", "(", "diff", ")", ")", "{", "search", "(", "q", ",", "further", ",", "radius", ",", "neighbors", ")", ";", "}", "}", "}" ]
Returns the neighbors in the given range of search target from the give tree node. @param q the query key. @param node the root of subtree. @param radius the radius of search range from target. @param neighbors the list of found neighbors in the range.
[ "Returns", "the", "neighbors", "in", "the", "given", "range", "of", "search", "target", "from", "the", "give", "tree", "node", "." ]
e27e43e90fbaacce3f99d30120cf9dd6a764c33d
https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/core/src/main/java/smile/neighbor/KDTree.java#L352-L383
17,137
haifengl/smile
math/src/main/java/smile/math/matrix/Cholesky.java
Cholesky.inverse
public DenseMatrix inverse() { int n = L.nrows(); DenseMatrix inv = Matrix.eye(n); solve(inv); return inv; }
java
public DenseMatrix inverse() { int n = L.nrows(); DenseMatrix inv = Matrix.eye(n); solve(inv); return inv; }
[ "public", "DenseMatrix", "inverse", "(", ")", "{", "int", "n", "=", "L", ".", "nrows", "(", ")", ";", "DenseMatrix", "inv", "=", "Matrix", ".", "eye", "(", "n", ")", ";", "solve", "(", "inv", ")", ";", "return", "inv", ";", "}" ]
Returns the matrix inverse.
[ "Returns", "the", "matrix", "inverse", "." ]
e27e43e90fbaacce3f99d30120cf9dd6a764c33d
https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/math/src/main/java/smile/math/matrix/Cholesky.java#L88-L93
17,138
haifengl/smile
plot/src/main/java/smile/swing/table/TableCopyPasteAdapter.java
TableCopyPasteAdapter.actionPerformed
@Override public void actionPerformed(ActionEvent e) { if (e.getActionCommand().compareTo("Copy") == 0) { StringBuilder sbf = new StringBuilder(); // Check to ensure we have selected only a contiguous block of // cells int numcols = table.getSelectedColumnCount(); int numrows = table.getSelectedRowCount(); int[] rowsselected = table.getSelectedRows(); int[] colsselected = table.getSelectedColumns(); if (!((numrows - 1 == rowsselected[rowsselected.length - 1] - rowsselected[0] && numrows == rowsselected.length) && (numcols - 1 == colsselected[colsselected.length - 1] - colsselected[0] && numcols == colsselected.length))) { JOptionPane.showMessageDialog(null, "Invalid Copy Selection", "Invalid Copy Selection", JOptionPane.ERROR_MESSAGE); return; } for (int i = 0; i < numrows; i++) { for (int j = 0; j < numcols; j++) { sbf.append(table.getValueAt(rowsselected[i], colsselected[j])); if (j < numcols - 1) { sbf.append("\t"); } } sbf.append("\n"); } stsel = new StringSelection(sbf.toString()); system = Toolkit.getDefaultToolkit().getSystemClipboard(); system.setContents(stsel, stsel); } if (e.getActionCommand().compareTo("Paste") == 0) { LOGGER.log(Level.FINE, "Trying to Paste"); int startRow = (table.getSelectedRows())[0]; int startCol = (table.getSelectedColumns())[0]; try { String trstring = (String) (system.getContents(this).getTransferData(DataFlavor.stringFlavor)); StringTokenizer st1 = new StringTokenizer(trstring, "\n"); for (int i = 0; st1.hasMoreTokens(); i++) { rowstring = st1.nextToken(); StringTokenizer st2 = new StringTokenizer(rowstring, "\t"); for (int j = 0; st2.hasMoreTokens(); j++) { value = (String) st2.nextToken(); if (startRow + i < table.getRowCount() && startCol + j < table.getColumnCount()) { table.setValueAt(value, startRow + i, startCol + j); } } } } catch (Exception ex) { } } }
java
@Override public void actionPerformed(ActionEvent e) { if (e.getActionCommand().compareTo("Copy") == 0) { StringBuilder sbf = new StringBuilder(); // Check to ensure we have selected only a contiguous block of // cells int numcols = table.getSelectedColumnCount(); int numrows = table.getSelectedRowCount(); int[] rowsselected = table.getSelectedRows(); int[] colsselected = table.getSelectedColumns(); if (!((numrows - 1 == rowsselected[rowsselected.length - 1] - rowsselected[0] && numrows == rowsselected.length) && (numcols - 1 == colsselected[colsselected.length - 1] - colsselected[0] && numcols == colsselected.length))) { JOptionPane.showMessageDialog(null, "Invalid Copy Selection", "Invalid Copy Selection", JOptionPane.ERROR_MESSAGE); return; } for (int i = 0; i < numrows; i++) { for (int j = 0; j < numcols; j++) { sbf.append(table.getValueAt(rowsselected[i], colsselected[j])); if (j < numcols - 1) { sbf.append("\t"); } } sbf.append("\n"); } stsel = new StringSelection(sbf.toString()); system = Toolkit.getDefaultToolkit().getSystemClipboard(); system.setContents(stsel, stsel); } if (e.getActionCommand().compareTo("Paste") == 0) { LOGGER.log(Level.FINE, "Trying to Paste"); int startRow = (table.getSelectedRows())[0]; int startCol = (table.getSelectedColumns())[0]; try { String trstring = (String) (system.getContents(this).getTransferData(DataFlavor.stringFlavor)); StringTokenizer st1 = new StringTokenizer(trstring, "\n"); for (int i = 0; st1.hasMoreTokens(); i++) { rowstring = st1.nextToken(); StringTokenizer st2 = new StringTokenizer(rowstring, "\t"); for (int j = 0; st2.hasMoreTokens(); j++) { value = (String) st2.nextToken(); if (startRow + i < table.getRowCount() && startCol + j < table.getColumnCount()) { table.setValueAt(value, startRow + i, startCol + j); } } } } catch (Exception ex) { } } }
[ "@", "Override", "public", "void", "actionPerformed", "(", "ActionEvent", "e", ")", "{", "if", "(", "e", ".", "getActionCommand", "(", ")", ".", "compareTo", "(", "\"Copy\"", ")", "==", "0", ")", "{", "StringBuilder", "sbf", "=", "new", "StringBuilder", "(", ")", ";", "// Check to ensure we have selected only a contiguous block of", "// cells", "int", "numcols", "=", "table", ".", "getSelectedColumnCount", "(", ")", ";", "int", "numrows", "=", "table", ".", "getSelectedRowCount", "(", ")", ";", "int", "[", "]", "rowsselected", "=", "table", ".", "getSelectedRows", "(", ")", ";", "int", "[", "]", "colsselected", "=", "table", ".", "getSelectedColumns", "(", ")", ";", "if", "(", "!", "(", "(", "numrows", "-", "1", "==", "rowsselected", "[", "rowsselected", ".", "length", "-", "1", "]", "-", "rowsselected", "[", "0", "]", "&&", "numrows", "==", "rowsselected", ".", "length", ")", "&&", "(", "numcols", "-", "1", "==", "colsselected", "[", "colsselected", ".", "length", "-", "1", "]", "-", "colsselected", "[", "0", "]", "&&", "numcols", "==", "colsselected", ".", "length", ")", ")", ")", "{", "JOptionPane", ".", "showMessageDialog", "(", "null", ",", "\"Invalid Copy Selection\"", ",", "\"Invalid Copy Selection\"", ",", "JOptionPane", ".", "ERROR_MESSAGE", ")", ";", "return", ";", "}", "for", "(", "int", "i", "=", "0", ";", "i", "<", "numrows", ";", "i", "++", ")", "{", "for", "(", "int", "j", "=", "0", ";", "j", "<", "numcols", ";", "j", "++", ")", "{", "sbf", ".", "append", "(", "table", ".", "getValueAt", "(", "rowsselected", "[", "i", "]", ",", "colsselected", "[", "j", "]", ")", ")", ";", "if", "(", "j", "<", "numcols", "-", "1", ")", "{", "sbf", ".", "append", "(", "\"\\t\"", ")", ";", "}", "}", "sbf", ".", "append", "(", "\"\\n\"", ")", ";", "}", "stsel", "=", "new", "StringSelection", "(", "sbf", ".", "toString", "(", ")", ")", ";", "system", "=", "Toolkit", ".", "getDefaultToolkit", "(", ")", ".", "getSystemClipboard", "(", ")", ";", "system", ".", "setContents", "(", "stsel", ",", "stsel", ")", ";", "}", "if", "(", "e", ".", "getActionCommand", "(", ")", ".", "compareTo", "(", "\"Paste\"", ")", "==", "0", ")", "{", "LOGGER", ".", "log", "(", "Level", ".", "FINE", ",", "\"Trying to Paste\"", ")", ";", "int", "startRow", "=", "(", "table", ".", "getSelectedRows", "(", ")", ")", "[", "0", "]", ";", "int", "startCol", "=", "(", "table", ".", "getSelectedColumns", "(", ")", ")", "[", "0", "]", ";", "try", "{", "String", "trstring", "=", "(", "String", ")", "(", "system", ".", "getContents", "(", "this", ")", ".", "getTransferData", "(", "DataFlavor", ".", "stringFlavor", ")", ")", ";", "StringTokenizer", "st1", "=", "new", "StringTokenizer", "(", "trstring", ",", "\"\\n\"", ")", ";", "for", "(", "int", "i", "=", "0", ";", "st1", ".", "hasMoreTokens", "(", ")", ";", "i", "++", ")", "{", "rowstring", "=", "st1", ".", "nextToken", "(", ")", ";", "StringTokenizer", "st2", "=", "new", "StringTokenizer", "(", "rowstring", ",", "\"\\t\"", ")", ";", "for", "(", "int", "j", "=", "0", ";", "st2", ".", "hasMoreTokens", "(", ")", ";", "j", "++", ")", "{", "value", "=", "(", "String", ")", "st2", ".", "nextToken", "(", ")", ";", "if", "(", "startRow", "+", "i", "<", "table", ".", "getRowCount", "(", ")", "&&", "startCol", "+", "j", "<", "table", ".", "getColumnCount", "(", ")", ")", "{", "table", ".", "setValueAt", "(", "value", ",", "startRow", "+", "i", ",", "startCol", "+", "j", ")", ";", "}", "}", "}", "}", "catch", "(", "Exception", "ex", ")", "{", "}", "}", "}" ]
This method is activated on the Keystrokes we are listening to in this implementation. Here it listens for Copy and Paste ActionCommands. Selections comprising non-adjacent cells result in invalid selection and then copy action cannot be performed. Paste is done by aligning the upper left corner of the selection with the 1st element in the current selection of the JTable.
[ "This", "method", "is", "activated", "on", "the", "Keystrokes", "we", "are", "listening", "to", "in", "this", "implementation", ".", "Here", "it", "listens", "for", "Copy", "and", "Paste", "ActionCommands", ".", "Selections", "comprising", "non", "-", "adjacent", "cells", "result", "in", "invalid", "selection", "and", "then", "copy", "action", "cannot", "be", "performed", ".", "Paste", "is", "done", "by", "aligning", "the", "upper", "left", "corner", "of", "the", "selection", "with", "the", "1st", "element", "in", "the", "current", "selection", "of", "the", "JTable", "." ]
e27e43e90fbaacce3f99d30120cf9dd6a764c33d
https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/plot/src/main/java/smile/swing/table/TableCopyPasteAdapter.java#L79-L133
17,139
haifengl/smile
nlp/src/main/java/smile/nlp/collocation/BigramCollocationFinder.java
BigramCollocationFinder.find
public BigramCollocation[] find(Corpus corpus, int k) { BigramCollocation[] bigrams = new BigramCollocation[k]; HeapSelect<BigramCollocation> heap = new HeapSelect<>(bigrams); Iterator<Bigram> iterator = corpus.getBigrams(); while (iterator.hasNext()) { Bigram bigram = iterator.next(); int c12 = corpus.getBigramFrequency(bigram); if (c12 > minFreq) { int c1 = corpus.getTermFrequency(bigram.w1); int c2 = corpus.getTermFrequency(bigram.w2); double score = likelihoodRatio(c1, c2, c12, corpus.size()); heap.add(new BigramCollocation(bigram.w1, bigram.w2, c12, -score)); } } heap.sort(); BigramCollocation[] collocations = new BigramCollocation[k]; for (int i = 0; i < k; i++) { BigramCollocation bigram = bigrams[k-i-1]; collocations[i] = new BigramCollocation(bigram.w1(), bigram.w2(), bigram.frequency(), -bigram.score()); } return collocations; }
java
public BigramCollocation[] find(Corpus corpus, int k) { BigramCollocation[] bigrams = new BigramCollocation[k]; HeapSelect<BigramCollocation> heap = new HeapSelect<>(bigrams); Iterator<Bigram> iterator = corpus.getBigrams(); while (iterator.hasNext()) { Bigram bigram = iterator.next(); int c12 = corpus.getBigramFrequency(bigram); if (c12 > minFreq) { int c1 = corpus.getTermFrequency(bigram.w1); int c2 = corpus.getTermFrequency(bigram.w2); double score = likelihoodRatio(c1, c2, c12, corpus.size()); heap.add(new BigramCollocation(bigram.w1, bigram.w2, c12, -score)); } } heap.sort(); BigramCollocation[] collocations = new BigramCollocation[k]; for (int i = 0; i < k; i++) { BigramCollocation bigram = bigrams[k-i-1]; collocations[i] = new BigramCollocation(bigram.w1(), bigram.w2(), bigram.frequency(), -bigram.score()); } return collocations; }
[ "public", "BigramCollocation", "[", "]", "find", "(", "Corpus", "corpus", ",", "int", "k", ")", "{", "BigramCollocation", "[", "]", "bigrams", "=", "new", "BigramCollocation", "[", "k", "]", ";", "HeapSelect", "<", "BigramCollocation", ">", "heap", "=", "new", "HeapSelect", "<>", "(", "bigrams", ")", ";", "Iterator", "<", "Bigram", ">", "iterator", "=", "corpus", ".", "getBigrams", "(", ")", ";", "while", "(", "iterator", ".", "hasNext", "(", ")", ")", "{", "Bigram", "bigram", "=", "iterator", ".", "next", "(", ")", ";", "int", "c12", "=", "corpus", ".", "getBigramFrequency", "(", "bigram", ")", ";", "if", "(", "c12", ">", "minFreq", ")", "{", "int", "c1", "=", "corpus", ".", "getTermFrequency", "(", "bigram", ".", "w1", ")", ";", "int", "c2", "=", "corpus", ".", "getTermFrequency", "(", "bigram", ".", "w2", ")", ";", "double", "score", "=", "likelihoodRatio", "(", "c1", ",", "c2", ",", "c12", ",", "corpus", ".", "size", "(", ")", ")", ";", "heap", ".", "add", "(", "new", "BigramCollocation", "(", "bigram", ".", "w1", ",", "bigram", ".", "w2", ",", "c12", ",", "-", "score", ")", ")", ";", "}", "}", "heap", ".", "sort", "(", ")", ";", "BigramCollocation", "[", "]", "collocations", "=", "new", "BigramCollocation", "[", "k", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "k", ";", "i", "++", ")", "{", "BigramCollocation", "bigram", "=", "bigrams", "[", "k", "-", "i", "-", "1", "]", ";", "collocations", "[", "i", "]", "=", "new", "BigramCollocation", "(", "bigram", ".", "w1", "(", ")", ",", "bigram", ".", "w2", "(", ")", ",", "bigram", ".", "frequency", "(", ")", ",", "-", "bigram", ".", "score", "(", ")", ")", ";", "}", "return", "collocations", ";", "}" ]
Finds top k bigram collocations in the given corpus. @return the array of significant bigram collocations in descending order of likelihood ratio.
[ "Finds", "top", "k", "bigram", "collocations", "in", "the", "given", "corpus", "." ]
e27e43e90fbaacce3f99d30120cf9dd6a764c33d
https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/nlp/src/main/java/smile/nlp/collocation/BigramCollocationFinder.java#L66-L93
17,140
haifengl/smile
nlp/src/main/java/smile/nlp/collocation/BigramCollocationFinder.java
BigramCollocationFinder.find
public BigramCollocation[] find(Corpus corpus, double p) { if (p <= 0.0 || p >= 1.0) { throw new IllegalArgumentException("Invalid p = " + p); } double cutoff = chisq.quantile(p); ArrayList<BigramCollocation> bigrams = new ArrayList<>(); Iterator<Bigram> iterator = corpus.getBigrams(); while (iterator.hasNext()) { Bigram bigram = iterator.next(); int c12 = corpus.getBigramFrequency(bigram); if (c12 > minFreq) { int c1 = corpus.getTermFrequency(bigram.w1); int c2 = corpus.getTermFrequency(bigram.w2); double score = likelihoodRatio(c1, c2, c12, corpus.size()); if (score > cutoff) { bigrams.add(new BigramCollocation(bigram.w1, bigram.w2, c12, score)); } } } int n = bigrams.size(); BigramCollocation[] collocations = new BigramCollocation[n]; for (int i = 0; i < n; i++) { collocations[i] = bigrams.get(i); } Arrays.sort(collocations); // Reverse to descending order for (int i = 0; i < n/2; i++) { BigramCollocation b = collocations[i]; collocations[i] = collocations[n-i-1]; collocations[n-i-1] = b; } return collocations; }
java
public BigramCollocation[] find(Corpus corpus, double p) { if (p <= 0.0 || p >= 1.0) { throw new IllegalArgumentException("Invalid p = " + p); } double cutoff = chisq.quantile(p); ArrayList<BigramCollocation> bigrams = new ArrayList<>(); Iterator<Bigram> iterator = corpus.getBigrams(); while (iterator.hasNext()) { Bigram bigram = iterator.next(); int c12 = corpus.getBigramFrequency(bigram); if (c12 > minFreq) { int c1 = corpus.getTermFrequency(bigram.w1); int c2 = corpus.getTermFrequency(bigram.w2); double score = likelihoodRatio(c1, c2, c12, corpus.size()); if (score > cutoff) { bigrams.add(new BigramCollocation(bigram.w1, bigram.w2, c12, score)); } } } int n = bigrams.size(); BigramCollocation[] collocations = new BigramCollocation[n]; for (int i = 0; i < n; i++) { collocations[i] = bigrams.get(i); } Arrays.sort(collocations); // Reverse to descending order for (int i = 0; i < n/2; i++) { BigramCollocation b = collocations[i]; collocations[i] = collocations[n-i-1]; collocations[n-i-1] = b; } return collocations; }
[ "public", "BigramCollocation", "[", "]", "find", "(", "Corpus", "corpus", ",", "double", "p", ")", "{", "if", "(", "p", "<=", "0.0", "||", "p", ">=", "1.0", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Invalid p = \"", "+", "p", ")", ";", "}", "double", "cutoff", "=", "chisq", ".", "quantile", "(", "p", ")", ";", "ArrayList", "<", "BigramCollocation", ">", "bigrams", "=", "new", "ArrayList", "<>", "(", ")", ";", "Iterator", "<", "Bigram", ">", "iterator", "=", "corpus", ".", "getBigrams", "(", ")", ";", "while", "(", "iterator", ".", "hasNext", "(", ")", ")", "{", "Bigram", "bigram", "=", "iterator", ".", "next", "(", ")", ";", "int", "c12", "=", "corpus", ".", "getBigramFrequency", "(", "bigram", ")", ";", "if", "(", "c12", ">", "minFreq", ")", "{", "int", "c1", "=", "corpus", ".", "getTermFrequency", "(", "bigram", ".", "w1", ")", ";", "int", "c2", "=", "corpus", ".", "getTermFrequency", "(", "bigram", ".", "w2", ")", ";", "double", "score", "=", "likelihoodRatio", "(", "c1", ",", "c2", ",", "c12", ",", "corpus", ".", "size", "(", ")", ")", ";", "if", "(", "score", ">", "cutoff", ")", "{", "bigrams", ".", "add", "(", "new", "BigramCollocation", "(", "bigram", ".", "w1", ",", "bigram", ".", "w2", ",", "c12", ",", "score", ")", ")", ";", "}", "}", "}", "int", "n", "=", "bigrams", ".", "size", "(", ")", ";", "BigramCollocation", "[", "]", "collocations", "=", "new", "BigramCollocation", "[", "n", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "n", ";", "i", "++", ")", "{", "collocations", "[", "i", "]", "=", "bigrams", ".", "get", "(", "i", ")", ";", "}", "Arrays", ".", "sort", "(", "collocations", ")", ";", "// Reverse to descending order", "for", "(", "int", "i", "=", "0", ";", "i", "<", "n", "/", "2", ";", "i", "++", ")", "{", "BigramCollocation", "b", "=", "collocations", "[", "i", "]", ";", "collocations", "[", "i", "]", "=", "collocations", "[", "n", "-", "i", "-", "1", "]", ";", "collocations", "[", "n", "-", "i", "-", "1", "]", "=", "b", ";", "}", "return", "collocations", ";", "}" ]
Finds bigram collocations in the given corpus whose p-value is less than the given threshold. @param p the p-value threshold @return the array of significant bigram collocations in descending order of likelihood ratio.
[ "Finds", "bigram", "collocations", "in", "the", "given", "corpus", "whose", "p", "-", "value", "is", "less", "than", "the", "given", "threshold", "." ]
e27e43e90fbaacce3f99d30120cf9dd6a764c33d
https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/nlp/src/main/java/smile/nlp/collocation/BigramCollocationFinder.java#L102-L142
17,141
haifengl/smile
nlp/src/main/java/smile/nlp/collocation/BigramCollocationFinder.java
BigramCollocationFinder.likelihoodRatio
private double likelihoodRatio(int c1, int c2, int c12, long N) { double p = (double) c2 / N; double p1 = (double) c12 / c1; double p2 = (double) (c2 - c12) / (N - c1); double logLambda = logL(c12, c1, p) + logL(c2-c12, N-c1, p) - logL(c12, c1, p1) - logL(c2-c12, N-c1, p2); return -2 * logLambda; }
java
private double likelihoodRatio(int c1, int c2, int c12, long N) { double p = (double) c2 / N; double p1 = (double) c12 / c1; double p2 = (double) (c2 - c12) / (N - c1); double logLambda = logL(c12, c1, p) + logL(c2-c12, N-c1, p) - logL(c12, c1, p1) - logL(c2-c12, N-c1, p2); return -2 * logLambda; }
[ "private", "double", "likelihoodRatio", "(", "int", "c1", ",", "int", "c2", ",", "int", "c12", ",", "long", "N", ")", "{", "double", "p", "=", "(", "double", ")", "c2", "/", "N", ";", "double", "p1", "=", "(", "double", ")", "c12", "/", "c1", ";", "double", "p2", "=", "(", "double", ")", "(", "c2", "-", "c12", ")", "/", "(", "N", "-", "c1", ")", ";", "double", "logLambda", "=", "logL", "(", "c12", ",", "c1", ",", "p", ")", "+", "logL", "(", "c2", "-", "c12", ",", "N", "-", "c1", ",", "p", ")", "-", "logL", "(", "c12", ",", "c1", ",", "p1", ")", "-", "logL", "(", "c2", "-", "c12", ",", "N", "-", "c1", ",", "p2", ")", ";", "return", "-", "2", "*", "logLambda", ";", "}" ]
Returns the likelihood ratio test statistic -2 log &lambda; @param c1 the number of occurrences of w1. @param c2 the number of occurrences of w2. @param c12 the number of occurrences of w1 w2. @param N the number of tokens in the corpus.
[ "Returns", "the", "likelihood", "ratio", "test", "statistic", "-", "2", "log", "&lambda", ";" ]
e27e43e90fbaacce3f99d30120cf9dd6a764c33d
https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/nlp/src/main/java/smile/nlp/collocation/BigramCollocationFinder.java#L151-L158
17,142
haifengl/smile
nlp/src/main/java/smile/nlp/collocation/BigramCollocationFinder.java
BigramCollocationFinder.logL
private double logL(int k, long n, double x) { if (x == 0.0) x = 0.01; if (x == 1.0) x = 0.99; return k * Math.log(x) + (n-k) * Math.log(1-x); }
java
private double logL(int k, long n, double x) { if (x == 0.0) x = 0.01; if (x == 1.0) x = 0.99; return k * Math.log(x) + (n-k) * Math.log(1-x); }
[ "private", "double", "logL", "(", "int", "k", ",", "long", "n", ",", "double", "x", ")", "{", "if", "(", "x", "==", "0.0", ")", "x", "=", "0.01", ";", "if", "(", "x", "==", "1.0", ")", "x", "=", "0.99", ";", "return", "k", "*", "Math", ".", "log", "(", "x", ")", "+", "(", "n", "-", "k", ")", "*", "Math", ".", "log", "(", "1", "-", "x", ")", ";", "}" ]
Help function for calculating likelihood ratio statistic.
[ "Help", "function", "for", "calculating", "likelihood", "ratio", "statistic", "." ]
e27e43e90fbaacce3f99d30120cf9dd6a764c33d
https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/nlp/src/main/java/smile/nlp/collocation/BigramCollocationFinder.java#L163-L167
17,143
haifengl/smile
core/src/main/java/smile/wavelet/WaveletShrinkage.java
WaveletShrinkage.denoise
public static void denoise(double[] t, Wavelet wavelet, boolean soft) { wavelet.transform(t); int n = t.length; int nh = t.length >> 1; double[] wc = new double[nh]; System.arraycopy(t, nh, wc, 0, nh); double error = Math.mad(wc) / 0.6745; double lambda = error * Math.sqrt(2 * Math.log(n)); if (soft) { for (int i = 2; i < n; i++) { t[i] = Math.signum(t[i]) * Math.max(Math.abs(t[i]) - lambda, 0.0); } } else { for (int i = 2; i < n; i++) { if (Math.abs(t[i]) < lambda) { t[i] = 0.0; } } } wavelet.inverse(t); }
java
public static void denoise(double[] t, Wavelet wavelet, boolean soft) { wavelet.transform(t); int n = t.length; int nh = t.length >> 1; double[] wc = new double[nh]; System.arraycopy(t, nh, wc, 0, nh); double error = Math.mad(wc) / 0.6745; double lambda = error * Math.sqrt(2 * Math.log(n)); if (soft) { for (int i = 2; i < n; i++) { t[i] = Math.signum(t[i]) * Math.max(Math.abs(t[i]) - lambda, 0.0); } } else { for (int i = 2; i < n; i++) { if (Math.abs(t[i]) < lambda) { t[i] = 0.0; } } } wavelet.inverse(t); }
[ "public", "static", "void", "denoise", "(", "double", "[", "]", "t", ",", "Wavelet", "wavelet", ",", "boolean", "soft", ")", "{", "wavelet", ".", "transform", "(", "t", ")", ";", "int", "n", "=", "t", ".", "length", ";", "int", "nh", "=", "t", ".", "length", ">>", "1", ";", "double", "[", "]", "wc", "=", "new", "double", "[", "nh", "]", ";", "System", ".", "arraycopy", "(", "t", ",", "nh", ",", "wc", ",", "0", ",", "nh", ")", ";", "double", "error", "=", "Math", ".", "mad", "(", "wc", ")", "/", "0.6745", ";", "double", "lambda", "=", "error", "*", "Math", ".", "sqrt", "(", "2", "*", "Math", ".", "log", "(", "n", ")", ")", ";", "if", "(", "soft", ")", "{", "for", "(", "int", "i", "=", "2", ";", "i", "<", "n", ";", "i", "++", ")", "{", "t", "[", "i", "]", "=", "Math", ".", "signum", "(", "t", "[", "i", "]", ")", "*", "Math", ".", "max", "(", "Math", ".", "abs", "(", "t", "[", "i", "]", ")", "-", "lambda", ",", "0.0", ")", ";", "}", "}", "else", "{", "for", "(", "int", "i", "=", "2", ";", "i", "<", "n", ";", "i", "++", ")", "{", "if", "(", "Math", ".", "abs", "(", "t", "[", "i", "]", ")", "<", "lambda", ")", "{", "t", "[", "i", "]", "=", "0.0", ";", "}", "}", "}", "wavelet", ".", "inverse", "(", "t", ")", ";", "}" ]
Adaptive denoising a time series with given wavelet. @param t the time series array. The size should be a power of 2. For time series of size no power of 2, 0 padding can be applied. @param wavelet the wavelet to transform the time series. @param soft true if apply soft thresholding.
[ "Adaptive", "denoising", "a", "time", "series", "with", "given", "wavelet", "." ]
e27e43e90fbaacce3f99d30120cf9dd6a764c33d
https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/core/src/main/java/smile/wavelet/WaveletShrinkage.java#L68-L93
17,144
haifengl/smile
interpolation/src/main/java/smile/interpolation/CubicSplineInterpolation1D.java
CubicSplineInterpolation1D.sety2
private void sety2(double[] x, double[] y) { double p, qn, sig, un; double[] u = new double[n - 1]; y2[0] = u[0] = 0.0; for (int i = 1; i < n - 1; i++) { sig = (x[i] - x[i - 1]) / (x[i + 1] - x[i - 1]); p = sig * y2[i - 1] + 2.0; y2[i] = (sig - 1.0) / p; u[i] = (y[i + 1] - y[i]) / (x[i + 1] - x[i]) - (y[i] - y[i - 1]) / (x[i] - x[i - 1]); u[i] = (6.0 * u[i] / (x[i + 1] - x[i - 1]) - sig * u[i - 1]) / p; } qn = un = 0.0; y2[n - 1] = (un - qn * u[n - 2]) / (qn * y2[n - 2] + 1.0); for (int k = n - 2; k >= 0; k--) { y2[k] = y2[k] * y2[k + 1] + u[k]; } }
java
private void sety2(double[] x, double[] y) { double p, qn, sig, un; double[] u = new double[n - 1]; y2[0] = u[0] = 0.0; for (int i = 1; i < n - 1; i++) { sig = (x[i] - x[i - 1]) / (x[i + 1] - x[i - 1]); p = sig * y2[i - 1] + 2.0; y2[i] = (sig - 1.0) / p; u[i] = (y[i + 1] - y[i]) / (x[i + 1] - x[i]) - (y[i] - y[i - 1]) / (x[i] - x[i - 1]); u[i] = (6.0 * u[i] / (x[i + 1] - x[i - 1]) - sig * u[i - 1]) / p; } qn = un = 0.0; y2[n - 1] = (un - qn * u[n - 2]) / (qn * y2[n - 2] + 1.0); for (int k = n - 2; k >= 0; k--) { y2[k] = y2[k] * y2[k + 1] + u[k]; } }
[ "private", "void", "sety2", "(", "double", "[", "]", "x", ",", "double", "[", "]", "y", ")", "{", "double", "p", ",", "qn", ",", "sig", ",", "un", ";", "double", "[", "]", "u", "=", "new", "double", "[", "n", "-", "1", "]", ";", "y2", "[", "0", "]", "=", "u", "[", "0", "]", "=", "0.0", ";", "for", "(", "int", "i", "=", "1", ";", "i", "<", "n", "-", "1", ";", "i", "++", ")", "{", "sig", "=", "(", "x", "[", "i", "]", "-", "x", "[", "i", "-", "1", "]", ")", "/", "(", "x", "[", "i", "+", "1", "]", "-", "x", "[", "i", "-", "1", "]", ")", ";", "p", "=", "sig", "*", "y2", "[", "i", "-", "1", "]", "+", "2.0", ";", "y2", "[", "i", "]", "=", "(", "sig", "-", "1.0", ")", "/", "p", ";", "u", "[", "i", "]", "=", "(", "y", "[", "i", "+", "1", "]", "-", "y", "[", "i", "]", ")", "/", "(", "x", "[", "i", "+", "1", "]", "-", "x", "[", "i", "]", ")", "-", "(", "y", "[", "i", "]", "-", "y", "[", "i", "-", "1", "]", ")", "/", "(", "x", "[", "i", "]", "-", "x", "[", "i", "-", "1", "]", ")", ";", "u", "[", "i", "]", "=", "(", "6.0", "*", "u", "[", "i", "]", "/", "(", "x", "[", "i", "+", "1", "]", "-", "x", "[", "i", "-", "1", "]", ")", "-", "sig", "*", "u", "[", "i", "-", "1", "]", ")", "/", "p", ";", "}", "qn", "=", "un", "=", "0.0", ";", "y2", "[", "n", "-", "1", "]", "=", "(", "un", "-", "qn", "*", "u", "[", "n", "-", "2", "]", ")", "/", "(", "qn", "*", "y2", "[", "n", "-", "2", "]", "+", "1.0", ")", ";", "for", "(", "int", "k", "=", "n", "-", "2", ";", "k", ">=", "0", ";", "k", "--", ")", "{", "y2", "[", "k", "]", "=", "y2", "[", "k", "]", "*", "y2", "[", "k", "+", "1", "]", "+", "u", "[", "k", "]", ";", "}", "}" ]
Calculate the second derivatives of the interpolating function at the tabulated points. At the endpoints, we use a natural spline with zero second derivative on that boundary.
[ "Calculate", "the", "second", "derivatives", "of", "the", "interpolating", "function", "at", "the", "tabulated", "points", ".", "At", "the", "endpoints", "we", "use", "a", "natural", "spline", "with", "zero", "second", "derivative", "on", "that", "boundary", "." ]
e27e43e90fbaacce3f99d30120cf9dd6a764c33d
https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/interpolation/src/main/java/smile/interpolation/CubicSplineInterpolation1D.java#L73-L92
17,145
haifengl/smile
math/src/main/java/smile/stat/distribution/DiscreteMixture.java
DiscreteMixture.bic
public double bic(double[] data) { if (components.isEmpty()) { throw new IllegalStateException("Mixture is empty!"); } int n = data.length; double logLikelihood = 0.0; for (double x : data) { double p = p(x); if (p > 0) { logLikelihood += Math.log(p); } } return logLikelihood - 0.5 * npara() * Math.log(n); }
java
public double bic(double[] data) { if (components.isEmpty()) { throw new IllegalStateException("Mixture is empty!"); } int n = data.length; double logLikelihood = 0.0; for (double x : data) { double p = p(x); if (p > 0) { logLikelihood += Math.log(p); } } return logLikelihood - 0.5 * npara() * Math.log(n); }
[ "public", "double", "bic", "(", "double", "[", "]", "data", ")", "{", "if", "(", "components", ".", "isEmpty", "(", ")", ")", "{", "throw", "new", "IllegalStateException", "(", "\"Mixture is empty!\"", ")", ";", "}", "int", "n", "=", "data", ".", "length", ";", "double", "logLikelihood", "=", "0.0", ";", "for", "(", "double", "x", ":", "data", ")", "{", "double", "p", "=", "p", "(", "x", ")", ";", "if", "(", "p", ">", "0", ")", "{", "logLikelihood", "+=", "Math", ".", "log", "(", "p", ")", ";", "}", "}", "return", "logLikelihood", "-", "0.5", "*", "npara", "(", ")", "*", "Math", ".", "log", "(", "n", ")", ";", "}" ]
BIC score of the mixture for given data.
[ "BIC", "score", "of", "the", "mixture", "for", "given", "data", "." ]
e27e43e90fbaacce3f99d30120cf9dd6a764c33d
https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/math/src/main/java/smile/stat/distribution/DiscreteMixture.java#L227-L243
17,146
haifengl/smile
core/src/main/java/smile/clustering/SIB.java
SIB.seed
private static int[] seed(SparseDataset data, int k) { int n = data.size(); int[] y = new int[n]; SparseArray centroid = data.get(Math.randomInt(n)).x; double[] D = new double[n]; for (int i = 0; i < n; i++) { D[i] = Double.MAX_VALUE; } // pick the next center for (int i = 1; i < k; i++) { for (int j = 0; j < n; j++) { double dist = Math.JensenShannonDivergence(data.get(j).x, centroid); if (dist < D[j]) { D[j] = dist; y[j] = i - 1; } } double cutoff = Math.random() * Math.sum(D); double cost = 0.0; int index = 0; for (; index < n; index++) { cost += D[index]; if (cost >= cutoff) { break; } } centroid = data.get(index).x; } for (int j = 0; j < n; j++) { // compute the distance between this sample and the current center double dist = Math.JensenShannonDivergence(data.get(j).x, centroid); if (dist < D[j]) { D[j] = dist; y[j] = k - 1; } } return y; }
java
private static int[] seed(SparseDataset data, int k) { int n = data.size(); int[] y = new int[n]; SparseArray centroid = data.get(Math.randomInt(n)).x; double[] D = new double[n]; for (int i = 0; i < n; i++) { D[i] = Double.MAX_VALUE; } // pick the next center for (int i = 1; i < k; i++) { for (int j = 0; j < n; j++) { double dist = Math.JensenShannonDivergence(data.get(j).x, centroid); if (dist < D[j]) { D[j] = dist; y[j] = i - 1; } } double cutoff = Math.random() * Math.sum(D); double cost = 0.0; int index = 0; for (; index < n; index++) { cost += D[index]; if (cost >= cutoff) { break; } } centroid = data.get(index).x; } for (int j = 0; j < n; j++) { // compute the distance between this sample and the current center double dist = Math.JensenShannonDivergence(data.get(j).x, centroid); if (dist < D[j]) { D[j] = dist; y[j] = k - 1; } } return y; }
[ "private", "static", "int", "[", "]", "seed", "(", "SparseDataset", "data", ",", "int", "k", ")", "{", "int", "n", "=", "data", ".", "size", "(", ")", ";", "int", "[", "]", "y", "=", "new", "int", "[", "n", "]", ";", "SparseArray", "centroid", "=", "data", ".", "get", "(", "Math", ".", "randomInt", "(", "n", ")", ")", ".", "x", ";", "double", "[", "]", "D", "=", "new", "double", "[", "n", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "n", ";", "i", "++", ")", "{", "D", "[", "i", "]", "=", "Double", ".", "MAX_VALUE", ";", "}", "// pick the next center", "for", "(", "int", "i", "=", "1", ";", "i", "<", "k", ";", "i", "++", ")", "{", "for", "(", "int", "j", "=", "0", ";", "j", "<", "n", ";", "j", "++", ")", "{", "double", "dist", "=", "Math", ".", "JensenShannonDivergence", "(", "data", ".", "get", "(", "j", ")", ".", "x", ",", "centroid", ")", ";", "if", "(", "dist", "<", "D", "[", "j", "]", ")", "{", "D", "[", "j", "]", "=", "dist", ";", "y", "[", "j", "]", "=", "i", "-", "1", ";", "}", "}", "double", "cutoff", "=", "Math", ".", "random", "(", ")", "*", "Math", ".", "sum", "(", "D", ")", ";", "double", "cost", "=", "0.0", ";", "int", "index", "=", "0", ";", "for", "(", ";", "index", "<", "n", ";", "index", "++", ")", "{", "cost", "+=", "D", "[", "index", "]", ";", "if", "(", "cost", ">=", "cutoff", ")", "{", "break", ";", "}", "}", "centroid", "=", "data", ".", "get", "(", "index", ")", ".", "x", ";", "}", "for", "(", "int", "j", "=", "0", ";", "j", "<", "n", ";", "j", "++", ")", "{", "// compute the distance between this sample and the current center", "double", "dist", "=", "Math", ".", "JensenShannonDivergence", "(", "data", ".", "get", "(", "j", ")", ".", "x", ",", "centroid", ")", ";", "if", "(", "dist", "<", "D", "[", "j", "]", ")", "{", "D", "[", "j", "]", "=", "dist", ";", "y", "[", "j", "]", "=", "k", "-", "1", ";", "}", "}", "return", "y", ";", "}" ]
Initialize clusters with KMeans++ algorithm.
[ "Initialize", "clusters", "with", "KMeans", "++", "algorithm", "." ]
e27e43e90fbaacce3f99d30120cf9dd6a764c33d
https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/core/src/main/java/smile/clustering/SIB.java#L228-L272
17,147
haifengl/smile
math/src/main/java/smile/stat/distribution/TDistribution.java
TDistribution.cdf2tiled
public double cdf2tiled(double x) { if (x < 0) { throw new IllegalArgumentException("Invalid x: " + x); } return 1.0 - Beta.regularizedIncompleteBetaFunction(0.5 * nu, 0.5, nu / (nu + x * x)); }
java
public double cdf2tiled(double x) { if (x < 0) { throw new IllegalArgumentException("Invalid x: " + x); } return 1.0 - Beta.regularizedIncompleteBetaFunction(0.5 * nu, 0.5, nu / (nu + x * x)); }
[ "public", "double", "cdf2tiled", "(", "double", "x", ")", "{", "if", "(", "x", "<", "0", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Invalid x: \"", "+", "x", ")", ";", "}", "return", "1.0", "-", "Beta", ".", "regularizedIncompleteBetaFunction", "(", "0.5", "*", "nu", ",", "0.5", ",", "nu", "/", "(", "nu", "+", "x", "*", "x", ")", ")", ";", "}" ]
Two-tailed cdf.
[ "Two", "-", "tailed", "cdf", "." ]
e27e43e90fbaacce3f99d30120cf9dd6a764c33d
https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/math/src/main/java/smile/stat/distribution/TDistribution.java#L134-L140
17,148
haifengl/smile
math/src/main/java/smile/stat/distribution/TDistribution.java
TDistribution.quantile2tiled
public double quantile2tiled(double p) { if (p < 0.0 || p > 1.0) { throw new IllegalArgumentException("Invalid p: " + p); } double x = Beta.inverseRegularizedIncompleteBetaFunction(0.5 * nu, 0.5, 1.0 - p); return Math.sqrt(nu * (1.0 - x) / x); }
java
public double quantile2tiled(double p) { if (p < 0.0 || p > 1.0) { throw new IllegalArgumentException("Invalid p: " + p); } double x = Beta.inverseRegularizedIncompleteBetaFunction(0.5 * nu, 0.5, 1.0 - p); return Math.sqrt(nu * (1.0 - x) / x); }
[ "public", "double", "quantile2tiled", "(", "double", "p", ")", "{", "if", "(", "p", "<", "0.0", "||", "p", ">", "1.0", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Invalid p: \"", "+", "p", ")", ";", "}", "double", "x", "=", "Beta", ".", "inverseRegularizedIncompleteBetaFunction", "(", "0.5", "*", "nu", ",", "0.5", ",", "1.0", "-", "p", ")", ";", "return", "Math", ".", "sqrt", "(", "nu", "*", "(", "1.0", "-", "x", ")", "/", "x", ")", ";", "}" ]
Two-tailed quantile.
[ "Two", "-", "tailed", "quantile", "." ]
e27e43e90fbaacce3f99d30120cf9dd6a764c33d
https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/math/src/main/java/smile/stat/distribution/TDistribution.java#L145-L152
17,149
haifengl/smile
data/src/main/java/smile/data/parser/DelimitedTextParser.java
DelimitedTextParser.parse
public AttributeDataset parse(String name, InputStream stream) throws IOException, ParseException { try (BufferedReader reader = new BufferedReader(new InputStreamReader(stream))) { return parse(name, null, reader); } }
java
public AttributeDataset parse(String name, InputStream stream) throws IOException, ParseException { try (BufferedReader reader = new BufferedReader(new InputStreamReader(stream))) { return parse(name, null, reader); } }
[ "public", "AttributeDataset", "parse", "(", "String", "name", ",", "InputStream", "stream", ")", "throws", "IOException", ",", "ParseException", "{", "try", "(", "BufferedReader", "reader", "=", "new", "BufferedReader", "(", "new", "InputStreamReader", "(", "stream", ")", ")", ")", "{", "return", "parse", "(", "name", ",", "null", ",", "reader", ")", ";", "}", "}" ]
Parse a dataset from an input stream. @param name the name of dataset. @param stream the input stream of data. @throws java.io.FileNotFoundException
[ "Parse", "a", "dataset", "from", "an", "input", "stream", "." ]
e27e43e90fbaacce3f99d30120cf9dd6a764c33d
https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/data/src/main/java/smile/data/parser/DelimitedTextParser.java#L297-L301
17,150
haifengl/smile
plot/src/main/java/smile/plot/Label.java
Label.coordToString
public static String coordToString(double... c) { StringBuilder builder = new StringBuilder("("); for (int i = 0; i < c.length; i++) { builder.append(Math.round(c[i], 2)).append(","); } if (c.length > 0) { builder.setCharAt(builder.length(), ')'); } else { builder.append(")"); } return builder.toString(); }
java
public static String coordToString(double... c) { StringBuilder builder = new StringBuilder("("); for (int i = 0; i < c.length; i++) { builder.append(Math.round(c[i], 2)).append(","); } if (c.length > 0) { builder.setCharAt(builder.length(), ')'); } else { builder.append(")"); } return builder.toString(); }
[ "public", "static", "String", "coordToString", "(", "double", "...", "c", ")", "{", "StringBuilder", "builder", "=", "new", "StringBuilder", "(", "\"(\"", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "c", ".", "length", ";", "i", "++", ")", "{", "builder", ".", "append", "(", "Math", ".", "round", "(", "c", "[", "i", "]", ",", "2", ")", ")", ".", "append", "(", "\",\"", ")", ";", "}", "if", "(", "c", ".", "length", ">", "0", ")", "{", "builder", ".", "setCharAt", "(", "builder", ".", "length", "(", ")", ",", "'", "'", ")", ";", "}", "else", "{", "builder", ".", "append", "(", "\")\"", ")", ";", "}", "return", "builder", ".", "toString", "(", ")", ";", "}" ]
Convert coordinate to a string.
[ "Convert", "coordinate", "to", "a", "string", "." ]
e27e43e90fbaacce3f99d30120cf9dd6a764c33d
https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/plot/src/main/java/smile/plot/Label.java#L179-L192
17,151
haifengl/smile
math/src/main/java/smile/sort/QuickSelect.java
QuickSelect.median
public static <T extends Comparable<? super T>> T median(T[] a) { int k = a.length / 2; return select(a, k); }
java
public static <T extends Comparable<? super T>> T median(T[] a) { int k = a.length / 2; return select(a, k); }
[ "public", "static", "<", "T", "extends", "Comparable", "<", "?", "super", "T", ">", ">", "T", "median", "(", "T", "[", "]", "a", ")", "{", "int", "k", "=", "a", ".", "length", "/", "2", ";", "return", "select", "(", "a", ",", "k", ")", ";", "}" ]
Find the median of an array of type double.
[ "Find", "the", "median", "of", "an", "array", "of", "type", "double", "." ]
e27e43e90fbaacce3f99d30120cf9dd6a764c33d
https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/math/src/main/java/smile/sort/QuickSelect.java#L299-L302
17,152
haifengl/smile
core/src/main/java/smile/validation/AUC.java
AUC.measure
public static double measure(int[] truth, double[] probability) { if (truth.length != probability.length) { throw new IllegalArgumentException(String.format("The vector sizes don't match: %d != %d.", truth.length, probability.length)); } // for large sample size, overflow may happen for pos * neg. // switch to double to prevent it. double pos = 0; double neg = 0; for (int i = 0; i < truth.length; i++) { if (truth[i] == 0) { neg++; } else if (truth[i] == 1) { pos++; } else { throw new IllegalArgumentException("AUC is only for binary classification. Invalid label: " + truth[i]); } } int[] label = truth.clone(); double[] prediction = probability.clone(); QuickSort.sort(prediction, label); double[] rank = new double[label.length]; for (int i = 0; i < prediction.length; i++) { if (i == prediction.length - 1 || prediction[i] != prediction[i+1]) { rank[i] = i + 1; } else { int j = i + 1; for (; j < prediction.length && prediction[j] == prediction[i]; j++); double r = (i + 1 + j) / 2.0; for (int k = i; k < j; k++) rank[k] = r; i = j - 1; } } double auc = 0.0; for (int i = 0; i < label.length; i++) { if (label[i] == 1) auc += rank[i]; } auc = (auc - (pos * (pos+1) / 2.0)) / (pos * neg); return auc; }
java
public static double measure(int[] truth, double[] probability) { if (truth.length != probability.length) { throw new IllegalArgumentException(String.format("The vector sizes don't match: %d != %d.", truth.length, probability.length)); } // for large sample size, overflow may happen for pos * neg. // switch to double to prevent it. double pos = 0; double neg = 0; for (int i = 0; i < truth.length; i++) { if (truth[i] == 0) { neg++; } else if (truth[i] == 1) { pos++; } else { throw new IllegalArgumentException("AUC is only for binary classification. Invalid label: " + truth[i]); } } int[] label = truth.clone(); double[] prediction = probability.clone(); QuickSort.sort(prediction, label); double[] rank = new double[label.length]; for (int i = 0; i < prediction.length; i++) { if (i == prediction.length - 1 || prediction[i] != prediction[i+1]) { rank[i] = i + 1; } else { int j = i + 1; for (; j < prediction.length && prediction[j] == prediction[i]; j++); double r = (i + 1 + j) / 2.0; for (int k = i; k < j; k++) rank[k] = r; i = j - 1; } } double auc = 0.0; for (int i = 0; i < label.length; i++) { if (label[i] == 1) auc += rank[i]; } auc = (auc - (pos * (pos+1) / 2.0)) / (pos * neg); return auc; }
[ "public", "static", "double", "measure", "(", "int", "[", "]", "truth", ",", "double", "[", "]", "probability", ")", "{", "if", "(", "truth", ".", "length", "!=", "probability", ".", "length", ")", "{", "throw", "new", "IllegalArgumentException", "(", "String", ".", "format", "(", "\"The vector sizes don't match: %d != %d.\"", ",", "truth", ".", "length", ",", "probability", ".", "length", ")", ")", ";", "}", "// for large sample size, overflow may happen for pos * neg.", "// switch to double to prevent it.", "double", "pos", "=", "0", ";", "double", "neg", "=", "0", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "truth", ".", "length", ";", "i", "++", ")", "{", "if", "(", "truth", "[", "i", "]", "==", "0", ")", "{", "neg", "++", ";", "}", "else", "if", "(", "truth", "[", "i", "]", "==", "1", ")", "{", "pos", "++", ";", "}", "else", "{", "throw", "new", "IllegalArgumentException", "(", "\"AUC is only for binary classification. Invalid label: \"", "+", "truth", "[", "i", "]", ")", ";", "}", "}", "int", "[", "]", "label", "=", "truth", ".", "clone", "(", ")", ";", "double", "[", "]", "prediction", "=", "probability", ".", "clone", "(", ")", ";", "QuickSort", ".", "sort", "(", "prediction", ",", "label", ")", ";", "double", "[", "]", "rank", "=", "new", "double", "[", "label", ".", "length", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "prediction", ".", "length", ";", "i", "++", ")", "{", "if", "(", "i", "==", "prediction", ".", "length", "-", "1", "||", "prediction", "[", "i", "]", "!=", "prediction", "[", "i", "+", "1", "]", ")", "{", "rank", "[", "i", "]", "=", "i", "+", "1", ";", "}", "else", "{", "int", "j", "=", "i", "+", "1", ";", "for", "(", ";", "j", "<", "prediction", ".", "length", "&&", "prediction", "[", "j", "]", "==", "prediction", "[", "i", "]", ";", "j", "++", ")", ";", "double", "r", "=", "(", "i", "+", "1", "+", "j", ")", "/", "2.0", ";", "for", "(", "int", "k", "=", "i", ";", "k", "<", "j", ";", "k", "++", ")", "rank", "[", "k", "]", "=", "r", ";", "i", "=", "j", "-", "1", ";", "}", "}", "double", "auc", "=", "0.0", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "label", ".", "length", ";", "i", "++", ")", "{", "if", "(", "label", "[", "i", "]", "==", "1", ")", "auc", "+=", "rank", "[", "i", "]", ";", "}", "auc", "=", "(", "auc", "-", "(", "pos", "*", "(", "pos", "+", "1", ")", "/", "2.0", ")", ")", "/", "(", "pos", "*", "neg", ")", ";", "return", "auc", ";", "}" ]
Caulculate AUC for binary classifier. @param truth The sample labels @param probability The posterior probability of positive class. @return AUC
[ "Caulculate", "AUC", "for", "binary", "classifier", "." ]
e27e43e90fbaacce3f99d30120cf9dd6a764c33d
https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/core/src/main/java/smile/validation/AUC.java#L52-L98
17,153
haifengl/smile
core/src/main/java/smile/vq/GrowingNeuralGas.java
GrowingNeuralGas.neurons
public Neuron[] neurons() { HashMap<Integer, Neuron> hash = new HashMap<>(); Neuron[] neurons = new Neuron[nodes.size()]; int i = 0; for (Node node : nodes) { Neuron[] neighbors = new Neuron[node.edges.size()]; neurons[i] = new Neuron(node.w, neighbors); hash.put(node.id, neurons[i]); i++; } i = 0; for (Node node : nodes) { int j = 0; for (Edge edge : node.edges) { if (edge.a != node) neurons[i].neighbors[j++] = hash.get(edge.a.id); else neurons[i].neighbors[j++] = hash.get(edge.b.id); } i++; } return neurons; }
java
public Neuron[] neurons() { HashMap<Integer, Neuron> hash = new HashMap<>(); Neuron[] neurons = new Neuron[nodes.size()]; int i = 0; for (Node node : nodes) { Neuron[] neighbors = new Neuron[node.edges.size()]; neurons[i] = new Neuron(node.w, neighbors); hash.put(node.id, neurons[i]); i++; } i = 0; for (Node node : nodes) { int j = 0; for (Edge edge : node.edges) { if (edge.a != node) neurons[i].neighbors[j++] = hash.get(edge.a.id); else neurons[i].neighbors[j++] = hash.get(edge.b.id); } i++; } return neurons; }
[ "public", "Neuron", "[", "]", "neurons", "(", ")", "{", "HashMap", "<", "Integer", ",", "Neuron", ">", "hash", "=", "new", "HashMap", "<>", "(", ")", ";", "Neuron", "[", "]", "neurons", "=", "new", "Neuron", "[", "nodes", ".", "size", "(", ")", "]", ";", "int", "i", "=", "0", ";", "for", "(", "Node", "node", ":", "nodes", ")", "{", "Neuron", "[", "]", "neighbors", "=", "new", "Neuron", "[", "node", ".", "edges", ".", "size", "(", ")", "]", ";", "neurons", "[", "i", "]", "=", "new", "Neuron", "(", "node", ".", "w", ",", "neighbors", ")", ";", "hash", ".", "put", "(", "node", ".", "id", ",", "neurons", "[", "i", "]", ")", ";", "i", "++", ";", "}", "i", "=", "0", ";", "for", "(", "Node", "node", ":", "nodes", ")", "{", "int", "j", "=", "0", ";", "for", "(", "Edge", "edge", ":", "node", ".", "edges", ")", "{", "if", "(", "edge", ".", "a", "!=", "node", ")", "neurons", "[", "i", "]", ".", "neighbors", "[", "j", "++", "]", "=", "hash", ".", "get", "(", "edge", ".", "a", ".", "id", ")", ";", "else", "neurons", "[", "i", "]", ".", "neighbors", "[", "j", "++", "]", "=", "hash", ".", "get", "(", "edge", ".", "b", ".", "id", ")", ";", "}", "i", "++", ";", "}", "return", "neurons", ";", "}" ]
Returns the neurons in the network. @return the neurons in the network.
[ "Returns", "the", "neurons", "in", "the", "network", "." ]
e27e43e90fbaacce3f99d30120cf9dd6a764c33d
https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/core/src/main/java/smile/vq/GrowingNeuralGas.java#L225-L250
17,154
haifengl/smile
core/src/main/java/smile/vq/GrowingNeuralGas.java
GrowingNeuralGas.predict
@Override public int predict(double[] x) { double minDist = Double.MAX_VALUE; int bestCluster = 0; int i = 0; for (Node neuron : nodes) { double dist = Math.squaredDistance(x, neuron.w); if (dist < minDist) { minDist = dist; bestCluster = i; } i++; } if (y == null || y.length != nodes.size()) { return bestCluster; } else { return y[bestCluster]; } }
java
@Override public int predict(double[] x) { double minDist = Double.MAX_VALUE; int bestCluster = 0; int i = 0; for (Node neuron : nodes) { double dist = Math.squaredDistance(x, neuron.w); if (dist < minDist) { minDist = dist; bestCluster = i; } i++; } if (y == null || y.length != nodes.size()) { return bestCluster; } else { return y[bestCluster]; } }
[ "@", "Override", "public", "int", "predict", "(", "double", "[", "]", "x", ")", "{", "double", "minDist", "=", "Double", ".", "MAX_VALUE", ";", "int", "bestCluster", "=", "0", ";", "int", "i", "=", "0", ";", "for", "(", "Node", "neuron", ":", "nodes", ")", "{", "double", "dist", "=", "Math", ".", "squaredDistance", "(", "x", ",", "neuron", ".", "w", ")", ";", "if", "(", "dist", "<", "minDist", ")", "{", "minDist", "=", "dist", ";", "bestCluster", "=", "i", ";", "}", "i", "++", ";", "}", "if", "(", "y", "==", "null", "||", "y", ".", "length", "!=", "nodes", ".", "size", "(", ")", ")", "{", "return", "bestCluster", ";", "}", "else", "{", "return", "y", "[", "bestCluster", "]", ";", "}", "}" ]
Cluster a new instance to the nearest neuron. @param x a new instance. @return the cluster label. If the method partition() was called, this is the cluster id of nearest neuron. Otherwise, it is just the index of neuron.
[ "Cluster", "a", "new", "instance", "to", "the", "nearest", "neuron", "." ]
e27e43e90fbaacce3f99d30120cf9dd6a764c33d
https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/core/src/main/java/smile/vq/GrowingNeuralGas.java#L404-L425
17,155
haifengl/smile
plot/src/main/java/smile/plot/Projection2D.java
Projection2D.inverseProjection
public double[] inverseProjection(int x, int y) { double[] sc = new double[2]; double ratio = (canvas.base.upperBound[0] - canvas.base.lowerBound[0]) / (canvas.getWidth() * (1 - 2 * canvas.margin)); sc[0] = canvas.base.lowerBound[0] + ratio * (x - canvas.getWidth() * canvas.margin); ratio = (canvas.base.upperBound[1] - canvas.base.lowerBound[1]) / (canvas.getHeight() * (1 - 2 * canvas.margin)); sc[1] = canvas.base.lowerBound[1] + ratio * (canvas.getHeight() * (1 - canvas.margin) - y); return sc; }
java
public double[] inverseProjection(int x, int y) { double[] sc = new double[2]; double ratio = (canvas.base.upperBound[0] - canvas.base.lowerBound[0]) / (canvas.getWidth() * (1 - 2 * canvas.margin)); sc[0] = canvas.base.lowerBound[0] + ratio * (x - canvas.getWidth() * canvas.margin); ratio = (canvas.base.upperBound[1] - canvas.base.lowerBound[1]) / (canvas.getHeight() * (1 - 2 * canvas.margin)); sc[1] = canvas.base.lowerBound[1] + ratio * (canvas.getHeight() * (1 - canvas.margin) - y); return sc; }
[ "public", "double", "[", "]", "inverseProjection", "(", "int", "x", ",", "int", "y", ")", "{", "double", "[", "]", "sc", "=", "new", "double", "[", "2", "]", ";", "double", "ratio", "=", "(", "canvas", ".", "base", ".", "upperBound", "[", "0", "]", "-", "canvas", ".", "base", ".", "lowerBound", "[", "0", "]", ")", "/", "(", "canvas", ".", "getWidth", "(", ")", "*", "(", "1", "-", "2", "*", "canvas", ".", "margin", ")", ")", ";", "sc", "[", "0", "]", "=", "canvas", ".", "base", ".", "lowerBound", "[", "0", "]", "+", "ratio", "*", "(", "x", "-", "canvas", ".", "getWidth", "(", ")", "*", "canvas", ".", "margin", ")", ";", "ratio", "=", "(", "canvas", ".", "base", ".", "upperBound", "[", "1", "]", "-", "canvas", ".", "base", ".", "lowerBound", "[", "1", "]", ")", "/", "(", "canvas", ".", "getHeight", "(", ")", "*", "(", "1", "-", "2", "*", "canvas", ".", "margin", ")", ")", ";", "sc", "[", "1", "]", "=", "canvas", ".", "base", ".", "lowerBound", "[", "1", "]", "+", "ratio", "*", "(", "canvas", ".", "getHeight", "(", ")", "*", "(", "1", "-", "canvas", ".", "margin", ")", "-", "y", ")", ";", "return", "sc", ";", "}" ]
Project the screen coordinate back to the logical coordinates. @param x the x of Java2D coordinate in the canvas. @param y the y of Java2D coordinate in the canvas
[ "Project", "the", "screen", "coordinate", "back", "to", "the", "logical", "coordinates", "." ]
e27e43e90fbaacce3f99d30120cf9dd6a764c33d
https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/plot/src/main/java/smile/plot/Projection2D.java#L45-L55
17,156
haifengl/smile
core/src/main/java/smile/vq/SOM.java
SOM.getClusterLabel
public int[][] getClusterLabel() { if (y == null) { throw new IllegalStateException("Neuron cluster labels are not available. Call partition() first."); } int[][] clusterLabels = new int[height][width]; for (int i = 0, l = 0; i < height; i++) { for (int j = 0; j < width; j++) { clusterLabels[i][j] = y[i*width + j]; } } return clusterLabels; }
java
public int[][] getClusterLabel() { if (y == null) { throw new IllegalStateException("Neuron cluster labels are not available. Call partition() first."); } int[][] clusterLabels = new int[height][width]; for (int i = 0, l = 0; i < height; i++) { for (int j = 0; j < width; j++) { clusterLabels[i][j] = y[i*width + j]; } } return clusterLabels; }
[ "public", "int", "[", "]", "[", "]", "getClusterLabel", "(", ")", "{", "if", "(", "y", "==", "null", ")", "{", "throw", "new", "IllegalStateException", "(", "\"Neuron cluster labels are not available. Call partition() first.\"", ")", ";", "}", "int", "[", "]", "[", "]", "clusterLabels", "=", "new", "int", "[", "height", "]", "[", "width", "]", ";", "for", "(", "int", "i", "=", "0", ",", "l", "=", "0", ";", "i", "<", "height", ";", "i", "++", ")", "{", "for", "(", "int", "j", "=", "0", ";", "j", "<", "width", ";", "j", "++", ")", "{", "clusterLabels", "[", "i", "]", "[", "j", "]", "=", "y", "[", "i", "*", "width", "+", "j", "]", ";", "}", "}", "return", "clusterLabels", ";", "}" ]
Returns the cluster labels for each neuron. If the neurons have not been clustered, throws an Illegal State Exception.
[ "Returns", "the", "cluster", "labels", "for", "each", "neuron", ".", "If", "the", "neurons", "have", "not", "been", "clustered", "throws", "an", "Illegal", "State", "Exception", "." ]
e27e43e90fbaacce3f99d30120cf9dd6a764c33d
https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/core/src/main/java/smile/vq/SOM.java#L401-L413
17,157
haifengl/smile
core/src/main/java/smile/vq/SOM.java
SOM.partition
public int[] partition(int k) { int n = width * height; double[][] units = new double[n][d]; for (int i = 0, l = 0; i < height; i++) { for (int j = 0; j < width; j++, l++) { units[l] = neurons[i][j]; } } double[][] proximity = new double[n][]; for (int i = 0; i < n; i++) { proximity[i] = new double[i + 1]; for (int j = 0; j < i; j++) { proximity[i][j] = Math.distance(units[i], units[j]); } } Linkage linkage = new UPGMALinkage(proximity); HierarchicalClustering hc = new HierarchicalClustering(linkage); y = hc.partition(k); int[] cluster = new int[bmu.length]; for (int i = 0; i < cluster.length; i++) { cluster[i] = y[bmu[i][0] * width + bmu[i][1]]; } return cluster; }
java
public int[] partition(int k) { int n = width * height; double[][] units = new double[n][d]; for (int i = 0, l = 0; i < height; i++) { for (int j = 0; j < width; j++, l++) { units[l] = neurons[i][j]; } } double[][] proximity = new double[n][]; for (int i = 0; i < n; i++) { proximity[i] = new double[i + 1]; for (int j = 0; j < i; j++) { proximity[i][j] = Math.distance(units[i], units[j]); } } Linkage linkage = new UPGMALinkage(proximity); HierarchicalClustering hc = new HierarchicalClustering(linkage); y = hc.partition(k); int[] cluster = new int[bmu.length]; for (int i = 0; i < cluster.length; i++) { cluster[i] = y[bmu[i][0] * width + bmu[i][1]]; } return cluster; }
[ "public", "int", "[", "]", "partition", "(", "int", "k", ")", "{", "int", "n", "=", "width", "*", "height", ";", "double", "[", "]", "[", "]", "units", "=", "new", "double", "[", "n", "]", "[", "d", "]", ";", "for", "(", "int", "i", "=", "0", ",", "l", "=", "0", ";", "i", "<", "height", ";", "i", "++", ")", "{", "for", "(", "int", "j", "=", "0", ";", "j", "<", "width", ";", "j", "++", ",", "l", "++", ")", "{", "units", "[", "l", "]", "=", "neurons", "[", "i", "]", "[", "j", "]", ";", "}", "}", "double", "[", "]", "[", "]", "proximity", "=", "new", "double", "[", "n", "]", "[", "", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "n", ";", "i", "++", ")", "{", "proximity", "[", "i", "]", "=", "new", "double", "[", "i", "+", "1", "]", ";", "for", "(", "int", "j", "=", "0", ";", "j", "<", "i", ";", "j", "++", ")", "{", "proximity", "[", "i", "]", "[", "j", "]", "=", "Math", ".", "distance", "(", "units", "[", "i", "]", ",", "units", "[", "j", "]", ")", ";", "}", "}", "Linkage", "linkage", "=", "new", "UPGMALinkage", "(", "proximity", ")", ";", "HierarchicalClustering", "hc", "=", "new", "HierarchicalClustering", "(", "linkage", ")", ";", "y", "=", "hc", ".", "partition", "(", "k", ")", ";", "int", "[", "]", "cluster", "=", "new", "int", "[", "bmu", ".", "length", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "cluster", ".", "length", ";", "i", "++", ")", "{", "cluster", "[", "i", "]", "=", "y", "[", "bmu", "[", "i", "]", "[", "0", "]", "*", "width", "+", "bmu", "[", "i", "]", "[", "1", "]", "]", ";", "}", "return", "cluster", ";", "}" ]
Clustering the neurons into k groups. And then assigns the samples in each neuron to the corresponding cluster. @param k the number of clusters. @return the cluster label of samples.
[ "Clustering", "the", "neurons", "into", "k", "groups", ".", "And", "then", "assigns", "the", "samples", "in", "each", "neuron", "to", "the", "corresponding", "cluster", "." ]
e27e43e90fbaacce3f99d30120cf9dd6a764c33d
https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/core/src/main/java/smile/vq/SOM.java#L421-L448
17,158
haifengl/smile
core/src/main/java/smile/vq/SOM.java
SOM.predict
@Override public int predict(double[] x) { double best = Double.MAX_VALUE; int ii = -1, jj = -1; for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { double dist = Math.squaredDistance(neurons[i][j], x); if (dist < best) { best = dist; ii = i; jj = j; } } } if (y == null) { return ii * width + jj; } else { return y[ii * width + jj]; } }
java
@Override public int predict(double[] x) { double best = Double.MAX_VALUE; int ii = -1, jj = -1; for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { double dist = Math.squaredDistance(neurons[i][j], x); if (dist < best) { best = dist; ii = i; jj = j; } } } if (y == null) { return ii * width + jj; } else { return y[ii * width + jj]; } }
[ "@", "Override", "public", "int", "predict", "(", "double", "[", "]", "x", ")", "{", "double", "best", "=", "Double", ".", "MAX_VALUE", ";", "int", "ii", "=", "-", "1", ",", "jj", "=", "-", "1", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "height", ";", "i", "++", ")", "{", "for", "(", "int", "j", "=", "0", ";", "j", "<", "width", ";", "j", "++", ")", "{", "double", "dist", "=", "Math", ".", "squaredDistance", "(", "neurons", "[", "i", "]", "[", "j", "]", ",", "x", ")", ";", "if", "(", "dist", "<", "best", ")", "{", "best", "=", "dist", ";", "ii", "=", "i", ";", "jj", "=", "j", ";", "}", "}", "}", "if", "(", "y", "==", "null", ")", "{", "return", "ii", "*", "width", "+", "jj", ";", "}", "else", "{", "return", "y", "[", "ii", "*", "width", "+", "jj", "]", ";", "}", "}" ]
Cluster a new instance to the nearest neuron. For clustering purpose, one should build a sufficient large map to capture the structure of data space. Then the neurons of map can be clustered into a small number of clusters. Finally the sample should be assign to the cluster of its nearest neurons. @param x a new instance. @return the cluster label. If the method {@link #partition(int)} is called before, this is the cluster label of the nearest neuron. Otherwise, this is the index of neuron (i * width + j).
[ "Cluster", "a", "new", "instance", "to", "the", "nearest", "neuron", ".", "For", "clustering", "purpose", "one", "should", "build", "a", "sufficient", "large", "map", "to", "capture", "the", "structure", "of", "data", "space", ".", "Then", "the", "neurons", "of", "map", "can", "be", "clustered", "into", "a", "small", "number", "of", "clusters", ".", "Finally", "the", "sample", "should", "be", "assign", "to", "the", "cluster", "of", "its", "nearest", "neurons", "." ]
e27e43e90fbaacce3f99d30120cf9dd6a764c33d
https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/core/src/main/java/smile/vq/SOM.java#L462-L482
17,159
haifengl/smile
data/src/main/java/smile/data/parser/LibsvmParser.java
LibsvmParser.parse
public SparseDataset parse(String name, String path) throws IOException, ParseException { return parse(name, new File(path)); }
java
public SparseDataset parse(String name, String path) throws IOException, ParseException { return parse(name, new File(path)); }
[ "public", "SparseDataset", "parse", "(", "String", "name", ",", "String", "path", ")", "throws", "IOException", ",", "ParseException", "{", "return", "parse", "(", "name", ",", "new", "File", "(", "path", ")", ")", ";", "}" ]
Parse a libsvm sparse dataset from given file. @param path the file path of data source. @throws java.io.IOException
[ "Parse", "a", "libsvm", "sparse", "dataset", "from", "given", "file", "." ]
e27e43e90fbaacce3f99d30120cf9dd6a764c33d
https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/data/src/main/java/smile/data/parser/LibsvmParser.java#L92-L94
17,160
haifengl/smile
data/src/main/java/smile/data/parser/LibsvmParser.java
LibsvmParser.parse
public SparseDataset parse(String name, InputStream stream) throws IOException, ParseException { BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); try { String line = reader.readLine(); if (line == null) { throw new IOException("Empty data source."); } String[] tokens = line.trim().split("\\s+"); boolean classification = true; Attribute response = null; try { Integer.valueOf(tokens[0]); response = new NominalAttribute("class"); } catch (NumberFormatException e) { try { Double.valueOf(tokens[0]); response = new NominalAttribute("response"); classification = false; } catch (NumberFormatException ex) { logger.error("Failed to parse {}", tokens[0], ex); throw new NumberFormatException("Unrecognized response variable value: " + tokens[0]); } } SparseDataset sparse = new SparseDataset(name, response); for (int i = 0; line != null; i++) { tokens = line.trim().split("\\s+"); if (classification) { int y = Integer.parseInt(tokens[0]); sparse.set(i, y); } else { double y = Double.parseDouble(tokens[0]); sparse.set(i, y); } for (int k = 1; k < tokens.length; k++) { String[] pair = tokens[k].split(":"); if (pair.length != 2) { throw new NumberFormatException("Invalid data: " + tokens[k]); } int j = Integer.parseInt(pair[0]) - 1; double x = Double.parseDouble(pair[1]); sparse.set(i, j, x); } line = reader.readLine(); } if (classification) { int n = sparse.size(); int[] y = sparse.toArray(new int[n]); int[] label = Math.unique(y); Arrays.sort(label); for (int c : label) { response.valueOf(String.valueOf(c)); } for (int i = 0; i < n; i++) { sparse.get(i).y = Arrays.binarySearch(label, y[i]); } } return sparse; } finally { reader.close(); } }
java
public SparseDataset parse(String name, InputStream stream) throws IOException, ParseException { BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); try { String line = reader.readLine(); if (line == null) { throw new IOException("Empty data source."); } String[] tokens = line.trim().split("\\s+"); boolean classification = true; Attribute response = null; try { Integer.valueOf(tokens[0]); response = new NominalAttribute("class"); } catch (NumberFormatException e) { try { Double.valueOf(tokens[0]); response = new NominalAttribute("response"); classification = false; } catch (NumberFormatException ex) { logger.error("Failed to parse {}", tokens[0], ex); throw new NumberFormatException("Unrecognized response variable value: " + tokens[0]); } } SparseDataset sparse = new SparseDataset(name, response); for (int i = 0; line != null; i++) { tokens = line.trim().split("\\s+"); if (classification) { int y = Integer.parseInt(tokens[0]); sparse.set(i, y); } else { double y = Double.parseDouble(tokens[0]); sparse.set(i, y); } for (int k = 1; k < tokens.length; k++) { String[] pair = tokens[k].split(":"); if (pair.length != 2) { throw new NumberFormatException("Invalid data: " + tokens[k]); } int j = Integer.parseInt(pair[0]) - 1; double x = Double.parseDouble(pair[1]); sparse.set(i, j, x); } line = reader.readLine(); } if (classification) { int n = sparse.size(); int[] y = sparse.toArray(new int[n]); int[] label = Math.unique(y); Arrays.sort(label); for (int c : label) { response.valueOf(String.valueOf(c)); } for (int i = 0; i < n; i++) { sparse.get(i).y = Arrays.binarySearch(label, y[i]); } } return sparse; } finally { reader.close(); } }
[ "public", "SparseDataset", "parse", "(", "String", "name", ",", "InputStream", "stream", ")", "throws", "IOException", ",", "ParseException", "{", "BufferedReader", "reader", "=", "new", "BufferedReader", "(", "new", "InputStreamReader", "(", "stream", ")", ")", ";", "try", "{", "String", "line", "=", "reader", ".", "readLine", "(", ")", ";", "if", "(", "line", "==", "null", ")", "{", "throw", "new", "IOException", "(", "\"Empty data source.\"", ")", ";", "}", "String", "[", "]", "tokens", "=", "line", ".", "trim", "(", ")", ".", "split", "(", "\"\\\\s+\"", ")", ";", "boolean", "classification", "=", "true", ";", "Attribute", "response", "=", "null", ";", "try", "{", "Integer", ".", "valueOf", "(", "tokens", "[", "0", "]", ")", ";", "response", "=", "new", "NominalAttribute", "(", "\"class\"", ")", ";", "}", "catch", "(", "NumberFormatException", "e", ")", "{", "try", "{", "Double", ".", "valueOf", "(", "tokens", "[", "0", "]", ")", ";", "response", "=", "new", "NominalAttribute", "(", "\"response\"", ")", ";", "classification", "=", "false", ";", "}", "catch", "(", "NumberFormatException", "ex", ")", "{", "logger", ".", "error", "(", "\"Failed to parse {}\"", ",", "tokens", "[", "0", "]", ",", "ex", ")", ";", "throw", "new", "NumberFormatException", "(", "\"Unrecognized response variable value: \"", "+", "tokens", "[", "0", "]", ")", ";", "}", "}", "SparseDataset", "sparse", "=", "new", "SparseDataset", "(", "name", ",", "response", ")", ";", "for", "(", "int", "i", "=", "0", ";", "line", "!=", "null", ";", "i", "++", ")", "{", "tokens", "=", "line", ".", "trim", "(", ")", ".", "split", "(", "\"\\\\s+\"", ")", ";", "if", "(", "classification", ")", "{", "int", "y", "=", "Integer", ".", "parseInt", "(", "tokens", "[", "0", "]", ")", ";", "sparse", ".", "set", "(", "i", ",", "y", ")", ";", "}", "else", "{", "double", "y", "=", "Double", ".", "parseDouble", "(", "tokens", "[", "0", "]", ")", ";", "sparse", ".", "set", "(", "i", ",", "y", ")", ";", "}", "for", "(", "int", "k", "=", "1", ";", "k", "<", "tokens", ".", "length", ";", "k", "++", ")", "{", "String", "[", "]", "pair", "=", "tokens", "[", "k", "]", ".", "split", "(", "\":\"", ")", ";", "if", "(", "pair", ".", "length", "!=", "2", ")", "{", "throw", "new", "NumberFormatException", "(", "\"Invalid data: \"", "+", "tokens", "[", "k", "]", ")", ";", "}", "int", "j", "=", "Integer", ".", "parseInt", "(", "pair", "[", "0", "]", ")", "-", "1", ";", "double", "x", "=", "Double", ".", "parseDouble", "(", "pair", "[", "1", "]", ")", ";", "sparse", ".", "set", "(", "i", ",", "j", ",", "x", ")", ";", "}", "line", "=", "reader", ".", "readLine", "(", ")", ";", "}", "if", "(", "classification", ")", "{", "int", "n", "=", "sparse", ".", "size", "(", ")", ";", "int", "[", "]", "y", "=", "sparse", ".", "toArray", "(", "new", "int", "[", "n", "]", ")", ";", "int", "[", "]", "label", "=", "Math", ".", "unique", "(", "y", ")", ";", "Arrays", ".", "sort", "(", "label", ")", ";", "for", "(", "int", "c", ":", "label", ")", "{", "response", ".", "valueOf", "(", "String", ".", "valueOf", "(", "c", ")", ")", ";", "}", "for", "(", "int", "i", "=", "0", ";", "i", "<", "n", ";", "i", "++", ")", "{", "sparse", ".", "get", "(", "i", ")", ".", "y", "=", "Arrays", ".", "binarySearch", "(", "label", ",", "y", "[", "i", "]", ")", ";", "}", "}", "return", "sparse", ";", "}", "finally", "{", "reader", ".", "close", "(", ")", ";", "}", "}" ]
Parse a libsvm sparse dataset from an input stream. @param name the name of dataset. @param stream the input stream of data. @throws java.io.IOException
[ "Parse", "a", "libsvm", "sparse", "dataset", "from", "an", "input", "stream", "." ]
e27e43e90fbaacce3f99d30120cf9dd6a764c33d
https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/data/src/main/java/smile/data/parser/LibsvmParser.java#L120-L190
17,161
haifengl/smile
data/src/main/java/smile/data/parser/microarray/TXTParser.java
TXTParser.parse
public AttributeDataset parse(String name, String path) throws IOException, ParseException { return parse(name, new File(path)); }
java
public AttributeDataset parse(String name, String path) throws IOException, ParseException { return parse(name, new File(path)); }
[ "public", "AttributeDataset", "parse", "(", "String", "name", ",", "String", "path", ")", "throws", "IOException", ",", "ParseException", "{", "return", "parse", "(", "name", ",", "new", "File", "(", "path", ")", ")", ";", "}" ]
Parse a TXT dataset from given file. @param path the file path of data source. @throws java.io.IOException
[ "Parse", "a", "TXT", "dataset", "from", "given", "file", "." ]
e27e43e90fbaacce3f99d30120cf9dd6a764c33d
https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/data/src/main/java/smile/data/parser/microarray/TXTParser.java#L96-L98
17,162
haifengl/smile
data/src/main/java/smile/data/parser/microarray/TXTParser.java
TXTParser.parse
public AttributeDataset parse(String name, InputStream stream) throws IOException, ParseException { BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); String line = reader.readLine(); if (line == null) { throw new IOException("Empty data source."); } String[] tokens = line.split("\t", -1); int start = 1; int p = tokens.length - 1; if (tokens[1].equalsIgnoreCase("description")) { start = 2; p = tokens.length - 2; } Attribute[] attributes = new Attribute[p]; for (int i = 0; i < p; i++) { attributes[i] = new NumericAttribute(tokens[i+start]); } AttributeDataset data = new AttributeDataset(name, attributes); for (int i = 2; (line = reader.readLine()) != null; i++) { tokens = line.split("\t", -1); if (tokens.length != p+start) { throw new IOException(String.format("Invalid number of elements of line %d: %d", i, tokens.length)); } double[] x = new double[p]; for (int j = 0; j < p; j++) { if (tokens[j+start].isEmpty()) { x[j] = Double.NaN; } else { x[j] = Double.valueOf(tokens[j+start]); } } AttributeDataset.Row datum = data.add(x); datum.name = tokens[0]; if (start == 2) { datum.description = tokens[1]; } } reader.close(); return data; }
java
public AttributeDataset parse(String name, InputStream stream) throws IOException, ParseException { BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); String line = reader.readLine(); if (line == null) { throw new IOException("Empty data source."); } String[] tokens = line.split("\t", -1); int start = 1; int p = tokens.length - 1; if (tokens[1].equalsIgnoreCase("description")) { start = 2; p = tokens.length - 2; } Attribute[] attributes = new Attribute[p]; for (int i = 0; i < p; i++) { attributes[i] = new NumericAttribute(tokens[i+start]); } AttributeDataset data = new AttributeDataset(name, attributes); for (int i = 2; (line = reader.readLine()) != null; i++) { tokens = line.split("\t", -1); if (tokens.length != p+start) { throw new IOException(String.format("Invalid number of elements of line %d: %d", i, tokens.length)); } double[] x = new double[p]; for (int j = 0; j < p; j++) { if (tokens[j+start].isEmpty()) { x[j] = Double.NaN; } else { x[j] = Double.valueOf(tokens[j+start]); } } AttributeDataset.Row datum = data.add(x); datum.name = tokens[0]; if (start == 2) { datum.description = tokens[1]; } } reader.close(); return data; }
[ "public", "AttributeDataset", "parse", "(", "String", "name", ",", "InputStream", "stream", ")", "throws", "IOException", ",", "ParseException", "{", "BufferedReader", "reader", "=", "new", "BufferedReader", "(", "new", "InputStreamReader", "(", "stream", ")", ")", ";", "String", "line", "=", "reader", ".", "readLine", "(", ")", ";", "if", "(", "line", "==", "null", ")", "{", "throw", "new", "IOException", "(", "\"Empty data source.\"", ")", ";", "}", "String", "[", "]", "tokens", "=", "line", ".", "split", "(", "\"\\t\"", ",", "-", "1", ")", ";", "int", "start", "=", "1", ";", "int", "p", "=", "tokens", ".", "length", "-", "1", ";", "if", "(", "tokens", "[", "1", "]", ".", "equalsIgnoreCase", "(", "\"description\"", ")", ")", "{", "start", "=", "2", ";", "p", "=", "tokens", ".", "length", "-", "2", ";", "}", "Attribute", "[", "]", "attributes", "=", "new", "Attribute", "[", "p", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "p", ";", "i", "++", ")", "{", "attributes", "[", "i", "]", "=", "new", "NumericAttribute", "(", "tokens", "[", "i", "+", "start", "]", ")", ";", "}", "AttributeDataset", "data", "=", "new", "AttributeDataset", "(", "name", ",", "attributes", ")", ";", "for", "(", "int", "i", "=", "2", ";", "(", "line", "=", "reader", ".", "readLine", "(", ")", ")", "!=", "null", ";", "i", "++", ")", "{", "tokens", "=", "line", ".", "split", "(", "\"\\t\"", ",", "-", "1", ")", ";", "if", "(", "tokens", ".", "length", "!=", "p", "+", "start", ")", "{", "throw", "new", "IOException", "(", "String", ".", "format", "(", "\"Invalid number of elements of line %d: %d\"", ",", "i", ",", "tokens", ".", "length", ")", ")", ";", "}", "double", "[", "]", "x", "=", "new", "double", "[", "p", "]", ";", "for", "(", "int", "j", "=", "0", ";", "j", "<", "p", ";", "j", "++", ")", "{", "if", "(", "tokens", "[", "j", "+", "start", "]", ".", "isEmpty", "(", ")", ")", "{", "x", "[", "j", "]", "=", "Double", ".", "NaN", ";", "}", "else", "{", "x", "[", "j", "]", "=", "Double", ".", "valueOf", "(", "tokens", "[", "j", "+", "start", "]", ")", ";", "}", "}", "AttributeDataset", ".", "Row", "datum", "=", "data", ".", "add", "(", "x", ")", ";", "datum", ".", "name", "=", "tokens", "[", "0", "]", ";", "if", "(", "start", "==", "2", ")", "{", "datum", ".", "description", "=", "tokens", "[", "1", "]", ";", "}", "}", "reader", ".", "close", "(", ")", ";", "return", "data", ";", "}" ]
Parse a TXT dataset from an input stream. @param name the name of dataset. @param stream the input stream of data. @throws java.io.IOException
[ "Parse", "a", "TXT", "dataset", "from", "an", "input", "stream", "." ]
e27e43e90fbaacce3f99d30120cf9dd6a764c33d
https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/data/src/main/java/smile/data/parser/microarray/TXTParser.java#L123-L170
17,163
haifengl/smile
math/src/main/java/smile/math/matrix/Factory.java
Factory.matrix
public static DenseMatrix matrix(double[][] A) { if (nlmatrixZeros != null) { try { return (DenseMatrix) nlmatrixArray2D.newInstance((Object) A); } catch (Exception e) { logger.error("Failed to call NLMatrix(double[][]): {}", e); } } return new JMatrix(A); }
java
public static DenseMatrix matrix(double[][] A) { if (nlmatrixZeros != null) { try { return (DenseMatrix) nlmatrixArray2D.newInstance((Object) A); } catch (Exception e) { logger.error("Failed to call NLMatrix(double[][]): {}", e); } } return new JMatrix(A); }
[ "public", "static", "DenseMatrix", "matrix", "(", "double", "[", "]", "[", "]", "A", ")", "{", "if", "(", "nlmatrixZeros", "!=", "null", ")", "{", "try", "{", "return", "(", "DenseMatrix", ")", "nlmatrixArray2D", ".", "newInstance", "(", "(", "Object", ")", "A", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "logger", ".", "error", "(", "\"Failed to call NLMatrix(double[][]): {}\"", ",", "e", ")", ";", "}", "}", "return", "new", "JMatrix", "(", "A", ")", ";", "}" ]
Creates a matrix initialized by A.
[ "Creates", "a", "matrix", "initialized", "by", "A", "." ]
e27e43e90fbaacce3f99d30120cf9dd6a764c33d
https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/math/src/main/java/smile/math/matrix/Factory.java#L70-L80
17,164
haifengl/smile
math/src/main/java/smile/math/matrix/Factory.java
Factory.matrix
public static DenseMatrix matrix(int nrows, int ncols) { if (nlmatrixZeros != null) { try { return (DenseMatrix) nlmatrixZeros.newInstance(nrows, ncols); } catch (Exception e) { logger.error("Failed to call NLMatrix(int, int): {}", e); } } return new JMatrix(nrows, ncols); }
java
public static DenseMatrix matrix(int nrows, int ncols) { if (nlmatrixZeros != null) { try { return (DenseMatrix) nlmatrixZeros.newInstance(nrows, ncols); } catch (Exception e) { logger.error("Failed to call NLMatrix(int, int): {}", e); } } return new JMatrix(nrows, ncols); }
[ "public", "static", "DenseMatrix", "matrix", "(", "int", "nrows", ",", "int", "ncols", ")", "{", "if", "(", "nlmatrixZeros", "!=", "null", ")", "{", "try", "{", "return", "(", "DenseMatrix", ")", "nlmatrixZeros", ".", "newInstance", "(", "nrows", ",", "ncols", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "logger", ".", "error", "(", "\"Failed to call NLMatrix(int, int): {}\"", ",", "e", ")", ";", "}", "}", "return", "new", "JMatrix", "(", "nrows", ",", "ncols", ")", ";", "}" ]
Creates a matrix of all zeros.
[ "Creates", "a", "matrix", "of", "all", "zeros", "." ]
e27e43e90fbaacce3f99d30120cf9dd6a764c33d
https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/math/src/main/java/smile/math/matrix/Factory.java#L96-L106
17,165
haifengl/smile
math/src/main/java/smile/math/matrix/Factory.java
Factory.matrix
public static DenseMatrix matrix(int nrows, int ncols, double value) { if (nlmatrixOnes != null) { try { return (DenseMatrix) nlmatrixOnes.newInstance(nrows, ncols, value); } catch (Exception e) { logger.error("Failed to call NLMatrix(int, int, double): {}", e); } } return new JMatrix(nrows, ncols, value); }
java
public static DenseMatrix matrix(int nrows, int ncols, double value) { if (nlmatrixOnes != null) { try { return (DenseMatrix) nlmatrixOnes.newInstance(nrows, ncols, value); } catch (Exception e) { logger.error("Failed to call NLMatrix(int, int, double): {}", e); } } return new JMatrix(nrows, ncols, value); }
[ "public", "static", "DenseMatrix", "matrix", "(", "int", "nrows", ",", "int", "ncols", ",", "double", "value", ")", "{", "if", "(", "nlmatrixOnes", "!=", "null", ")", "{", "try", "{", "return", "(", "DenseMatrix", ")", "nlmatrixOnes", ".", "newInstance", "(", "nrows", ",", "ncols", ",", "value", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "logger", ".", "error", "(", "\"Failed to call NLMatrix(int, int, double): {}\"", ",", "e", ")", ";", "}", "}", "return", "new", "JMatrix", "(", "nrows", ",", "ncols", ",", "value", ")", ";", "}" ]
Creates a matrix filled with given value.
[ "Creates", "a", "matrix", "filled", "with", "given", "value", "." ]
e27e43e90fbaacce3f99d30120cf9dd6a764c33d
https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/math/src/main/java/smile/math/matrix/Factory.java#L109-L119
17,166
haifengl/smile
plot/src/main/java/smile/plot/QQPlot.java
QQPlot.plot
public static PlotCanvas plot(double[] x) { double[] lowerBound = {Math.min(x), GaussianDistribution.getInstance().quantile(1 / (x.length + 1.0))}; double[] upperBound = {Math.max(x), GaussianDistribution.getInstance().quantile(x.length / (x.length + 1.0))}; PlotCanvas canvas = new PlotCanvas(lowerBound, upperBound); canvas.add(new QQPlot(x)); return canvas; }
java
public static PlotCanvas plot(double[] x) { double[] lowerBound = {Math.min(x), GaussianDistribution.getInstance().quantile(1 / (x.length + 1.0))}; double[] upperBound = {Math.max(x), GaussianDistribution.getInstance().quantile(x.length / (x.length + 1.0))}; PlotCanvas canvas = new PlotCanvas(lowerBound, upperBound); canvas.add(new QQPlot(x)); return canvas; }
[ "public", "static", "PlotCanvas", "plot", "(", "double", "[", "]", "x", ")", "{", "double", "[", "]", "lowerBound", "=", "{", "Math", ".", "min", "(", "x", ")", ",", "GaussianDistribution", ".", "getInstance", "(", ")", ".", "quantile", "(", "1", "/", "(", "x", ".", "length", "+", "1.0", ")", ")", "}", ";", "double", "[", "]", "upperBound", "=", "{", "Math", ".", "max", "(", "x", ")", ",", "GaussianDistribution", ".", "getInstance", "(", ")", ".", "quantile", "(", "x", ".", "length", "/", "(", "x", ".", "length", "+", "1.0", ")", ")", "}", ";", "PlotCanvas", "canvas", "=", "new", "PlotCanvas", "(", "lowerBound", ",", "upperBound", ")", ";", "canvas", ".", "add", "(", "new", "QQPlot", "(", "x", ")", ")", ";", "return", "canvas", ";", "}" ]
Create a plot canvas with the one sample Q-Q plot to standard normal distribution. The x-axis is the quantiles of x and the y-axis is the quantiles of normal distribution. @param x a sample set.
[ "Create", "a", "plot", "canvas", "with", "the", "one", "sample", "Q", "-", "Q", "plot", "to", "standard", "normal", "distribution", ".", "The", "x", "-", "axis", "is", "the", "quantiles", "of", "x", "and", "the", "y", "-", "axis", "is", "the", "quantiles", "of", "normal", "distribution", "." ]
e27e43e90fbaacce3f99d30120cf9dd6a764c33d
https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/plot/src/main/java/smile/plot/QQPlot.java#L175-L181
17,167
haifengl/smile
plot/src/main/java/smile/plot/QQPlot.java
QQPlot.plot
public static PlotCanvas plot(double[] x, double[] y) { double[] lowerBound = {Math.min(x), Math.min(y)}; double[] upperBound = {Math.max(x), Math.max(y)}; PlotCanvas canvas = new PlotCanvas(lowerBound, upperBound); canvas.add(new QQPlot(x, y)); return canvas; }
java
public static PlotCanvas plot(double[] x, double[] y) { double[] lowerBound = {Math.min(x), Math.min(y)}; double[] upperBound = {Math.max(x), Math.max(y)}; PlotCanvas canvas = new PlotCanvas(lowerBound, upperBound); canvas.add(new QQPlot(x, y)); return canvas; }
[ "public", "static", "PlotCanvas", "plot", "(", "double", "[", "]", "x", ",", "double", "[", "]", "y", ")", "{", "double", "[", "]", "lowerBound", "=", "{", "Math", ".", "min", "(", "x", ")", ",", "Math", ".", "min", "(", "y", ")", "}", ";", "double", "[", "]", "upperBound", "=", "{", "Math", ".", "max", "(", "x", ")", ",", "Math", ".", "max", "(", "y", ")", "}", ";", "PlotCanvas", "canvas", "=", "new", "PlotCanvas", "(", "lowerBound", ",", "upperBound", ")", ";", "canvas", ".", "add", "(", "new", "QQPlot", "(", "x", ",", "y", ")", ")", ";", "return", "canvas", ";", "}" ]
Create a plot canvas with the two sample Q-Q plot. The x-axis is the quantiles of x and the y-axis is the quantiles of y. @param x a sample set. @param y a sample set.
[ "Create", "a", "plot", "canvas", "with", "the", "two", "sample", "Q", "-", "Q", "plot", ".", "The", "x", "-", "axis", "is", "the", "quantiles", "of", "x", "and", "the", "y", "-", "axis", "is", "the", "quantiles", "of", "y", "." ]
e27e43e90fbaacce3f99d30120cf9dd6a764c33d
https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/plot/src/main/java/smile/plot/QQPlot.java#L204-L210
17,168
haifengl/smile
plot/src/main/java/smile/plot/QQPlot.java
QQPlot.plot
public static PlotCanvas plot(int[] x, DiscreteDistribution d) { double[] lowerBound = {Math.min(x), d.quantile(1 / (x.length + 1.0))}; double[] upperBound = {Math.max(x), d.quantile(x.length / (x.length + 1.0))}; PlotCanvas canvas = new PlotCanvas(lowerBound, upperBound); canvas.add(new QQPlot(x, d)); return canvas; }
java
public static PlotCanvas plot(int[] x, DiscreteDistribution d) { double[] lowerBound = {Math.min(x), d.quantile(1 / (x.length + 1.0))}; double[] upperBound = {Math.max(x), d.quantile(x.length / (x.length + 1.0))}; PlotCanvas canvas = new PlotCanvas(lowerBound, upperBound); canvas.add(new QQPlot(x, d)); return canvas; }
[ "public", "static", "PlotCanvas", "plot", "(", "int", "[", "]", "x", ",", "DiscreteDistribution", "d", ")", "{", "double", "[", "]", "lowerBound", "=", "{", "Math", ".", "min", "(", "x", ")", ",", "d", ".", "quantile", "(", "1", "/", "(", "x", ".", "length", "+", "1.0", ")", ")", "}", ";", "double", "[", "]", "upperBound", "=", "{", "Math", ".", "max", "(", "x", ")", ",", "d", ".", "quantile", "(", "x", ".", "length", "/", "(", "x", ".", "length", "+", "1.0", ")", ")", "}", ";", "PlotCanvas", "canvas", "=", "new", "PlotCanvas", "(", "lowerBound", ",", "upperBound", ")", ";", "canvas", ".", "add", "(", "new", "QQPlot", "(", "x", ",", "d", ")", ")", ";", "return", "canvas", ";", "}" ]
Create a plot canvas with the one sample Q-Q plot to given distribution. The x-axis is the quantiles of x and the y-axis is the quantiles of given distribution. @param x a sample set. @param d a distribution.
[ "Create", "a", "plot", "canvas", "with", "the", "one", "sample", "Q", "-", "Q", "plot", "to", "given", "distribution", ".", "The", "x", "-", "axis", "is", "the", "quantiles", "of", "x", "and", "the", "y", "-", "axis", "is", "the", "quantiles", "of", "given", "distribution", "." ]
e27e43e90fbaacce3f99d30120cf9dd6a764c33d
https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/plot/src/main/java/smile/plot/QQPlot.java#L219-L225
17,169
haifengl/smile
plot/src/main/java/smile/plot/Projection3D.java
Projection3D.precompute
private void precompute() { sinTheta = Math.sin(theta); cosTheta = Math.cos(theta); sinPhi = Math.sin(phi); cosPhi = Math.cos(phi); }
java
private void precompute() { sinTheta = Math.sin(theta); cosTheta = Math.cos(theta); sinPhi = Math.sin(phi); cosPhi = Math.cos(phi); }
[ "private", "void", "precompute", "(", ")", "{", "sinTheta", "=", "Math", ".", "sin", "(", "theta", ")", ";", "cosTheta", "=", "Math", ".", "cos", "(", "theta", ")", ";", "sinPhi", "=", "Math", ".", "sin", "(", "phi", ")", ";", "cosPhi", "=", "Math", ".", "cos", "(", "phi", ")", ";", "}" ]
Pre-computes sin and cos of rotation angles.
[ "Pre", "-", "computes", "sin", "and", "cos", "of", "rotation", "angles", "." ]
e27e43e90fbaacce3f99d30120cf9dd6a764c33d
https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/plot/src/main/java/smile/plot/Projection3D.java#L65-L70
17,170
haifengl/smile
plot/src/main/java/smile/plot/Projection3D.java
Projection3D.project
public double[] project(double[] xyz) { double[] coord = new double[3]; coord[0] = cosTheta * xyz[1] - sinTheta * xyz[0]; coord[1] = cosPhi * xyz[2] - sinPhi * cosTheta * xyz[0] - sinPhi * sinTheta * xyz[1]; coord[2] = cosPhi * sinTheta * xyz[1] + sinPhi * xyz[2] + cosPhi * cosTheta * xyz[0]; return coord; }
java
public double[] project(double[] xyz) { double[] coord = new double[3]; coord[0] = cosTheta * xyz[1] - sinTheta * xyz[0]; coord[1] = cosPhi * xyz[2] - sinPhi * cosTheta * xyz[0] - sinPhi * sinTheta * xyz[1]; coord[2] = cosPhi * sinTheta * xyz[1] + sinPhi * xyz[2] + cosPhi * cosTheta * xyz[0]; return coord; }
[ "public", "double", "[", "]", "project", "(", "double", "[", "]", "xyz", ")", "{", "double", "[", "]", "coord", "=", "new", "double", "[", "3", "]", ";", "coord", "[", "0", "]", "=", "cosTheta", "*", "xyz", "[", "1", "]", "-", "sinTheta", "*", "xyz", "[", "0", "]", ";", "coord", "[", "1", "]", "=", "cosPhi", "*", "xyz", "[", "2", "]", "-", "sinPhi", "*", "cosTheta", "*", "xyz", "[", "0", "]", "-", "sinPhi", "*", "sinTheta", "*", "xyz", "[", "1", "]", ";", "coord", "[", "2", "]", "=", "cosPhi", "*", "sinTheta", "*", "xyz", "[", "1", "]", "+", "sinPhi", "*", "xyz", "[", "2", "]", "+", "cosPhi", "*", "cosTheta", "*", "xyz", "[", "0", "]", ";", "return", "coord", ";", "}" ]
Returns the camera coordinates. @param xyz the world coordinates. @return the camera coordinates.
[ "Returns", "the", "camera", "coordinates", "." ]
e27e43e90fbaacce3f99d30120cf9dd6a764c33d
https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/plot/src/main/java/smile/plot/Projection3D.java#L77-L85
17,171
haifengl/smile
plot/src/main/java/smile/plot/Projection3D.java
Projection3D.z
public double z(double[] xyz) { return cosPhi * sinTheta * xyz[1] + sinPhi * xyz[2] + cosPhi * cosTheta * xyz[0]; }
java
public double z(double[] xyz) { return cosPhi * sinTheta * xyz[1] + sinPhi * xyz[2] + cosPhi * cosTheta * xyz[0]; }
[ "public", "double", "z", "(", "double", "[", "]", "xyz", ")", "{", "return", "cosPhi", "*", "sinTheta", "*", "xyz", "[", "1", "]", "+", "sinPhi", "*", "xyz", "[", "2", "]", "+", "cosPhi", "*", "cosTheta", "*", "xyz", "[", "0", "]", ";", "}" ]
Returns z-axis value in the camera coordinates. @param xyz the world coordinates. @return z-axis value in the camera coordinates.
[ "Returns", "z", "-", "axis", "value", "in", "the", "camera", "coordinates", "." ]
e27e43e90fbaacce3f99d30120cf9dd6a764c33d
https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/plot/src/main/java/smile/plot/Projection3D.java#L92-L94
17,172
haifengl/smile
plot/src/main/java/smile/plot/Projection3D.java
Projection3D.rotate
public void rotate(double t, double p) { theta = theta - t / 100; phi = phi + p / 100; precompute(); reset(); }
java
public void rotate(double t, double p) { theta = theta - t / 100; phi = phi + p / 100; precompute(); reset(); }
[ "public", "void", "rotate", "(", "double", "t", ",", "double", "p", ")", "{", "theta", "=", "theta", "-", "t", "/", "100", ";", "phi", "=", "phi", "+", "p", "/", "100", ";", "precompute", "(", ")", ";", "reset", "(", ")", ";", "}" ]
Rotates the plot, i.e. change the view angle. @param t the change add to &theta; @param p the change add to &phi;
[ "Rotates", "the", "plot", "i", ".", "e", ".", "change", "the", "view", "angle", "." ]
e27e43e90fbaacce3f99d30120cf9dd6a764c33d
https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/plot/src/main/java/smile/plot/Projection3D.java#L133-L138
17,173
haifengl/smile
netlib/src/main/java/smile/netlib/LU.java
LU.pivsign
private static int pivsign(int[] piv, int n) { int pivsign = 1; for (int i = 0; i < n; i++) { if (piv[i] != (i+1)) pivsign = -pivsign; } return pivsign; }
java
private static int pivsign(int[] piv, int n) { int pivsign = 1; for (int i = 0; i < n; i++) { if (piv[i] != (i+1)) pivsign = -pivsign; } return pivsign; }
[ "private", "static", "int", "pivsign", "(", "int", "[", "]", "piv", ",", "int", "n", ")", "{", "int", "pivsign", "=", "1", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "n", ";", "i", "++", ")", "{", "if", "(", "piv", "[", "i", "]", "!=", "(", "i", "+", "1", ")", ")", "pivsign", "=", "-", "pivsign", ";", "}", "return", "pivsign", ";", "}" ]
Returns the pivot sign.
[ "Returns", "the", "pivot", "sign", "." ]
e27e43e90fbaacce3f99d30120cf9dd6a764c33d
https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/netlib/src/main/java/smile/netlib/LU.java#L55-L63
17,174
haifengl/smile
netlib/src/main/java/smile/netlib/LU.java
LU.inverse
@Override public DenseMatrix inverse() { int m = lu.nrows(); int n = lu.ncols(); if (m != n) { throw new IllegalArgumentException(String.format("Matrix is not square: %d x %d", m, n)); } int nb = LAPACK.getInstance().ilaenv(1, "DGETRI", "", n, -1, -1, -1); if (nb < 0) { logger.warn("LAPACK ILAENV error code: {}", nb); } if (nb < 1) nb = 1; int lwork = lu.ncols() * nb; double[] work = new double[lwork]; intW info = new intW(0); LAPACK.getInstance().dgetri(lu.ncols(), lu.data(), lu.ld(), piv, work, lwork, info); if (info.val != 0) { logger.error("LAPACK DGETRI error code: {}", info.val); throw new IllegalArgumentException("LAPACK DGETRI error code: " + info.val); } return lu; }
java
@Override public DenseMatrix inverse() { int m = lu.nrows(); int n = lu.ncols(); if (m != n) { throw new IllegalArgumentException(String.format("Matrix is not square: %d x %d", m, n)); } int nb = LAPACK.getInstance().ilaenv(1, "DGETRI", "", n, -1, -1, -1); if (nb < 0) { logger.warn("LAPACK ILAENV error code: {}", nb); } if (nb < 1) nb = 1; int lwork = lu.ncols() * nb; double[] work = new double[lwork]; intW info = new intW(0); LAPACK.getInstance().dgetri(lu.ncols(), lu.data(), lu.ld(), piv, work, lwork, info); if (info.val != 0) { logger.error("LAPACK DGETRI error code: {}", info.val); throw new IllegalArgumentException("LAPACK DGETRI error code: " + info.val); } return lu; }
[ "@", "Override", "public", "DenseMatrix", "inverse", "(", ")", "{", "int", "m", "=", "lu", ".", "nrows", "(", ")", ";", "int", "n", "=", "lu", ".", "ncols", "(", ")", ";", "if", "(", "m", "!=", "n", ")", "{", "throw", "new", "IllegalArgumentException", "(", "String", ".", "format", "(", "\"Matrix is not square: %d x %d\"", ",", "m", ",", "n", ")", ")", ";", "}", "int", "nb", "=", "LAPACK", ".", "getInstance", "(", ")", ".", "ilaenv", "(", "1", ",", "\"DGETRI\"", ",", "\"\"", ",", "n", ",", "-", "1", ",", "-", "1", ",", "-", "1", ")", ";", "if", "(", "nb", "<", "0", ")", "{", "logger", ".", "warn", "(", "\"LAPACK ILAENV error code: {}\"", ",", "nb", ")", ";", "}", "if", "(", "nb", "<", "1", ")", "nb", "=", "1", ";", "int", "lwork", "=", "lu", ".", "ncols", "(", ")", "*", "nb", ";", "double", "[", "]", "work", "=", "new", "double", "[", "lwork", "]", ";", "intW", "info", "=", "new", "intW", "(", "0", ")", ";", "LAPACK", ".", "getInstance", "(", ")", ".", "dgetri", "(", "lu", ".", "ncols", "(", ")", ",", "lu", ".", "data", "(", ")", ",", "lu", ".", "ld", "(", ")", ",", "piv", ",", "work", ",", "lwork", ",", "info", ")", ";", "if", "(", "info", ".", "val", "!=", "0", ")", "{", "logger", ".", "error", "(", "\"LAPACK DGETRI error code: {}\"", ",", "info", ".", "val", ")", ";", "throw", "new", "IllegalArgumentException", "(", "\"LAPACK DGETRI error code: \"", "+", "info", ".", "val", ")", ";", "}", "return", "lu", ";", "}" ]
Returns the matrix inverse. The LU matrix will overwritten with the inverse of the original matrix.
[ "Returns", "the", "matrix", "inverse", ".", "The", "LU", "matrix", "will", "overwritten", "with", "the", "inverse", "of", "the", "original", "matrix", "." ]
e27e43e90fbaacce3f99d30120cf9dd6a764c33d
https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/netlib/src/main/java/smile/netlib/LU.java#L69-L96
17,175
haifengl/smile
core/src/main/java/smile/neighbor/CoverTree.java
CoverTree.buildCoverTree
private void buildCoverTree() { ArrayList<DistanceSet> pointSet = new ArrayList<>(); ArrayList<DistanceSet> consumedSet = new ArrayList<>(); E point = data[0]; int idx = 0; double maxDist = -1; for (int i = 1; i < data.length; i++) { DistanceSet set = new DistanceSet(i); double dist = distance.d(point, data[i]); set.dist.add(dist); pointSet.add(set); if (dist > maxDist) { maxDist = dist; } } root = batchInsert(idx, getScale(maxDist), getScale(maxDist), pointSet, consumedSet); }
java
private void buildCoverTree() { ArrayList<DistanceSet> pointSet = new ArrayList<>(); ArrayList<DistanceSet> consumedSet = new ArrayList<>(); E point = data[0]; int idx = 0; double maxDist = -1; for (int i = 1; i < data.length; i++) { DistanceSet set = new DistanceSet(i); double dist = distance.d(point, data[i]); set.dist.add(dist); pointSet.add(set); if (dist > maxDist) { maxDist = dist; } } root = batchInsert(idx, getScale(maxDist), getScale(maxDist), pointSet, consumedSet); }
[ "private", "void", "buildCoverTree", "(", ")", "{", "ArrayList", "<", "DistanceSet", ">", "pointSet", "=", "new", "ArrayList", "<>", "(", ")", ";", "ArrayList", "<", "DistanceSet", ">", "consumedSet", "=", "new", "ArrayList", "<>", "(", ")", ";", "E", "point", "=", "data", "[", "0", "]", ";", "int", "idx", "=", "0", ";", "double", "maxDist", "=", "-", "1", ";", "for", "(", "int", "i", "=", "1", ";", "i", "<", "data", ".", "length", ";", "i", "++", ")", "{", "DistanceSet", "set", "=", "new", "DistanceSet", "(", "i", ")", ";", "double", "dist", "=", "distance", ".", "d", "(", "point", ",", "data", "[", "i", "]", ")", ";", "set", ".", "dist", ".", "add", "(", "dist", ")", ";", "pointSet", ".", "add", "(", "set", ")", ";", "if", "(", "dist", ">", "maxDist", ")", "{", "maxDist", "=", "dist", ";", "}", "}", "root", "=", "batchInsert", "(", "idx", ",", "getScale", "(", "maxDist", ")", ",", "getScale", "(", "maxDist", ")", ",", "pointSet", ",", "consumedSet", ")", ";", "}" ]
Builds the cover tree.
[ "Builds", "the", "cover", "tree", "." ]
e27e43e90fbaacce3f99d30120cf9dd6a764c33d
https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/core/src/main/java/smile/neighbor/CoverTree.java#L265-L284
17,176
haifengl/smile
core/src/main/java/smile/neighbor/CoverTree.java
CoverTree.max
private double max(ArrayList<DistanceSet> v) { double max = 0.0; for (DistanceSet n : v) { if (max < n.dist.get(n.dist.size() - 1)) { max = n.dist.get(n.dist.size() - 1); } } return max; }
java
private double max(ArrayList<DistanceSet> v) { double max = 0.0; for (DistanceSet n : v) { if (max < n.dist.get(n.dist.size() - 1)) { max = n.dist.get(n.dist.size() - 1); } } return max; }
[ "private", "double", "max", "(", "ArrayList", "<", "DistanceSet", ">", "v", ")", "{", "double", "max", "=", "0.0", ";", "for", "(", "DistanceSet", "n", ":", "v", ")", "{", "if", "(", "max", "<", "n", ".", "dist", ".", "get", "(", "n", ".", "dist", ".", "size", "(", ")", "-", "1", ")", ")", "{", "max", "=", "n", ".", "dist", ".", "get", "(", "n", ".", "dist", ".", "size", "(", ")", "-", "1", ")", ";", "}", "}", "return", "max", ";", "}" ]
Returns the max distance of the reference point p in current node to it's children nodes. @param v the stack of DistanceNode objects. @return the distance of the furthest child.
[ "Returns", "the", "max", "distance", "of", "the", "reference", "point", "p", "in", "current", "node", "to", "it", "s", "children", "nodes", "." ]
e27e43e90fbaacce3f99d30120cf9dd6a764c33d
https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/core/src/main/java/smile/neighbor/CoverTree.java#L430-L438
17,177
haifengl/smile
symbolic/src/main/java/smile/symbolic/Calculus.java
Calculus.diff
public static String diff(String expression) throws InvalidExpressionException { ExpressionTree expTree = parseToTree(expression); expTree.derive(); expTree.reduce(); return expTree.toString(); }
java
public static String diff(String expression) throws InvalidExpressionException { ExpressionTree expTree = parseToTree(expression); expTree.derive(); expTree.reduce(); return expTree.toString(); }
[ "public", "static", "String", "diff", "(", "String", "expression", ")", "throws", "InvalidExpressionException", "{", "ExpressionTree", "expTree", "=", "parseToTree", "(", "expression", ")", ";", "expTree", ".", "derive", "(", ")", ";", "expTree", ".", "reduce", "(", ")", ";", "return", "expTree", ".", "toString", "(", ")", ";", "}" ]
Compute the symbolic derivative. @param expression the mathematical expression
[ "Compute", "the", "symbolic", "derivative", "." ]
e27e43e90fbaacce3f99d30120cf9dd6a764c33d
https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/symbolic/src/main/java/smile/symbolic/Calculus.java#L30-L37
17,178
haifengl/smile
symbolic/src/main/java/smile/symbolic/Calculus.java
Calculus.diff
public static final double diff(String expression, double val) throws InvalidExpressionException { ExpressionTree expTree = parseToTree(expression); expTree.derive(); expTree.reduce(); return expTree.getVal(); }
java
public static final double diff(String expression, double val) throws InvalidExpressionException { ExpressionTree expTree = parseToTree(expression); expTree.derive(); expTree.reduce(); return expTree.getVal(); }
[ "public", "static", "final", "double", "diff", "(", "String", "expression", ",", "double", "val", ")", "throws", "InvalidExpressionException", "{", "ExpressionTree", "expTree", "=", "parseToTree", "(", "expression", ")", ";", "expTree", ".", "derive", "(", ")", ";", "expTree", ".", "reduce", "(", ")", ";", "return", "expTree", ".", "getVal", "(", ")", ";", "}" ]
Compute numeric derivative @param expression the mathematical expression @param val the value for which to evaluate the expression at @return numeric derivative
[ "Compute", "numeric", "derivative" ]
e27e43e90fbaacce3f99d30120cf9dd6a764c33d
https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/symbolic/src/main/java/smile/symbolic/Calculus.java#L45-L53
17,179
haifengl/smile
symbolic/src/main/java/smile/symbolic/Calculus.java
Calculus.diffReadable
public static String diffReadable(String expression) throws InvalidExpressionException { ExpressionParser p = new ExpressionParser(); return p.format(diff(expression)); }
java
public static String diffReadable(String expression) throws InvalidExpressionException { ExpressionParser p = new ExpressionParser(); return p.format(diff(expression)); }
[ "public", "static", "String", "diffReadable", "(", "String", "expression", ")", "throws", "InvalidExpressionException", "{", "ExpressionParser", "p", "=", "new", "ExpressionParser", "(", ")", ";", "return", "p", ".", "format", "(", "diff", "(", "expression", ")", ")", ";", "}" ]
Compute the reformatted symbolic derivative. @param expression the mathematical expressino @return "readable" form of the derived expression. Unnecessary * are deleted and unary minus is changed from $ to -.
[ "Compute", "the", "reformatted", "symbolic", "derivative", "." ]
e27e43e90fbaacce3f99d30120cf9dd6a764c33d
https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/symbolic/src/main/java/smile/symbolic/Calculus.java#L61-L66
17,180
haifengl/smile
symbolic/src/main/java/smile/symbolic/Calculus.java
Calculus.rewrite
public static String rewrite(String expression) throws InvalidExpressionException { ExpressionTree expTree = parseToTree(expression); expTree.reduce(); return expTree.toString(); }
java
public static String rewrite(String expression) throws InvalidExpressionException { ExpressionTree expTree = parseToTree(expression); expTree.reduce(); return expTree.toString(); }
[ "public", "static", "String", "rewrite", "(", "String", "expression", ")", "throws", "InvalidExpressionException", "{", "ExpressionTree", "expTree", "=", "parseToTree", "(", "expression", ")", ";", "expTree", ".", "reduce", "(", ")", ";", "return", "expTree", ".", "toString", "(", ")", ";", "}" ]
Rewrite the expression to eliminate redundant terms and simplify the expression. @param expression @return @throws InvalidExpressionException
[ "Rewrite", "the", "expression", "to", "eliminate", "redundant", "terms", "and", "simplify", "the", "expression", "." ]
e27e43e90fbaacce3f99d30120cf9dd6a764c33d
https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/symbolic/src/main/java/smile/symbolic/Calculus.java#L74-L81
17,181
haifengl/smile
symbolic/src/main/java/smile/symbolic/Calculus.java
Calculus.parseToTree
private static final ExpressionTree parseToTree(String expression) throws InvalidExpressionException { ExpressionParser parser = new ExpressionParser(); parser.parse(expression); return new ExpressionTree(parser.getVar(), parser.getTokens()); }
java
private static final ExpressionTree parseToTree(String expression) throws InvalidExpressionException { ExpressionParser parser = new ExpressionParser(); parser.parse(expression); return new ExpressionTree(parser.getVar(), parser.getTokens()); }
[ "private", "static", "final", "ExpressionTree", "parseToTree", "(", "String", "expression", ")", "throws", "InvalidExpressionException", "{", "ExpressionParser", "parser", "=", "new", "ExpressionParser", "(", ")", ";", "parser", ".", "parse", "(", "expression", ")", ";", "return", "new", "ExpressionTree", "(", "parser", ".", "getVar", "(", ")", ",", "parser", ".", "getTokens", "(", ")", ")", ";", "}" ]
Parse a mathematical expression and form a binary expression tree. @param expression @return @throws InvalidExpressionException
[ "Parse", "a", "mathematical", "expression", "and", "form", "a", "binary", "expression", "tree", "." ]
e27e43e90fbaacce3f99d30120cf9dd6a764c33d
https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/symbolic/src/main/java/smile/symbolic/Calculus.java#L100-L106
17,182
haifengl/smile
math/src/main/java/smile/stat/distribution/BinomialDistribution.java
BinomialDistribution.rand
@Override public double rand() { double np = n * p; // Poisson approximation for extremely low np if (np < 1.E-6) { return PoissonDistribution.tinyLambdaRand(np); } boolean inv = false; // invert if (p > 0.5) { // faster calculation by inversion inv = true; } if (np < 55) { // inversion method, using chop-down search from 0 if (p <= 0.5) { rng = new ModeSearch(p); } else { rng = new ModeSearch(1.0 - p); // faster calculation by inversion } } else { // ratio of uniforms method if (p <= 0.5) { rng = new Patchwork(p); } else { rng = new Patchwork(1.0 - p); // faster calculation by inversion } } int x = rng.rand(); if (inv) { x = n - x; // undo inversion } return x; }
java
@Override public double rand() { double np = n * p; // Poisson approximation for extremely low np if (np < 1.E-6) { return PoissonDistribution.tinyLambdaRand(np); } boolean inv = false; // invert if (p > 0.5) { // faster calculation by inversion inv = true; } if (np < 55) { // inversion method, using chop-down search from 0 if (p <= 0.5) { rng = new ModeSearch(p); } else { rng = new ModeSearch(1.0 - p); // faster calculation by inversion } } else { // ratio of uniforms method if (p <= 0.5) { rng = new Patchwork(p); } else { rng = new Patchwork(1.0 - p); // faster calculation by inversion } } int x = rng.rand(); if (inv) { x = n - x; // undo inversion } return x; }
[ "@", "Override", "public", "double", "rand", "(", ")", "{", "double", "np", "=", "n", "*", "p", ";", "// Poisson approximation for extremely low np", "if", "(", "np", "<", "1.E-6", ")", "{", "return", "PoissonDistribution", ".", "tinyLambdaRand", "(", "np", ")", ";", "}", "boolean", "inv", "=", "false", ";", "// invert", "if", "(", "p", ">", "0.5", ")", "{", "// faster calculation by inversion", "inv", "=", "true", ";", "}", "if", "(", "np", "<", "55", ")", "{", "// inversion method, using chop-down search from 0", "if", "(", "p", "<=", "0.5", ")", "{", "rng", "=", "new", "ModeSearch", "(", "p", ")", ";", "}", "else", "{", "rng", "=", "new", "ModeSearch", "(", "1.0", "-", "p", ")", ";", "// faster calculation by inversion", "}", "}", "else", "{", "// ratio of uniforms method", "if", "(", "p", "<=", "0.5", ")", "{", "rng", "=", "new", "Patchwork", "(", "p", ")", ";", "}", "else", "{", "rng", "=", "new", "Patchwork", "(", "1.0", "-", "p", ")", ";", "// faster calculation by inversion", "}", "}", "int", "x", "=", "rng", ".", "rand", "(", ")", ";", "if", "(", "inv", ")", "{", "x", "=", "n", "-", "x", ";", "// undo inversion", "}", "return", "x", ";", "}" ]
This function generates a random variate with the binomial distribution. Uses down/up search from the mode by chop-down technique for n*p &lt; 55, and patchwork rejection method for n*p &ge; 55. For n*p &lt; 1.E-6 numerical inaccuracy is avoided by poisson approximation.
[ "This", "function", "generates", "a", "random", "variate", "with", "the", "binomial", "distribution", "." ]
e27e43e90fbaacce3f99d30120cf9dd6a764c33d
https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/math/src/main/java/smile/stat/distribution/BinomialDistribution.java#L200-L237
17,183
haifengl/smile
math/src/main/java/smile/math/distance/EditDistance.java
EditDistance.weightedEdit
private double weightedEdit(char[] x, char[] y) { // switch parameters to use the shorter one as y to save space. if (x.length < y.length) { char[] swap = x; x = y; y = swap; } int radius = (int) Math.round(r * Math.max(x.length, y.length)); double[][] d = new double[2][y.length + 1]; d[0][0] = 0.0; for (int j = 1; j <= y.length; j++) { d[0][j] = d[0][j - 1] + weight[0][y[j]]; } for (int i = 1; i <= x.length; i++) { d[1][0] = d[0][0] + weight[x[i]][0]; int start = 1; int end = y.length; if (radius > 0) { start = i - radius; if (start > 1) d[1][start - 1] = Double.POSITIVE_INFINITY; else start = 1; end = i + radius; if (end < y.length) d[1][end+1] = Double.POSITIVE_INFINITY; else end = y.length; } for (int j = start; j <= end; j++) { double cost = weight[x[i - 1]][y[j - 1]]; d[1][j] = Math.min( d[0][j] + weight[x[i - 1]][0], // deletion d[1][j - 1] + weight[0][y[j - 1]], // insertion d[0][j - 1] + cost); // substitution } double[] swap = d[0]; d[0] = d[1]; d[1] = swap; } return d[0][y.length]; }
java
private double weightedEdit(char[] x, char[] y) { // switch parameters to use the shorter one as y to save space. if (x.length < y.length) { char[] swap = x; x = y; y = swap; } int radius = (int) Math.round(r * Math.max(x.length, y.length)); double[][] d = new double[2][y.length + 1]; d[0][0] = 0.0; for (int j = 1; j <= y.length; j++) { d[0][j] = d[0][j - 1] + weight[0][y[j]]; } for (int i = 1; i <= x.length; i++) { d[1][0] = d[0][0] + weight[x[i]][0]; int start = 1; int end = y.length; if (radius > 0) { start = i - radius; if (start > 1) d[1][start - 1] = Double.POSITIVE_INFINITY; else start = 1; end = i + radius; if (end < y.length) d[1][end+1] = Double.POSITIVE_INFINITY; else end = y.length; } for (int j = start; j <= end; j++) { double cost = weight[x[i - 1]][y[j - 1]]; d[1][j] = Math.min( d[0][j] + weight[x[i - 1]][0], // deletion d[1][j - 1] + weight[0][y[j - 1]], // insertion d[0][j - 1] + cost); // substitution } double[] swap = d[0]; d[0] = d[1]; d[1] = swap; } return d[0][y.length]; }
[ "private", "double", "weightedEdit", "(", "char", "[", "]", "x", ",", "char", "[", "]", "y", ")", "{", "// switch parameters to use the shorter one as y to save space.", "if", "(", "x", ".", "length", "<", "y", ".", "length", ")", "{", "char", "[", "]", "swap", "=", "x", ";", "x", "=", "y", ";", "y", "=", "swap", ";", "}", "int", "radius", "=", "(", "int", ")", "Math", ".", "round", "(", "r", "*", "Math", ".", "max", "(", "x", ".", "length", ",", "y", ".", "length", ")", ")", ";", "double", "[", "]", "[", "]", "d", "=", "new", "double", "[", "2", "]", "[", "y", ".", "length", "+", "1", "]", ";", "d", "[", "0", "]", "[", "0", "]", "=", "0.0", ";", "for", "(", "int", "j", "=", "1", ";", "j", "<=", "y", ".", "length", ";", "j", "++", ")", "{", "d", "[", "0", "]", "[", "j", "]", "=", "d", "[", "0", "]", "[", "j", "-", "1", "]", "+", "weight", "[", "0", "]", "[", "y", "[", "j", "]", "]", ";", "}", "for", "(", "int", "i", "=", "1", ";", "i", "<=", "x", ".", "length", ";", "i", "++", ")", "{", "d", "[", "1", "]", "[", "0", "]", "=", "d", "[", "0", "]", "[", "0", "]", "+", "weight", "[", "x", "[", "i", "]", "]", "[", "0", "]", ";", "int", "start", "=", "1", ";", "int", "end", "=", "y", ".", "length", ";", "if", "(", "radius", ">", "0", ")", "{", "start", "=", "i", "-", "radius", ";", "if", "(", "start", ">", "1", ")", "d", "[", "1", "]", "[", "start", "-", "1", "]", "=", "Double", ".", "POSITIVE_INFINITY", ";", "else", "start", "=", "1", ";", "end", "=", "i", "+", "radius", ";", "if", "(", "end", "<", "y", ".", "length", ")", "d", "[", "1", "]", "[", "end", "+", "1", "]", "=", "Double", ".", "POSITIVE_INFINITY", ";", "else", "end", "=", "y", ".", "length", ";", "}", "for", "(", "int", "j", "=", "start", ";", "j", "<=", "end", ";", "j", "++", ")", "{", "double", "cost", "=", "weight", "[", "x", "[", "i", "-", "1", "]", "]", "[", "y", "[", "j", "-", "1", "]", "]", ";", "d", "[", "1", "]", "[", "j", "]", "=", "Math", ".", "min", "(", "d", "[", "0", "]", "[", "j", "]", "+", "weight", "[", "x", "[", "i", "-", "1", "]", "]", "[", "0", "]", ",", "// deletion", "d", "[", "1", "]", "[", "j", "-", "1", "]", "+", "weight", "[", "0", "]", "[", "y", "[", "j", "-", "1", "]", "]", ",", "// insertion", "d", "[", "0", "]", "[", "j", "-", "1", "]", "+", "cost", ")", ";", "// substitution", "}", "double", "[", "]", "swap", "=", "d", "[", "0", "]", ";", "d", "[", "0", "]", "=", "d", "[", "1", "]", ";", "d", "[", "1", "]", "=", "swap", ";", "}", "return", "d", "[", "0", "]", "[", "y", ".", "length", "]", ";", "}" ]
Weighted edit distance.
[ "Weighted", "edit", "distance", "." ]
e27e43e90fbaacce3f99d30120cf9dd6a764c33d
https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/math/src/main/java/smile/math/distance/EditDistance.java#L166-L217
17,184
haifengl/smile
math/src/main/java/smile/math/distance/EditDistance.java
EditDistance.br
private int br(char[] x, char[] y) { if (x.length > y.length) { char[] swap = x; x = y; y = swap; } final int m = x.length; final int n = y.length; int ZERO_K = n; if (n+2 > FKP[0].length) FKP = new int[2*n+1][n+2]; for (int k = -ZERO_K; k < 0; k++) { int p = -k - 1; FKP[k + ZERO_K][p + 1] = Math.abs(k) - 1; FKP[k + ZERO_K][p] = -Integer.MAX_VALUE; } FKP[ZERO_K][0] = -1; for (int k = 1; k <= ZERO_K; k++) { int p = k - 1; FKP[k + ZERO_K][p + 1] = -1; FKP[k + ZERO_K][p] = -Integer.MAX_VALUE; } int p = n - m - 1; do { p++; for (int i = (p - (n-m))/2; i >= 1; i--) { brf.f(x, y, FKP, ZERO_K, n-m+i, p-i); } for (int i = (n-m+p)/2; i >= 1; i--) { brf.f(x, y, FKP, ZERO_K, n-m-i, p-i); } brf.f(x, y, FKP, ZERO_K, n - m, p); } while (FKP[(n - m) + ZERO_K][p] != m); return p - 1; }
java
private int br(char[] x, char[] y) { if (x.length > y.length) { char[] swap = x; x = y; y = swap; } final int m = x.length; final int n = y.length; int ZERO_K = n; if (n+2 > FKP[0].length) FKP = new int[2*n+1][n+2]; for (int k = -ZERO_K; k < 0; k++) { int p = -k - 1; FKP[k + ZERO_K][p + 1] = Math.abs(k) - 1; FKP[k + ZERO_K][p] = -Integer.MAX_VALUE; } FKP[ZERO_K][0] = -1; for (int k = 1; k <= ZERO_K; k++) { int p = k - 1; FKP[k + ZERO_K][p + 1] = -1; FKP[k + ZERO_K][p] = -Integer.MAX_VALUE; } int p = n - m - 1; do { p++; for (int i = (p - (n-m))/2; i >= 1; i--) { brf.f(x, y, FKP, ZERO_K, n-m+i, p-i); } for (int i = (n-m+p)/2; i >= 1; i--) { brf.f(x, y, FKP, ZERO_K, n-m-i, p-i); } brf.f(x, y, FKP, ZERO_K, n - m, p); } while (FKP[(n - m) + ZERO_K][p] != m); return p - 1; }
[ "private", "int", "br", "(", "char", "[", "]", "x", ",", "char", "[", "]", "y", ")", "{", "if", "(", "x", ".", "length", ">", "y", ".", "length", ")", "{", "char", "[", "]", "swap", "=", "x", ";", "x", "=", "y", ";", "y", "=", "swap", ";", "}", "final", "int", "m", "=", "x", ".", "length", ";", "final", "int", "n", "=", "y", ".", "length", ";", "int", "ZERO_K", "=", "n", ";", "if", "(", "n", "+", "2", ">", "FKP", "[", "0", "]", ".", "length", ")", "FKP", "=", "new", "int", "[", "2", "*", "n", "+", "1", "]", "[", "n", "+", "2", "]", ";", "for", "(", "int", "k", "=", "-", "ZERO_K", ";", "k", "<", "0", ";", "k", "++", ")", "{", "int", "p", "=", "-", "k", "-", "1", ";", "FKP", "[", "k", "+", "ZERO_K", "]", "[", "p", "+", "1", "]", "=", "Math", ".", "abs", "(", "k", ")", "-", "1", ";", "FKP", "[", "k", "+", "ZERO_K", "]", "[", "p", "]", "=", "-", "Integer", ".", "MAX_VALUE", ";", "}", "FKP", "[", "ZERO_K", "]", "[", "0", "]", "=", "-", "1", ";", "for", "(", "int", "k", "=", "1", ";", "k", "<=", "ZERO_K", ";", "k", "++", ")", "{", "int", "p", "=", "k", "-", "1", ";", "FKP", "[", "k", "+", "ZERO_K", "]", "[", "p", "+", "1", "]", "=", "-", "1", ";", "FKP", "[", "k", "+", "ZERO_K", "]", "[", "p", "]", "=", "-", "Integer", ".", "MAX_VALUE", ";", "}", "int", "p", "=", "n", "-", "m", "-", "1", ";", "do", "{", "p", "++", ";", "for", "(", "int", "i", "=", "(", "p", "-", "(", "n", "-", "m", ")", ")", "/", "2", ";", "i", ">=", "1", ";", "i", "--", ")", "{", "brf", ".", "f", "(", "x", ",", "y", ",", "FKP", ",", "ZERO_K", ",", "n", "-", "m", "+", "i", ",", "p", "-", "i", ")", ";", "}", "for", "(", "int", "i", "=", "(", "n", "-", "m", "+", "p", ")", "/", "2", ";", "i", ">=", "1", ";", "i", "--", ")", "{", "brf", ".", "f", "(", "x", ",", "y", ",", "FKP", ",", "ZERO_K", ",", "n", "-", "m", "-", "i", ",", "p", "-", "i", ")", ";", "}", "brf", ".", "f", "(", "x", ",", "y", ",", "FKP", ",", "ZERO_K", ",", "n", "-", "m", ",", "p", ")", ";", "}", "while", "(", "FKP", "[", "(", "n", "-", "m", ")", "+", "ZERO_K", "]", "[", "p", "]", "!=", "m", ")", ";", "return", "p", "-", "1", ";", "}" ]
Berghel & Roach's extended Ukkonen's algorithm.
[ "Berghel", "&", "Roach", "s", "extended", "Ukkonen", "s", "algorithm", "." ]
e27e43e90fbaacce3f99d30120cf9dd6a764c33d
https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/math/src/main/java/smile/math/distance/EditDistance.java#L278-L324
17,185
haifengl/smile
plot/src/main/java/smile/plot/Heatmap.java
Heatmap.init
private void init() { if (x == null) { x = new double[z[0].length]; for (int i = 0; i < x.length; i++) { x[i] = i + 0.5; } } if (y == null) { y = new double[z.length]; for (int i = 0; i < y.length; i++) { y[i] = y.length - i - 0.5; } } // In case of outliers, we use 1% and 99% quantiles as lower and // upper limits instead of min and max. int n = z.length * z[0].length; double[] values = new double[n]; int i = 0; for (double[] zi : z) { for (double zij : zi) { if (!Double.isNaN(zij)) { values[i++] = zij; } } } if (i > 0) { Arrays.sort(values, 0, i); min = values[(int)Math.round(0.01 * i)]; max = values[(int)Math.round(0.99 * (i-1))]; width = (max - min) / palette.length; } }
java
private void init() { if (x == null) { x = new double[z[0].length]; for (int i = 0; i < x.length; i++) { x[i] = i + 0.5; } } if (y == null) { y = new double[z.length]; for (int i = 0; i < y.length; i++) { y[i] = y.length - i - 0.5; } } // In case of outliers, we use 1% and 99% quantiles as lower and // upper limits instead of min and max. int n = z.length * z[0].length; double[] values = new double[n]; int i = 0; for (double[] zi : z) { for (double zij : zi) { if (!Double.isNaN(zij)) { values[i++] = zij; } } } if (i > 0) { Arrays.sort(values, 0, i); min = values[(int)Math.round(0.01 * i)]; max = values[(int)Math.round(0.99 * (i-1))]; width = (max - min) / palette.length; } }
[ "private", "void", "init", "(", ")", "{", "if", "(", "x", "==", "null", ")", "{", "x", "=", "new", "double", "[", "z", "[", "0", "]", ".", "length", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "x", ".", "length", ";", "i", "++", ")", "{", "x", "[", "i", "]", "=", "i", "+", "0.5", ";", "}", "}", "if", "(", "y", "==", "null", ")", "{", "y", "=", "new", "double", "[", "z", ".", "length", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "y", ".", "length", ";", "i", "++", ")", "{", "y", "[", "i", "]", "=", "y", ".", "length", "-", "i", "-", "0.5", ";", "}", "}", "// In case of outliers, we use 1% and 99% quantiles as lower and", "// upper limits instead of min and max.", "int", "n", "=", "z", ".", "length", "*", "z", "[", "0", "]", ".", "length", ";", "double", "[", "]", "values", "=", "new", "double", "[", "n", "]", ";", "int", "i", "=", "0", ";", "for", "(", "double", "[", "]", "zi", ":", "z", ")", "{", "for", "(", "double", "zij", ":", "zi", ")", "{", "if", "(", "!", "Double", ".", "isNaN", "(", "zij", ")", ")", "{", "values", "[", "i", "++", "]", "=", "zij", ";", "}", "}", "}", "if", "(", "i", ">", "0", ")", "{", "Arrays", ".", "sort", "(", "values", ",", "0", ",", "i", ")", ";", "min", "=", "values", "[", "(", "int", ")", "Math", ".", "round", "(", "0.01", "*", "i", ")", "]", ";", "max", "=", "values", "[", "(", "int", ")", "Math", ".", "round", "(", "0.99", "*", "(", "i", "-", "1", ")", ")", "]", ";", "width", "=", "(", "max", "-", "min", ")", "/", "palette", ".", "length", ";", "}", "}" ]
Initialize the internal variables.
[ "Initialize", "the", "internal", "variables", "." ]
e27e43e90fbaacce3f99d30120cf9dd6a764c33d
https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/plot/src/main/java/smile/plot/Heatmap.java#L163-L197
17,186
haifengl/smile
math/src/main/java/smile/math/Complex.java
Complex.minus
public Complex minus(Complex b) { Complex a = this; double real = a.re - b.re; double imag = a.im - b.im; return new Complex(real, imag); }
java
public Complex minus(Complex b) { Complex a = this; double real = a.re - b.re; double imag = a.im - b.im; return new Complex(real, imag); }
[ "public", "Complex", "minus", "(", "Complex", "b", ")", "{", "Complex", "a", "=", "this", ";", "double", "real", "=", "a", ".", "re", "-", "b", ".", "re", ";", "double", "imag", "=", "a", ".", "im", "-", "b", ".", "im", ";", "return", "new", "Complex", "(", "real", ",", "imag", ")", ";", "}" ]
Returns this - b.
[ "Returns", "this", "-", "b", "." ]
e27e43e90fbaacce3f99d30120cf9dd6a764c33d
https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/math/src/main/java/smile/math/Complex.java#L112-L117
17,187
haifengl/smile
math/src/main/java/smile/math/Complex.java
Complex.reciprocal
public Complex reciprocal() { double scale = re * re + im * im; return new Complex(re / scale, -im / scale); }
java
public Complex reciprocal() { double scale = re * re + im * im; return new Complex(re / scale, -im / scale); }
[ "public", "Complex", "reciprocal", "(", ")", "{", "double", "scale", "=", "re", "*", "re", "+", "im", "*", "im", ";", "return", "new", "Complex", "(", "re", "/", "scale", ",", "-", "im", "/", "scale", ")", ";", "}" ]
Returns the reciprocal.
[ "Returns", "the", "reciprocal", "." ]
e27e43e90fbaacce3f99d30120cf9dd6a764c33d
https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/math/src/main/java/smile/math/Complex.java#L167-L170
17,188
haifengl/smile
math/src/main/java/smile/math/Complex.java
Complex.exp
public Complex exp() { return new Complex(Math.exp(re) * Math.cos(im), Math.exp(re) * Math.sin(im)); }
java
public Complex exp() { return new Complex(Math.exp(re) * Math.cos(im), Math.exp(re) * Math.sin(im)); }
[ "public", "Complex", "exp", "(", ")", "{", "return", "new", "Complex", "(", "Math", ".", "exp", "(", "re", ")", "*", "Math", ".", "cos", "(", "im", ")", ",", "Math", ".", "exp", "(", "re", ")", "*", "Math", ".", "sin", "(", "im", ")", ")", ";", "}" ]
Returns the complex exponential.
[ "Returns", "the", "complex", "exponential", "." ]
e27e43e90fbaacce3f99d30120cf9dd6a764c33d
https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/math/src/main/java/smile/math/Complex.java#L189-L191
17,189
haifengl/smile
math/src/main/java/smile/math/Complex.java
Complex.sin
public Complex sin() { return new Complex(Math.sin(re) * Math.cosh(im), Math.cos(re) * Math.sinh(im)); }
java
public Complex sin() { return new Complex(Math.sin(re) * Math.cosh(im), Math.cos(re) * Math.sinh(im)); }
[ "public", "Complex", "sin", "(", ")", "{", "return", "new", "Complex", "(", "Math", ".", "sin", "(", "re", ")", "*", "Math", ".", "cosh", "(", "im", ")", ",", "Math", ".", "cos", "(", "re", ")", "*", "Math", ".", "sinh", "(", "im", ")", ")", ";", "}" ]
Returns the complex sine.
[ "Returns", "the", "complex", "sine", "." ]
e27e43e90fbaacce3f99d30120cf9dd6a764c33d
https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/math/src/main/java/smile/math/Complex.java#L196-L198
17,190
haifengl/smile
core/src/main/java/smile/regression/ElasticNet.java
ElasticNet.getAugmentedResponse
private double[] getAugmentedResponse(double[] y) { double[] ret = new double[y.length + p]; System.arraycopy(y, 0, ret, 0, y.length); return ret; }
java
private double[] getAugmentedResponse(double[] y) { double[] ret = new double[y.length + p]; System.arraycopy(y, 0, ret, 0, y.length); return ret; }
[ "private", "double", "[", "]", "getAugmentedResponse", "(", "double", "[", "]", "y", ")", "{", "double", "[", "]", "ret", "=", "new", "double", "[", "y", ".", "length", "+", "p", "]", ";", "System", ".", "arraycopy", "(", "y", ",", "0", ",", "ret", ",", "0", ",", "y", ".", "length", ")", ";", "return", "ret", ";", "}" ]
transform the original response array by padding 0 at the tail @param y original response array @return response array with padding 0 at tail
[ "transform", "the", "original", "response", "array", "by", "padding", "0", "at", "the", "tail" ]
e27e43e90fbaacce3f99d30120cf9dd6a764c33d
https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/core/src/main/java/smile/regression/ElasticNet.java#L163-L167
17,191
haifengl/smile
core/src/main/java/smile/regression/ElasticNet.java
ElasticNet.getAugmentedData
private double[][] getAugmentedData(double[][] x) { double[][] ret = new double[x.length + p][p]; double padding = c * Math.sqrt(lambda2); for (int i = 0; i < x.length; i++) { for (int j = 0; j < p; j++) { ret[i][j] = c * x[i][j]; } } for (int i = x.length; i < ret.length; i++) { ret[i][i - x.length] = padding; } return ret; }
java
private double[][] getAugmentedData(double[][] x) { double[][] ret = new double[x.length + p][p]; double padding = c * Math.sqrt(lambda2); for (int i = 0; i < x.length; i++) { for (int j = 0; j < p; j++) { ret[i][j] = c * x[i][j]; } } for (int i = x.length; i < ret.length; i++) { ret[i][i - x.length] = padding; } return ret; }
[ "private", "double", "[", "]", "[", "]", "getAugmentedData", "(", "double", "[", "]", "[", "]", "x", ")", "{", "double", "[", "]", "[", "]", "ret", "=", "new", "double", "[", "x", ".", "length", "+", "p", "]", "[", "p", "]", ";", "double", "padding", "=", "c", "*", "Math", ".", "sqrt", "(", "lambda2", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "x", ".", "length", ";", "i", "++", ")", "{", "for", "(", "int", "j", "=", "0", ";", "j", "<", "p", ";", "j", "++", ")", "{", "ret", "[", "i", "]", "[", "j", "]", "=", "c", "*", "x", "[", "i", "]", "[", "j", "]", ";", "}", "}", "for", "(", "int", "i", "=", "x", ".", "length", ";", "i", "<", "ret", ".", "length", ";", "i", "++", ")", "{", "ret", "[", "i", "]", "[", "i", "-", "x", ".", "length", "]", "=", "padding", ";", "}", "return", "ret", ";", "}" ]
transform the original data array by padding a weighted identity matrix and multiply a scaling @param x the original data array @return data with padding
[ "transform", "the", "original", "data", "array", "by", "padding", "a", "weighted", "identity", "matrix", "and", "multiply", "a", "scaling" ]
e27e43e90fbaacce3f99d30120cf9dd6a764c33d
https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/core/src/main/java/smile/regression/ElasticNet.java#L177-L189
17,192
haifengl/smile
data/src/main/java/smile/data/parser/BinarySparseDatasetParser.java
BinarySparseDatasetParser.parse
public BinarySparseDataset parse(String name, URI uri) throws IOException, ParseException { return parse(name, new File(uri)); }
java
public BinarySparseDataset parse(String name, URI uri) throws IOException, ParseException { return parse(name, new File(uri)); }
[ "public", "BinarySparseDataset", "parse", "(", "String", "name", ",", "URI", "uri", ")", "throws", "IOException", ",", "ParseException", "{", "return", "parse", "(", "name", ",", "new", "File", "(", "uri", ")", ")", ";", "}" ]
Parse a binary sparse dataset from given URI. @param uri the URI of data source. @throws java.io.IOException
[ "Parse", "a", "binary", "sparse", "dataset", "from", "given", "URI", "." ]
e27e43e90fbaacce3f99d30120cf9dd6a764c33d
https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/data/src/main/java/smile/data/parser/BinarySparseDatasetParser.java#L61-L63
17,193
haifengl/smile
data/src/main/java/smile/data/parser/BinarySparseDatasetParser.java
BinarySparseDatasetParser.parse
public BinarySparseDataset parse(String name, InputStream stream) throws IOException, ParseException { try (BufferedReader reader = new BufferedReader(new InputStreamReader(stream))) { BinarySparseDataset sparse = new BinarySparseDataset(name); String line = reader.readLine(); if (line == null) { throw new IOException("Empty data source."); } Set<Integer> items = new HashSet<>(); do { line = line.trim(); if (line.isEmpty()) { continue; } String[] s = line.split("\\s+"); items.clear(); for (int i = 0; i < s.length; i++) { items.add(Integer.parseInt(s[i])); } int j = 0; int[] point = new int[items.size()]; for (int i : items) { point[j++] = i; } Arrays.sort(point); sparse.add(point); line = reader.readLine(); } while (line != null); return sparse; } }
java
public BinarySparseDataset parse(String name, InputStream stream) throws IOException, ParseException { try (BufferedReader reader = new BufferedReader(new InputStreamReader(stream))) { BinarySparseDataset sparse = new BinarySparseDataset(name); String line = reader.readLine(); if (line == null) { throw new IOException("Empty data source."); } Set<Integer> items = new HashSet<>(); do { line = line.trim(); if (line.isEmpty()) { continue; } String[] s = line.split("\\s+"); items.clear(); for (int i = 0; i < s.length; i++) { items.add(Integer.parseInt(s[i])); } int j = 0; int[] point = new int[items.size()]; for (int i : items) { point[j++] = i; } Arrays.sort(point); sparse.add(point); line = reader.readLine(); } while (line != null); return sparse; } }
[ "public", "BinarySparseDataset", "parse", "(", "String", "name", ",", "InputStream", "stream", ")", "throws", "IOException", ",", "ParseException", "{", "try", "(", "BufferedReader", "reader", "=", "new", "BufferedReader", "(", "new", "InputStreamReader", "(", "stream", ")", ")", ")", "{", "BinarySparseDataset", "sparse", "=", "new", "BinarySparseDataset", "(", "name", ")", ";", "String", "line", "=", "reader", ".", "readLine", "(", ")", ";", "if", "(", "line", "==", "null", ")", "{", "throw", "new", "IOException", "(", "\"Empty data source.\"", ")", ";", "}", "Set", "<", "Integer", ">", "items", "=", "new", "HashSet", "<>", "(", ")", ";", "do", "{", "line", "=", "line", ".", "trim", "(", ")", ";", "if", "(", "line", ".", "isEmpty", "(", ")", ")", "{", "continue", ";", "}", "String", "[", "]", "s", "=", "line", ".", "split", "(", "\"\\\\s+\"", ")", ";", "items", ".", "clear", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "s", ".", "length", ";", "i", "++", ")", "{", "items", ".", "add", "(", "Integer", ".", "parseInt", "(", "s", "[", "i", "]", ")", ")", ";", "}", "int", "j", "=", "0", ";", "int", "[", "]", "point", "=", "new", "int", "[", "items", ".", "size", "(", ")", "]", ";", "for", "(", "int", "i", ":", "items", ")", "{", "point", "[", "j", "++", "]", "=", "i", ";", "}", "Arrays", ".", "sort", "(", "point", ")", ";", "sparse", ".", "add", "(", "point", ")", ";", "line", "=", "reader", ".", "readLine", "(", ")", ";", "}", "while", "(", "line", "!=", "null", ")", ";", "return", "sparse", ";", "}", "}" ]
Parse a binary sparse dataset from an input stream. @param name the name of dataset. @param stream the input stream of data. @throws java.io.IOException
[ "Parse", "a", "binary", "sparse", "dataset", "from", "an", "input", "stream", "." ]
e27e43e90fbaacce3f99d30120cf9dd6a764c33d
https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/data/src/main/java/smile/data/parser/BinarySparseDatasetParser.java#L115-L152
17,194
haifengl/smile
plot/src/main/java/smile/plot/Hexmap.java
Hexmap.plot
public static PlotCanvas plot(double[][] data) { double[] lowerBound = {-0.5, 0.36}; double[] upperBound = {data[0].length, data.length * 0.87 + 0.5}; PlotCanvas canvas = new PlotCanvas(lowerBound, upperBound, false); canvas.add(new Hexmap(data)); canvas.getAxis(0).setFrameVisible(false); canvas.getAxis(0).setLabelVisible(false); canvas.getAxis(0).setGridVisible(false); canvas.getAxis(1).setFrameVisible(false); canvas.getAxis(1).setLabelVisible(false); canvas.getAxis(1).setGridVisible(false); return canvas; }
java
public static PlotCanvas plot(double[][] data) { double[] lowerBound = {-0.5, 0.36}; double[] upperBound = {data[0].length, data.length * 0.87 + 0.5}; PlotCanvas canvas = new PlotCanvas(lowerBound, upperBound, false); canvas.add(new Hexmap(data)); canvas.getAxis(0).setFrameVisible(false); canvas.getAxis(0).setLabelVisible(false); canvas.getAxis(0).setGridVisible(false); canvas.getAxis(1).setFrameVisible(false); canvas.getAxis(1).setLabelVisible(false); canvas.getAxis(1).setGridVisible(false); return canvas; }
[ "public", "static", "PlotCanvas", "plot", "(", "double", "[", "]", "[", "]", "data", ")", "{", "double", "[", "]", "lowerBound", "=", "{", "-", "0.5", ",", "0.36", "}", ";", "double", "[", "]", "upperBound", "=", "{", "data", "[", "0", "]", ".", "length", ",", "data", ".", "length", "*", "0.87", "+", "0.5", "}", ";", "PlotCanvas", "canvas", "=", "new", "PlotCanvas", "(", "lowerBound", ",", "upperBound", ",", "false", ")", ";", "canvas", ".", "add", "(", "new", "Hexmap", "(", "data", ")", ")", ";", "canvas", ".", "getAxis", "(", "0", ")", ".", "setFrameVisible", "(", "false", ")", ";", "canvas", ".", "getAxis", "(", "0", ")", ".", "setLabelVisible", "(", "false", ")", ";", "canvas", ".", "getAxis", "(", "0", ")", ".", "setGridVisible", "(", "false", ")", ";", "canvas", ".", "getAxis", "(", "1", ")", ".", "setFrameVisible", "(", "false", ")", ";", "canvas", ".", "getAxis", "(", "1", ")", ".", "setLabelVisible", "(", "false", ")", ";", "canvas", ".", "getAxis", "(", "1", ")", ".", "setGridVisible", "(", "false", ")", ";", "return", "canvas", ";", "}" ]
Create a plot canvas with the pseudo hexmap plot of given data. @param data a data matrix to be shown in hexmap.
[ "Create", "a", "plot", "canvas", "with", "the", "pseudo", "hexmap", "plot", "of", "given", "data", "." ]
e27e43e90fbaacce3f99d30120cf9dd6a764c33d
https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/plot/src/main/java/smile/plot/Hexmap.java#L241-L255
17,195
haifengl/smile
plot/src/main/java/smile/swing/table/DateCellEditor.java
DateCellEditor.stopCellEditing
@Override public boolean stopCellEditing() { JFormattedTextField ftf = (JFormattedTextField) getComponent(); if (ftf.isEditValid()) { try { ftf.commitEdit(); } catch (java.text.ParseException ex) { } } else { //text is invalid Toolkit.getDefaultToolkit().beep(); textField.selectAll(); return false; //don't let the editor go away } return super.stopCellEditing(); }
java
@Override public boolean stopCellEditing() { JFormattedTextField ftf = (JFormattedTextField) getComponent(); if (ftf.isEditValid()) { try { ftf.commitEdit(); } catch (java.text.ParseException ex) { } } else { //text is invalid Toolkit.getDefaultToolkit().beep(); textField.selectAll(); return false; //don't let the editor go away } return super.stopCellEditing(); }
[ "@", "Override", "public", "boolean", "stopCellEditing", "(", ")", "{", "JFormattedTextField", "ftf", "=", "(", "JFormattedTextField", ")", "getComponent", "(", ")", ";", "if", "(", "ftf", ".", "isEditValid", "(", ")", ")", "{", "try", "{", "ftf", ".", "commitEdit", "(", ")", ";", "}", "catch", "(", "java", ".", "text", ".", "ParseException", "ex", ")", "{", "}", "}", "else", "{", "//text is invalid", "Toolkit", ".", "getDefaultToolkit", "(", ")", ".", "beep", "(", ")", ";", "textField", ".", "selectAll", "(", ")", ";", "return", "false", ";", "//don't let the editor go away", "}", "return", "super", ".", "stopCellEditing", "(", ")", ";", "}" ]
of this method so that everything gets cleaned up.
[ "of", "this", "method", "so", "that", "everything", "gets", "cleaned", "up", "." ]
e27e43e90fbaacce3f99d30120cf9dd6a764c33d
https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/plot/src/main/java/smile/swing/table/DateCellEditor.java#L129-L144
17,196
haifengl/smile
plot/src/main/java/smile/plot/BarPlot.java
BarPlot.init
private void init() { width = Double.MAX_VALUE; for (int i = 1; i < data.length; i++) { double w = Math.abs(data[i][0] - data[i - 1][0]); if (width > w) { width = w; } } leftTop = new double[data.length][2]; rightTop = new double[data.length][2]; leftBottom = new double[data.length][2]; rightBottom = new double[data.length][2]; for (int i = 0; i < data.length; i++) { leftTop[i][0] = data[i][0] - width / 2; leftTop[i][1] = data[i][1]; rightTop[i][0] = data[i][0] + width / 2; rightTop[i][1] = data[i][1]; leftBottom[i][0] = data[i][0] - width / 2; leftBottom[i][1] = 0; rightBottom[i][0] = data[i][0] + width / 2; rightBottom[i][1] = 0; } }
java
private void init() { width = Double.MAX_VALUE; for (int i = 1; i < data.length; i++) { double w = Math.abs(data[i][0] - data[i - 1][0]); if (width > w) { width = w; } } leftTop = new double[data.length][2]; rightTop = new double[data.length][2]; leftBottom = new double[data.length][2]; rightBottom = new double[data.length][2]; for (int i = 0; i < data.length; i++) { leftTop[i][0] = data[i][0] - width / 2; leftTop[i][1] = data[i][1]; rightTop[i][0] = data[i][0] + width / 2; rightTop[i][1] = data[i][1]; leftBottom[i][0] = data[i][0] - width / 2; leftBottom[i][1] = 0; rightBottom[i][0] = data[i][0] + width / 2; rightBottom[i][1] = 0; } }
[ "private", "void", "init", "(", ")", "{", "width", "=", "Double", ".", "MAX_VALUE", ";", "for", "(", "int", "i", "=", "1", ";", "i", "<", "data", ".", "length", ";", "i", "++", ")", "{", "double", "w", "=", "Math", ".", "abs", "(", "data", "[", "i", "]", "[", "0", "]", "-", "data", "[", "i", "-", "1", "]", "[", "0", "]", ")", ";", "if", "(", "width", ">", "w", ")", "{", "width", "=", "w", ";", "}", "}", "leftTop", "=", "new", "double", "[", "data", ".", "length", "]", "[", "2", "]", ";", "rightTop", "=", "new", "double", "[", "data", ".", "length", "]", "[", "2", "]", ";", "leftBottom", "=", "new", "double", "[", "data", ".", "length", "]", "[", "2", "]", ";", "rightBottom", "=", "new", "double", "[", "data", ".", "length", "]", "[", "2", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "data", ".", "length", ";", "i", "++", ")", "{", "leftTop", "[", "i", "]", "[", "0", "]", "=", "data", "[", "i", "]", "[", "0", "]", "-", "width", "/", "2", ";", "leftTop", "[", "i", "]", "[", "1", "]", "=", "data", "[", "i", "]", "[", "1", "]", ";", "rightTop", "[", "i", "]", "[", "0", "]", "=", "data", "[", "i", "]", "[", "0", "]", "+", "width", "/", "2", ";", "rightTop", "[", "i", "]", "[", "1", "]", "=", "data", "[", "i", "]", "[", "1", "]", ";", "leftBottom", "[", "i", "]", "[", "0", "]", "=", "data", "[", "i", "]", "[", "0", "]", "-", "width", "/", "2", ";", "leftBottom", "[", "i", "]", "[", "1", "]", "=", "0", ";", "rightBottom", "[", "i", "]", "[", "0", "]", "=", "data", "[", "i", "]", "[", "0", "]", "+", "width", "/", "2", ";", "rightBottom", "[", "i", "]", "[", "1", "]", "=", "0", ";", "}", "}" ]
Calculate bar width and position.
[ "Calculate", "bar", "width", "and", "position", "." ]
e27e43e90fbaacce3f99d30120cf9dd6a764c33d
https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/plot/src/main/java/smile/plot/BarPlot.java#L144-L171
17,197
haifengl/smile
math/src/main/java/smile/stat/distribution/HyperGeometricDistribution.java
HyperGeometricDistribution.rand
@Override public double rand() { int mm = m; int nn = n; if (mm > N / 2) { // invert mm mm = N - mm; } if (nn > N / 2) { // invert nn nn = N - nn; } if (nn > mm) { // swap nn and mm int swap = nn; nn = mm; mm = swap; } if (rng == null) { if ((double) nn * mm >= 20 * N) { // use ratio-of-uniforms method rng = new Patchwork(N, mm, nn); } else { // inversion method, using chop-down search from mode rng = new Inversion(N, mm, nn); } } return rng.rand(); }
java
@Override public double rand() { int mm = m; int nn = n; if (mm > N / 2) { // invert mm mm = N - mm; } if (nn > N / 2) { // invert nn nn = N - nn; } if (nn > mm) { // swap nn and mm int swap = nn; nn = mm; mm = swap; } if (rng == null) { if ((double) nn * mm >= 20 * N) { // use ratio-of-uniforms method rng = new Patchwork(N, mm, nn); } else { // inversion method, using chop-down search from mode rng = new Inversion(N, mm, nn); } } return rng.rand(); }
[ "@", "Override", "public", "double", "rand", "(", ")", "{", "int", "mm", "=", "m", ";", "int", "nn", "=", "n", ";", "if", "(", "mm", ">", "N", "/", "2", ")", "{", "// invert mm", "mm", "=", "N", "-", "mm", ";", "}", "if", "(", "nn", ">", "N", "/", "2", ")", "{", "// invert nn", "nn", "=", "N", "-", "nn", ";", "}", "if", "(", "nn", ">", "mm", ")", "{", "// swap nn and mm", "int", "swap", "=", "nn", ";", "nn", "=", "mm", ";", "mm", "=", "swap", ";", "}", "if", "(", "rng", "==", "null", ")", "{", "if", "(", "(", "double", ")", "nn", "*", "mm", ">=", "20", "*", "N", ")", "{", "// use ratio-of-uniforms method", "rng", "=", "new", "Patchwork", "(", "N", ",", "mm", ",", "nn", ")", ";", "}", "else", "{", "// inversion method, using chop-down search from mode", "rng", "=", "new", "Inversion", "(", "N", ",", "mm", ",", "nn", ")", ";", "}", "}", "return", "rng", ".", "rand", "(", ")", ";", "}" ]
Uses inversion by chop-down search from the mode when the mean &lt; 20 and the patchwork-rejection method when the mean &gt; 20.
[ "Uses", "inversion", "by", "chop", "-", "down", "search", "from", "the", "mode", "when", "the", "mean", "&lt", ";", "20", "and", "the", "patchwork", "-", "rejection", "method", "when", "the", "mean", "&gt", ";", "20", "." ]
e27e43e90fbaacce3f99d30120cf9dd6a764c33d
https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/math/src/main/java/smile/stat/distribution/HyperGeometricDistribution.java#L179-L212
17,198
haifengl/smile
core/src/main/java/smile/clustering/linkage/Linkage.java
Linkage.init
void init(double[][] proximity) { size = proximity.length; this.proximity = new float[size * (size+1) / 2]; // row wise /* for (int i = 0, k = 0; i < size; i++) { double[] pi = proximity[i]; for (int j = 0; j <= i; j++, k++) { this.proximity[k] = (float) pi[j]; } } */ // column wise for (int j = 0, k = 0; j < size; j++) { for (int i = j; i < size; i++, k++) { this.proximity[k] = (float) proximity[i][j]; } } }
java
void init(double[][] proximity) { size = proximity.length; this.proximity = new float[size * (size+1) / 2]; // row wise /* for (int i = 0, k = 0; i < size; i++) { double[] pi = proximity[i]; for (int j = 0; j <= i; j++, k++) { this.proximity[k] = (float) pi[j]; } } */ // column wise for (int j = 0, k = 0; j < size; j++) { for (int i = j; i < size; i++, k++) { this.proximity[k] = (float) proximity[i][j]; } } }
[ "void", "init", "(", "double", "[", "]", "[", "]", "proximity", ")", "{", "size", "=", "proximity", ".", "length", ";", "this", ".", "proximity", "=", "new", "float", "[", "size", "*", "(", "size", "+", "1", ")", "/", "2", "]", ";", "// row wise", "/*\n for (int i = 0, k = 0; i < size; i++) {\n double[] pi = proximity[i];\n for (int j = 0; j <= i; j++, k++) {\n this.proximity[k] = (float) pi[j];\n }\n }\n */", "// column wise", "for", "(", "int", "j", "=", "0", ",", "k", "=", "0", ";", "j", "<", "size", ";", "j", "++", ")", "{", "for", "(", "int", "i", "=", "j", ";", "i", "<", "size", ";", "i", "++", ",", "k", "++", ")", "{", "this", ".", "proximity", "[", "k", "]", "=", "(", "float", ")", "proximity", "[", "i", "]", "[", "j", "]", ";", "}", "}", "}" ]
Initialize the linkage with the lower triangular proximity matrix.
[ "Initialize", "the", "linkage", "with", "the", "lower", "triangular", "proximity", "matrix", "." ]
e27e43e90fbaacce3f99d30120cf9dd6a764c33d
https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/core/src/main/java/smile/clustering/linkage/Linkage.java#L46-L66
17,199
haifengl/smile
math/src/main/java/smile/math/distance/MinkowskiDistance.java
MinkowskiDistance.d
public double d(int[] x, int[] y) { if (x.length != y.length) throw new IllegalArgumentException(String.format("Arrays have different length: x[%d], y[%d]", x.length, y.length)); double dist = 0.0; if (weight == null) { for (int i = 0; i < x.length; i++) { double d = Math.abs(x[i] - y[i]); dist += Math.pow(d, p); } } else { if (x.length != weight.length) throw new IllegalArgumentException(String.format("Input vectors and weight vector have different length: %d, %d", x.length, weight.length)); for (int i = 0; i < x.length; i++) { double d = Math.abs(x[i] - y[i]); dist += weight[i] * Math.pow(d, p); } } return Math.pow(dist, 1.0/p); }
java
public double d(int[] x, int[] y) { if (x.length != y.length) throw new IllegalArgumentException(String.format("Arrays have different length: x[%d], y[%d]", x.length, y.length)); double dist = 0.0; if (weight == null) { for (int i = 0; i < x.length; i++) { double d = Math.abs(x[i] - y[i]); dist += Math.pow(d, p); } } else { if (x.length != weight.length) throw new IllegalArgumentException(String.format("Input vectors and weight vector have different length: %d, %d", x.length, weight.length)); for (int i = 0; i < x.length; i++) { double d = Math.abs(x[i] - y[i]); dist += weight[i] * Math.pow(d, p); } } return Math.pow(dist, 1.0/p); }
[ "public", "double", "d", "(", "int", "[", "]", "x", ",", "int", "[", "]", "y", ")", "{", "if", "(", "x", ".", "length", "!=", "y", ".", "length", ")", "throw", "new", "IllegalArgumentException", "(", "String", ".", "format", "(", "\"Arrays have different length: x[%d], y[%d]\"", ",", "x", ".", "length", ",", "y", ".", "length", ")", ")", ";", "double", "dist", "=", "0.0", ";", "if", "(", "weight", "==", "null", ")", "{", "for", "(", "int", "i", "=", "0", ";", "i", "<", "x", ".", "length", ";", "i", "++", ")", "{", "double", "d", "=", "Math", ".", "abs", "(", "x", "[", "i", "]", "-", "y", "[", "i", "]", ")", ";", "dist", "+=", "Math", ".", "pow", "(", "d", ",", "p", ")", ";", "}", "}", "else", "{", "if", "(", "x", ".", "length", "!=", "weight", ".", "length", ")", "throw", "new", "IllegalArgumentException", "(", "String", ".", "format", "(", "\"Input vectors and weight vector have different length: %d, %d\"", ",", "x", ".", "length", ",", "weight", ".", "length", ")", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "x", ".", "length", ";", "i", "++", ")", "{", "double", "d", "=", "Math", ".", "abs", "(", "x", "[", "i", "]", "-", "y", "[", "i", "]", ")", ";", "dist", "+=", "weight", "[", "i", "]", "*", "Math", ".", "pow", "(", "d", ",", "p", ")", ";", "}", "}", "return", "Math", ".", "pow", "(", "dist", ",", "1.0", "/", "p", ")", ";", "}" ]
Minkowski distance between the two arrays of type integer.
[ "Minkowski", "distance", "between", "the", "two", "arrays", "of", "type", "integer", "." ]
e27e43e90fbaacce3f99d30120cf9dd6a764c33d
https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/math/src/main/java/smile/math/distance/MinkowskiDistance.java#L77-L99