id
stringlengths
33
40
content
stringlengths
662
61.5k
max_stars_repo_path
stringlengths
85
97
bugs-dot-jar_data_CAMEL-9243_1957a828
--- BugID: CAMEL-9243 Summary: Invocation of Bean fails when Bean extends and abstract which implements the actual method Description: | The issue described here does NOT exist in 2.15.2 and only manifests in 2.15.3. With the following definition of a Bean: {code} public interface MyBaseInterface { @Handler String hello(@Body String hi); } public abstract static class MyAbstractBean implements MyBaseInterface { public String hello(@Body String hi) { return "Hello " + hi; } public String doCompute(String input) { fail("Should not invoke me"); return null; } } public static class MyConcreteBean extends MyAbstractBean { } {code} The following test case will fail to invoke the proper method: {code} public class BeanHandlerMethodTest extends ContextTestSupport { public void testInterfaceBeanMethod() throws Exception { BeanInfo info = new BeanInfo(context, MyConcreteBean.class); Exchange exchange = new DefaultExchange(context); MyConcreteBean pojo = new MyConcreteBean(); MethodInvocation mi = info.createInvocation(pojo, exchange); assertNotNull(mi); assertEquals("hello", mi.getMethod().getName()); } {code} The issue is how BeanInfo.introspect determines which methods are available to be invoked. At line 344, if the class is public, the interface methods are added to the list: {code} if (Modifier.isPublic(clazz.getModifiers())) { // add additional interface methods List<Method> extraMethods = getInterfaceMethods(clazz); for (Method target : extraMethods) { for (Method source : methods) { if (ObjectHelper.isOverridingMethod(source, target, false)) { overrides.add(target); } } } // remove all the overrides methods extraMethods.removeAll(overrides); methods.addAll(extraMethods); } {code} However, all the methods from the interface are "abstract". Later, when the real implementation is encountered as the code crawls up the tree, the abstract method is not replaced: Line 390: {code} MethodInfo existingMethodInfo = overridesExistingMethod(methodInfo); if (existingMethodInfo != null) { LOG.trace("This method is already overridden in a subclass, so the method from the sub class is preferred: {}", existingMethodInfo); return existingMethodInfo; } {code} Finally, during the invocation, the following was added as part of 2.15.3 release: Line 561: {code} removeAllAbstractMethods(localOperationsWithBody); removeAllAbstractMethods(localOperationsWithNoBody); removeAllAbstractMethods(localOperationsWithCustomAnnotation); removeAllAbstractMethods(localOperationsWithHandlerAnnotation); {code} As a result, the abstract method is removed and not invoked. I think the fix should be to see if the existingMethodInfo references an "abstract' method and if it does and methodInfo does not, replace the existingMethodInfo with methodInfo in the collection. This would preserve the preferences implied with the rest of the code while properly replacing the abstract method with their proper implementations. diff --git a/camel-core/src/main/java/org/apache/camel/component/bean/BeanInfo.java b/camel-core/src/main/java/org/apache/camel/component/bean/BeanInfo.java index d3c7214..a2f6ce8 100644 --- a/camel-core/src/main/java/org/apache/camel/component/bean/BeanInfo.java +++ b/camel-core/src/main/java/org/apache/camel/component/bean/BeanInfo.java @@ -987,7 +987,9 @@ public class BeanInfo { Iterator<MethodInfo> it = methods.iterator(); while (it.hasNext()) { MethodInfo info = it.next(); - if (Modifier.isAbstract(info.getMethod().getModifiers())) { + // if the class is an interface then keep the method + boolean isFromInterface = Modifier.isInterface(info.getMethod().getDeclaringClass().getModifiers()); + if (!isFromInterface && Modifier.isAbstract(info.getMethod().getModifiers())) { // we cannot invoke an abstract method it.remove(); }
bugs-dot-jar/camel_extracted_diff/developer-patch_bugs-dot-jar_CAMEL-9243_1957a828.diff
bugs-dot-jar_data_CAMEL-6936_4954d573
--- BugID: CAMEL-6936 Summary: FTP route with idempotent repo does not detect modified files Description: "Per my forum post:\nhttp://camel.465427.n5.nabble.com/inProgressRepository-Not-clearing-for-items-in-idempotentRepository-td5742613.html\n\nI'm attempting to consume messages from an FTP server using an idempotent repository to ensure that I do not re-download a file unless it has been modified. \n\nHere is my (quite simple) camel configuration: \n{code}\n <beans:bean id=\"downloadRepo\" class=\"org.apache.camel.processor.idempotent.FileIdempotentRepository\" >\n <beans:property name=\"fileStore\" value=\"/tmp/.repo.txt\"/>\n <beans:property name=\"cacheSize\" value=\"25000\"/>\n <beans:property name=\"maxFileStoreSize\" value=\"1000000\"/>\n \ </beans:bean>\n\n <camelContext trace=\"true\" xmlns=\"http://camel.apache.org/schema/spring\">\n \ <endpoint id=\"myFtpEndpoint\" uri=\"ftp://me@localhost?password=****&binary=true&recursive=true&consumer.delay=15000&readLock=changed&passiveMode=true&noop=true&idempotentRepository=#downloadRepo&idempotentKey=$simple{file:name}-$simple{file:modified}\" />\n <endpoint id=\"myFileEndpoint\" uri=\"file:///tmp/files\"/>\n\n \ <route>\n <from uri=\"ref:myFtpEndpoint\" />\n <to uri=\"ref:myFileEndpoint\" />\n </route>\n{code}\n\nWhen I start my application for the first time, all files are correctly downloaded from the FTP server and stored in the target directory, as well as recorded in the idempotent repo. \n\nWhen I restart my application, all files are correctly detected as being in the idempotent repo already on the first poll of the FTP server, and are not re-downloaded: \n\n13-11-04 16:52:10,811 TRACE [Camel (camel-1) thread #0 - ftp://me@localhost] org.apache.camel.component.file.remote.FtpConsumer: FtpFile[name=test1.txt, dir=false, file=true] \n2013-11-04 16:52:10,811 TRACE [Camel (camel-1) thread #0 - ftp://me@localhost] org.apache.camel.component.file.remote.FtpConsumer: This consumer is idempotent and the file has been consumed before. Will skip this file: RemoteFile[test1.txt] \n\nHowever, on all subsequent polls to the FTP server the idempotent check is short-circuited because the file is \"in progress\": \n\n2013-11-04 16:53:10,886 TRACE [Camel (camel-1) thread #0 - ftp://me@localhost] org.apache.camel.component.file.remote.FtpConsumer: FtpFile[name=test1.txt, dir=false, file=true]\n2013-11-04 16:53:10,886 TRACE [Camel (camel-1) thread #0 - ftp://me@localhost] org.apache.camel.component.file.remote.FtpConsumer: Skipping as file is already in progress: test1.txt \n\nI am using camel-ftp:2.11.1 (also observing same behavior with 2.12.1) When I inspect the source code I notice two interesting things. \nFirst, the GenericFileConsumer check that determines whether a file is already inProgress which is called from isValidFile() always adds the file to the inProgressRepository: \n{code}\n protected boolean isInProgress(GenericFile<T> file) { \n String key = file.getAbsoluteFilePath(); \n return !endpoint.getInProgressRepository().add(key); \n } \n{code}\n\nSecond, if a file is determined to match an entry already present in the idempotent repository it is discarded (GenericFileConsumer.isValidFile() returns false). This means it is never published to an exchange, and thus never reaches the code which would remove it from the inProgressRepository. \n\nSince the inProgress check happens before the Idempotent Check, we will always short circuit after we get into the inprogress state, and the file will never actually be checked again. " diff --git a/camel-core/src/main/java/org/apache/camel/component/file/GenericFileConsumer.java b/camel-core/src/main/java/org/apache/camel/component/file/GenericFileConsumer.java index c8452fd..02130d2 100644 --- a/camel-core/src/main/java/org/apache/camel/component/file/GenericFileConsumer.java +++ b/camel-core/src/main/java/org/apache/camel/component/file/GenericFileConsumer.java @@ -484,22 +484,32 @@ public abstract class GenericFileConsumer<T> extends ScheduledBatchPollingConsum return false; } - // if its a file then check we have the file in the idempotent registry already - if (!isDirectory && endpoint.isIdempotent()) { - // use absolute file path as default key, but evaluate if an expression key was configured - String key = file.getAbsoluteFilePath(); - if (endpoint.getIdempotentKey() != null) { - Exchange dummy = endpoint.createExchange(file); - key = endpoint.getIdempotentKey().evaluate(dummy, String.class); + boolean answer = true; + String key = null; + try { + // if its a file then check we have the file in the idempotent registry already + if (!isDirectory && endpoint.isIdempotent()) { + // use absolute file path as default key, but evaluate if an expression key was configured + key = file.getAbsoluteFilePath(); + if (endpoint.getIdempotentKey() != null) { + Exchange dummy = endpoint.createExchange(file); + key = endpoint.getIdempotentKey().evaluate(dummy, String.class); + } + if (key != null && endpoint.getIdempotentRepository().contains(key)) { + log.trace("This consumer is idempotent and the file has been consumed before. Will skip this file: {}", file); + answer = false; + } } - if (key != null && endpoint.getIdempotentRepository().contains(key)) { - log.trace("This consumer is idempotent and the file has been consumed before. Will skip this file: {}", file); - return false; + } finally { + // ensure to run this in finally block in case of runtime exceptions being thrown + if (!answer) { + // remove file from the in progress list as its no longer in progress + endpoint.getInProgressRepository().remove(key); } } // file matched - return true; + return answer; } /** @@ -607,6 +617,7 @@ public abstract class GenericFileConsumer<T> extends ScheduledBatchPollingConsum */ protected boolean isInProgress(GenericFile<T> file) { String key = file.getAbsoluteFilePath(); + // must use add, to have operation as atomic return !endpoint.getInProgressRepository().add(key); }
bugs-dot-jar/camel_extracted_diff/developer-patch_bugs-dot-jar_CAMEL-6936_4954d573.diff
bugs-dot-jar_data_CAMEL-5137_afa1d132
--- BugID: CAMEL-5137 Summary: Timer component does not suspend Description: A route which begins with a Timer consumer does not suspend the consumer when the route is suspended. diff --git a/camel-core/src/main/java/org/apache/camel/component/timer/TimerConsumer.java b/camel-core/src/main/java/org/apache/camel/component/timer/TimerConsumer.java index a2cf79e..13be495 100644 --- a/camel-core/src/main/java/org/apache/camel/component/timer/TimerConsumer.java +++ b/camel-core/src/main/java/org/apache/camel/component/timer/TimerConsumer.java @@ -50,6 +50,11 @@ public class TimerConsumer extends DefaultConsumer { @Override public void run() { + if (!isTaskRunAllowed()) { + // do not run timer task as it was not allowed + return; + } + try { long count = counter.incrementAndGet(); @@ -80,6 +85,14 @@ public class TimerConsumer extends DefaultConsumer { task = null; } + /** + * Whether the timer task is allow to run or not + */ + protected boolean isTaskRunAllowed() { + // only allow running the timer task if we can run and are not suspended + return isRunAllowed() && !isSuspended(); + } + protected void configureTask(TimerTask task, Timer timer) { if (endpoint.isFixedRate()) { if (endpoint.getTime() != null) {
bugs-dot-jar/camel_extracted_diff/developer-patch_bugs-dot-jar_CAMEL-5137_afa1d132.diff
bugs-dot-jar_data_CAMEL-7359_9cb09d14
--- BugID: CAMEL-7359 Summary: Simple Language - Additional after text after inbuilt function call is ignored Description: |- The following Simple expression is valid and runs OK - however it may have been appropriate to report an error to the developer. {code:xml} <setBody> <simple>${bodyAs(java.lang.String) Additional text ignored...}</simple> </setBody> {code} The above seems a somewhat contrived example; However this is a more 'realistic' scenario in which the behaviour is not unexpected - {code:xml} <setBody> <simple>${bodyAs(java.lang.String).toUpperCase()}</simple> </setBody> {code} The above simple expression will simply set the body to be of type java.lang.String, however will not invoke the subsequent toUpperCase() call - likewise no error is reported to the developer. Camel has the same issue when using the function of headerAs and mandatoryBodyAs. diff --git a/camel-core/src/main/java/org/apache/camel/language/simple/ast/SimpleFunctionExpression.java b/camel-core/src/main/java/org/apache/camel/language/simple/ast/SimpleFunctionExpression.java index 32a22b2..4eedcba 100644 --- a/camel-core/src/main/java/org/apache/camel/language/simple/ast/SimpleFunctionExpression.java +++ b/camel-core/src/main/java/org/apache/camel/language/simple/ast/SimpleFunctionExpression.java @@ -238,7 +238,8 @@ public class SimpleFunctionExpression extends LiteralExpression { String key = ObjectHelper.before(keyAndType, ","); String type = ObjectHelper.after(keyAndType, ","); - if (ObjectHelper.isEmpty(key) || ObjectHelper.isEmpty(type)) { + remainder = ObjectHelper.after(remainder, ")"); + if (ObjectHelper.isEmpty(key) || ObjectHelper.isEmpty(type) || ObjectHelper.isNotEmpty(remainder)) { throw new SimpleParserException("Valid syntax: ${headerAs(key, type)} was: " + function, token.getIndex()); } key = StringHelper.removeQuotes(key);
bugs-dot-jar/camel_extracted_diff/developer-patch_bugs-dot-jar_CAMEL-7359_9cb09d14.diff
bugs-dot-jar_data_CAMEL-7304_fa165d6b
--- BugID: CAMEL-7304 Summary: InterceptSendToEndpoint does not work where uri needs to be normalized Description: |- interceptSendToEndpoint("sftp://hostname:22/testDirectory?privateKeyFile=/user/.ssh.id_rsa") is not intercepted because uri passed to InterceptSendToEndpointDefinition is not normalized. As a result InterceptSendToEndpointDefinition createProcessor() method fails to match EndpointHelper.matchEndpoint(routeContext.getCamelContext(), uri, getUri()) and InterceptSendToEndpoint is not created. diff --git a/camel-core/src/main/java/org/apache/camel/model/InterceptSendToEndpointDefinition.java b/camel-core/src/main/java/org/apache/camel/model/InterceptSendToEndpointDefinition.java index 9b8bdc3..be2dcb9 100644 --- a/camel-core/src/main/java/org/apache/camel/model/InterceptSendToEndpointDefinition.java +++ b/camel-core/src/main/java/org/apache/camel/model/InterceptSendToEndpointDefinition.java @@ -22,6 +22,7 @@ import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlRootElement; +import org.apache.camel.CamelContext; import org.apache.camel.Endpoint; import org.apache.camel.Predicate; import org.apache.camel.Processor; @@ -30,6 +31,7 @@ import org.apache.camel.processor.InterceptEndpointProcessor; import org.apache.camel.spi.EndpointStrategy; import org.apache.camel.spi.RouteContext; import org.apache.camel.util.EndpointHelper; +import org.apache.camel.util.URISupport; /** * Represents an XML &lt;interceptToEndpoint/&gt; element @@ -95,7 +97,7 @@ public class InterceptSendToEndpointDefinition extends OutputDefinition<Intercep if (endpoint instanceof InterceptSendToEndpoint) { // endpoint already decorated return endpoint; - } else if (getUri() == null || EndpointHelper.matchEndpoint(routeContext.getCamelContext(), uri, getUri())) { + } else if (getUri() == null || matchPattern(routeContext.getCamelContext(), uri, getUri())) { // only proxy if the uri is matched decorate endpoint with our proxy // should be false by default boolean skip = isSkipSendToOriginalEndpoint(); @@ -121,6 +123,29 @@ public class InterceptSendToEndpointDefinition extends OutputDefinition<Intercep } /** + * Does the uri match the pattern. + * + * @param camelContext the CamelContext + * @param uri the uri + * @param pattern the pattern, which can be an endpoint uri as well + * @return <tt>true</tt> if matched and we should intercept, <tt>false</tt> if not matched, and not intercept. + */ + protected boolean matchPattern(CamelContext camelContext, String uri, String pattern) { + // match using the pattern as-is + boolean match = EndpointHelper.matchEndpoint(camelContext, uri, pattern); + if (!match) { + try { + // the pattern could be an uri, so we need to normalize it before matching again + pattern = URISupport.normalizeUri(pattern); + match = EndpointHelper.matchEndpoint(camelContext, uri, pattern); + } catch (Exception e) { + // ignore + } + } + return match; + } + + /** * Applies this interceptor only if the given predicate is true * * @param predicate the predicate
bugs-dot-jar/camel_extracted_diff/developer-patch_bugs-dot-jar_CAMEL-7304_fa165d6b.diff
bugs-dot-jar_data_CAMEL-6604_4209fabb
--- BugID: CAMEL-6604 Summary: Routing slip and dynamic router EIP - Stream caching not working Description: |- See nabble http://camel.465427.n5.nabble.com/stream-caching-to-HTTP-end-point-tp5736608.html diff --git a/camel-core/src/main/java/org/apache/camel/processor/RecipientListProcessor.java b/camel-core/src/main/java/org/apache/camel/processor/RecipientListProcessor.java index 92b3422..9a9bf91 100644 --- a/camel-core/src/main/java/org/apache/camel/processor/RecipientListProcessor.java +++ b/camel-core/src/main/java/org/apache/camel/processor/RecipientListProcessor.java @@ -30,6 +30,7 @@ import org.apache.camel.impl.ProducerCache; import org.apache.camel.processor.aggregate.AggregationStrategy; import org.apache.camel.spi.RouteContext; import org.apache.camel.util.ExchangeHelper; +import org.apache.camel.util.MessageHelper; import org.apache.camel.util.ServiceHelper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -100,6 +101,8 @@ public class RecipientListProcessor extends MulticastProcessor { // we have already acquired and prepare the producer LOG.trace("RecipientProcessorExchangePair #{} begin: {}", index, exchange); exchange.setProperty(Exchange.RECIPIENT_LIST_ENDPOINT, endpoint.getEndpointUri()); + // ensure stream caching is reset + MessageHelper.resetStreamCache(exchange.getIn()); } public void done() {
bugs-dot-jar/camel_extracted_diff/developer-patch_bugs-dot-jar_CAMEL-6604_4209fabb.diff
bugs-dot-jar_data_CAMEL-6743_745a85ab
--- BugID: CAMEL-6743 Summary: Using @Simple (or others) bean parameter binding for boolean type should eval as predicate Description: |- For example {code} public void read(String body, @Simple("${header.foo} != null") boolean foo) { {code} The foo parameter is a boolean and thus the @Simple expression should be evaluated as a predicate and not as an Expression which happens today. diff --git a/camel-core/src/main/java/org/apache/camel/component/bean/DefaultAnnotationExpressionFactory.java b/camel-core/src/main/java/org/apache/camel/component/bean/DefaultAnnotationExpressionFactory.java index 1038cdf..cf961c3 100644 --- a/camel-core/src/main/java/org/apache/camel/component/bean/DefaultAnnotationExpressionFactory.java +++ b/camel-core/src/main/java/org/apache/camel/component/bean/DefaultAnnotationExpressionFactory.java @@ -21,9 +21,11 @@ import java.lang.reflect.Method; import org.apache.camel.CamelContext; import org.apache.camel.Expression; +import org.apache.camel.Predicate; import org.apache.camel.language.LanguageAnnotation; import org.apache.camel.spi.Language; import org.apache.camel.util.ObjectHelper; +import org.apache.camel.util.PredicateToExpressionAdapter; /** * Default implementation of the {@link AnnotationExpressionFactory}. @@ -42,7 +44,13 @@ public class DefaultAnnotationExpressionFactory implements AnnotationExpressionF throw new IllegalArgumentException("Cannot find the language: " + languageName + " on the classpath"); } String expression = getExpressionFromAnnotation(annotation); - return language.createExpression(expression); + + if (expressionReturnType == Boolean.class || expressionReturnType == boolean.class) { + Predicate predicate = language.createPredicate(expression); + return PredicateToExpressionAdapter.toExpression(predicate); + } else { + return language.createExpression(expression); + } } protected String getExpressionFromAnnotation(Annotation annotation) {
bugs-dot-jar/camel_extracted_diff/developer-patch_bugs-dot-jar_CAMEL-6743_745a85ab.diff
bugs-dot-jar_data_CAMEL-9269_62b2042b
--- BugID: CAMEL-9269 Summary: NotifyBuilder.fromRoute() does not work for some endpoint types Description: "{{NotifyBuilder.fromRoute()}} does not work if the endpoint uri in the {{from()}} clause for a route does not match the actual endpoint uri the exchange was sent to. Because we also have the route id itself available in the exchange, we can use that as a fallback when the match on from endpoint uri doesn't work." diff --git a/camel-core/src/main/java/org/apache/camel/builder/NotifyBuilder.java b/camel-core/src/main/java/org/apache/camel/builder/NotifyBuilder.java index 1c42ad9..e5933494 100644 --- a/camel-core/src/main/java/org/apache/camel/builder/NotifyBuilder.java +++ b/camel-core/src/main/java/org/apache/camel/builder/NotifyBuilder.java @@ -154,6 +154,11 @@ public class NotifyBuilder { @Override public boolean onExchange(Exchange exchange) { String id = EndpointHelper.getRouteIdFromEndpoint(exchange.getFromEndpoint()); + + if (id == null) { + id = exchange.getFromRouteId(); + } + // filter non matching exchanges return EndpointHelper.matchPattern(id, routeId); }
bugs-dot-jar/camel_extracted_diff/developer-patch_bugs-dot-jar_CAMEL-9269_62b2042b.diff
bugs-dot-jar_data_CAMEL-4011_cbffff59
--- BugID: CAMEL-4011 Summary: type converters should return NULL for Double.NaN values instead of 0 Description: | see this discussion...http://camel.465427.n5.nabble.com/XPath-for-an-Integer-td4422095.html Update the ObjectConverter.toXXX() methods to check for Double.NaN and return NULL instead of relying on Number.intValue() diff --git a/camel-core/src/main/java/org/apache/camel/converter/ObjectConverter.java b/camel-core/src/main/java/org/apache/camel/converter/ObjectConverter.java index 465c4e9..24df843 100644 --- a/camel-core/src/main/java/org/apache/camel/converter/ObjectConverter.java +++ b/camel-core/src/main/java/org/apache/camel/converter/ObjectConverter.java @@ -137,6 +137,9 @@ public final class ObjectConverter { if (value instanceof Short) { return (Short) value; } else if (value instanceof Number) { + if (value.equals(Double.NaN)) { + return null; + } Number number = (Number) value; return number.shortValue(); } else if (value instanceof String) { @@ -154,6 +157,9 @@ public final class ObjectConverter { if (value instanceof Integer) { return (Integer) value; } else if (value instanceof Number) { + if (value.equals(Double.NaN)) { + return null; + } Number number = (Number) value; return number.intValue(); } else if (value instanceof String) { @@ -171,6 +177,9 @@ public final class ObjectConverter { if (value instanceof Long) { return (Long) value; } else if (value instanceof Number) { + if (value.equals(Double.NaN)) { + return null; + } Number number = (Number) value; return number.longValue(); } else if (value instanceof String) { @@ -188,6 +197,9 @@ public final class ObjectConverter { if (value instanceof Float) { return (Float) value; } else if (value instanceof Number) { + if (value.equals(Double.NaN)) { + return null; + } Number number = (Number) value; return number.floatValue(); } else if (value instanceof String) {
bugs-dot-jar/camel_extracted_diff/developer-patch_bugs-dot-jar_CAMEL-4011_cbffff59.diff
bugs-dot-jar_data_CAMEL-3281_f7dd2fff
--- BugID: CAMEL-3281 Summary: RouteBuilder - Let if fail if end user is configuring onException etc after routes Description: |- All such cross cutting concerns must be defined before routes. We should throw an exception if end user has configured them after routes, which is currently not supported in the DSL. diff --git a/camel-core/src/main/java/org/apache/camel/builder/RouteBuilder.java b/camel-core/src/main/java/org/apache/camel/builder/RouteBuilder.java index 1300f7d..a5cd8d1 100644 --- a/camel-core/src/main/java/org/apache/camel/builder/RouteBuilder.java +++ b/camel-core/src/main/java/org/apache/camel/builder/RouteBuilder.java @@ -136,6 +136,9 @@ public abstract class RouteBuilder extends BuilderSupport implements RoutesBuild * @return the current builder with the error handler configured */ public RouteBuilder errorHandler(ErrorHandlerBuilder errorHandlerBuilder) { + if (!routeCollection.getRoutes().isEmpty()) { + throw new IllegalArgumentException("errorHandler must be defined before any routes in the RouteBuilder"); + } routeCollection.setCamelContext(getContext()); setErrorHandlerBuilder(errorHandlerBuilder); return this; @@ -147,6 +150,9 @@ public abstract class RouteBuilder extends BuilderSupport implements RoutesBuild * @return the builder */ public InterceptDefinition intercept() { + if (!routeCollection.getRoutes().isEmpty()) { + throw new IllegalArgumentException("intercept must be defined before any routes in the RouteBuilder"); + } routeCollection.setCamelContext(getContext()); return routeCollection.intercept(); } @@ -157,6 +163,9 @@ public abstract class RouteBuilder extends BuilderSupport implements RoutesBuild * @return the builder */ public InterceptFromDefinition interceptFrom() { + if (!routeCollection.getRoutes().isEmpty()) { + throw new IllegalArgumentException("interceptFrom must be defined before any routes in the RouteBuilder"); + } routeCollection.setCamelContext(getContext()); return routeCollection.interceptFrom(); } @@ -168,6 +177,9 @@ public abstract class RouteBuilder extends BuilderSupport implements RoutesBuild * @return the builder */ public InterceptFromDefinition interceptFrom(String uri) { + if (!routeCollection.getRoutes().isEmpty()) { + throw new IllegalArgumentException("interceptFrom must be defined before any routes in the RouteBuilder"); + } routeCollection.setCamelContext(getContext()); return routeCollection.interceptFrom(uri); } @@ -179,6 +191,9 @@ public abstract class RouteBuilder extends BuilderSupport implements RoutesBuild * @return the builder */ public InterceptSendToEndpointDefinition interceptSendToEndpoint(String uri) { + if (!routeCollection.getRoutes().isEmpty()) { + throw new IllegalArgumentException("interceptSendToEndpoint must be defined before any routes in the RouteBuilder"); + } routeCollection.setCamelContext(getContext()); return routeCollection.interceptSendToEndpoint(uri); } @@ -191,6 +206,10 @@ public abstract class RouteBuilder extends BuilderSupport implements RoutesBuild * @return the builder */ public OnExceptionDefinition onException(Class exception) { + // is only allowed at the top currently + if (!routeCollection.getRoutes().isEmpty()) { + throw new IllegalArgumentException("onException must be defined before any routes in the RouteBuilder"); + } routeCollection.setCamelContext(getContext()); return routeCollection.onException(exception); } @@ -217,6 +236,10 @@ public abstract class RouteBuilder extends BuilderSupport implements RoutesBuild * @return the builder */ public OnCompletionDefinition onCompletion() { + // is only allowed at the top currently + if (!routeCollection.getRoutes().isEmpty()) { + throw new IllegalArgumentException("onCompletion must be defined before any routes in the RouteBuilder"); + } routeCollection.setCamelContext(getContext()); return routeCollection.onCompletion(); }
bugs-dot-jar/camel_extracted_diff/developer-patch_bugs-dot-jar_CAMEL-3281_f7dd2fff.diff
bugs-dot-jar_data_CAMEL-8624_597883fa
--- BugID: CAMEL-8624 Summary: Bean component - Potential NPE in BeanInfo Description: |- See nabble http://camel.465427.n5.nabble.com/transformers-not-working-after-update-to-2-15-1-tp5765600.html diff --git a/camel-core/src/main/java/org/apache/camel/component/bean/BeanInfo.java b/camel-core/src/main/java/org/apache/camel/component/bean/BeanInfo.java index d33eb7f..67a0893 100644 --- a/camel-core/src/main/java/org/apache/camel/component/bean/BeanInfo.java +++ b/camel-core/src/main/java/org/apache/camel/component/bean/BeanInfo.java @@ -759,20 +759,22 @@ public class BeanInfo { MethodInfo matched = null; int matchCounter = 0; for (MethodInfo methodInfo : operationList) { - if (methodInfo.getBodyParameterType().isInstance(body)) { - return methodInfo; - } + if (methodInfo.getBodyParameterType() != null) { + if (methodInfo.getBodyParameterType().isInstance(body)) { + return methodInfo; + } - // we should only try to convert, as we are looking for best match - Object value = exchange.getContext().getTypeConverter().tryConvertTo(methodInfo.getBodyParameterType(), exchange, body); - if (value != null) { - if (LOG.isTraceEnabled()) { - LOG.trace("Converted body from: {} to: {}", - body.getClass().getCanonicalName(), methodInfo.getBodyParameterType().getCanonicalName()); + // we should only try to convert, as we are looking for best match + Object value = exchange.getContext().getTypeConverter().tryConvertTo(methodInfo.getBodyParameterType(), exchange, body); + if (value != null) { + if (LOG.isTraceEnabled()) { + LOG.trace("Converted body from: {} to: {}", + body.getClass().getCanonicalName(), methodInfo.getBodyParameterType().getCanonicalName()); + } + matchCounter++; + newBody = value; + matched = methodInfo; } - matchCounter++; - newBody = value; - matched = methodInfo; } } if (matchCounter > 1) {
bugs-dot-jar/camel_extracted_diff/developer-patch_bugs-dot-jar_CAMEL-8624_597883fa.diff
bugs-dot-jar_data_CAMEL-4211_4efddb3f
--- BugID: CAMEL-4211 Summary: URISupport - Normalize URI should support parameters with same key Description: "See nabble\nhttp://camel.465427.n5.nabble.com/Problems-with-jetty-component-and-posts-with-more-then-one-value-for-a-field-tp4576908p4576908.html\n\nThe end user is using jetty producer component to send a HTTP POST/GET to some external client. In the endpoint uri he have the parameters, and there are 2 times {{to}} as parameter key. Currently Camel loses the 2nd {{to}} parameter. " diff --git a/camel-core/src/main/java/org/apache/camel/util/URISupport.java b/camel-core/src/main/java/org/apache/camel/util/URISupport.java index 71abd94..2675786 100644 --- a/camel-core/src/main/java/org/apache/camel/util/URISupport.java +++ b/camel-core/src/main/java/org/apache/camel/util/URISupport.java @@ -22,7 +22,9 @@ import java.net.URISyntaxException; import java.net.URLDecoder; import java.net.URLEncoder; import java.util.ArrayList; +import java.util.Arrays; import java.util.Collections; +import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; @@ -74,7 +76,28 @@ public final class URISupport { if (p >= 0) { String name = URLDecoder.decode(parameter.substring(0, p), CHARSET); String value = URLDecoder.decode(parameter.substring(p + 1), CHARSET); - rc.put(name, value); + + // does the key already exist? + if (rc.containsKey(name)) { + // yes it does, so make sure we can support multiple values, but using a list + // to hold the multiple values + Object existing = rc.get(name); + List<String> list; + if (existing instanceof List) { + list = CastUtils.cast((List<?>) existing); + } else { + // create a new list to hold the multiple values + list = new ArrayList<String>(); + String s = existing != null ? existing.toString() : null; + if (s != null) { + list.add(s); + } + } + list.add(value); + rc.put(name, list); + } else { + rc.put(name, value); + } } else { rc.put(parameter, null); } @@ -134,6 +157,7 @@ public final class URISupport { return value; } + @SuppressWarnings("unchecked") public static String createQueryString(Map<Object, Object> options) throws URISyntaxException { try { if (options.size() > 0) { @@ -147,12 +171,23 @@ public final class URISupport { } String key = (String) o; - String value = (String) options.get(key); - rc.append(URLEncoder.encode(key, CHARSET)); - // only append if value is not null - if (value != null) { - rc.append("="); - rc.append(URLEncoder.encode(value, CHARSET)); + Object value = options.get(key); + + // the value may be a list since the same key has multiple values + if (value instanceof List) { + List<String> list = (List<String>) value; + for (Iterator<String> it = list.iterator(); it.hasNext();) { + String s = it.next(); + appendQueryStringParameter(key, s, rc); + // append & separator if there is more in the list to append + if (it.hasNext()) { + rc.append("&"); + } + } + } else { + // use the value as a String + String s = value != null ? value.toString() : null; + appendQueryStringParameter(key, s, rc); } } return rc.toString(); @@ -166,6 +201,16 @@ public final class URISupport { } } + private static void appendQueryStringParameter(String key, String value, StringBuilder rc) throws UnsupportedEncodingException { + rc.append(URLEncoder.encode(key, CHARSET)); + // only append if value is not null + if (value != null) { + rc.append("="); + rc.append(URLEncoder.encode(value, CHARSET)); + } + } + + /** * Creates a URI from the original URI and the remaining parameters * <p/>
bugs-dot-jar/camel_extracted_diff/developer-patch_bugs-dot-jar_CAMEL-4211_4efddb3f.diff
bugs-dot-jar_data_CAMEL-9032_108d94f7
--- BugID: CAMEL-9032 Summary: Bean component - Should filter out abstract methods Description: |- If you call a method on a bean then the introspector should filter out abstract methods if there is class inheritance with abstract defined methods. See SO http://stackoverflow.com/questions/31671894/camel-ambiguousmethodcallexception-abstract-classes diff --git a/camel-core/src/main/java/org/apache/camel/component/bean/BeanInfo.java b/camel-core/src/main/java/org/apache/camel/component/bean/BeanInfo.java index 1b34622..d3c7214 100644 --- a/camel-core/src/main/java/org/apache/camel/component/bean/BeanInfo.java +++ b/camel-core/src/main/java/org/apache/camel/component/bean/BeanInfo.java @@ -557,6 +557,12 @@ public class BeanInfo { final List<MethodInfo> localOperationsWithCustomAnnotation = new ArrayList<MethodInfo>(operationsWithCustomAnnotation); final List<MethodInfo> localOperationsWithHandlerAnnotation = new ArrayList<MethodInfo>(operationsWithHandlerAnnotation); + // remove all abstract methods + removeAllAbstractMethods(localOperationsWithBody); + removeAllAbstractMethods(localOperationsWithNoBody); + removeAllAbstractMethods(localOperationsWithCustomAnnotation); + removeAllAbstractMethods(localOperationsWithHandlerAnnotation); + if (name != null) { // filter all lists to only include methods with this name removeNonMatchingMethods(localOperationsWithHandlerAnnotation, name); @@ -831,11 +837,6 @@ public class BeanInfo { return false; } - // must not be abstract - if (Modifier.isAbstract(method.getModifiers())) { - return false; - } - // return type must not be an Exchange and it should not be a bridge method if ((method.getReturnType() != null && Exchange.class.isAssignableFrom(method.getReturnType())) || method.isBridge()) { return false; @@ -982,6 +983,17 @@ public class BeanInfo { } } + private void removeAllAbstractMethods(List<MethodInfo> methods) { + Iterator<MethodInfo> it = methods.iterator(); + while (it.hasNext()) { + MethodInfo info = it.next(); + if (Modifier.isAbstract(info.getMethod().getModifiers())) { + // we cannot invoke an abstract method + it.remove(); + } + } + } + private boolean matchMethod(Method method, String methodName) { if (methodName == null) { return true;
bugs-dot-jar/camel_extracted_diff/developer-patch_bugs-dot-jar_CAMEL-9032_108d94f7.diff
bugs-dot-jar_data_CAMEL-7513_85ced066
--- BugID: CAMEL-7513 Summary: Using JPA entities as the argument in Aggregator using POJO Description: "I have an Aggregator POJO with this method :\n\npublic Map<Hoteles, List<EventoPrecio>> agregaEventoPrecio(Map<Hoteles, List<EventoPrecio>> lista, EventoPrecio evento) \n\nWith this route :\n\nfrom(\"timer://tesipro?fixedRate=true&period=60000\").\nbeanRef(\"uploadARIService\", \"getEventosPrecio\").\naggregate(constant(true), AggregationStrategies.bean(AgregadorEventos.class, \"agregaEventoPrecio\")).\ncompletionSize(100).\nlog(\"Ejecucion de Quartz \");\n\nAnd I get this error :\n\nError occurred during starting Camel: CamelContext(249-camel-9) due Parameter annotations at index 1 is not supported on method: public java.util.HashMap com.tesipro.conectores.interfaces.tesiproconpush.camel.AgregadorEventos.agregaEventoPrecio(java.util.HashMap,com.tesipro.conectores.domain.EventoPrecio) \ \n\nIt seems the problem is that annotations are not supported in the aggregator arguments nor in the argument class.\n\nhttps://github.com/apache/camel/blob/3f4f8e9ddcc8de32cca084927a10c5b3bceef7f9/camel-core/src/main/java/org/apache/camel/processor/aggregate/AggregationStrategyBeanInfo.java#L67" diff --git a/camel-core/src/main/java/org/apache/camel/processor/aggregate/AggregationStrategyBeanInfo.java b/camel-core/src/main/java/org/apache/camel/processor/aggregate/AggregationStrategyBeanInfo.java index f898be7..ed93a96e 100644 --- a/camel-core/src/main/java/org/apache/camel/processor/aggregate/AggregationStrategyBeanInfo.java +++ b/camel-core/src/main/java/org/apache/camel/processor/aggregate/AggregationStrategyBeanInfo.java @@ -16,6 +16,7 @@ */ package org.apache.camel.processor.aggregate; +import java.lang.annotation.Annotation; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; @@ -62,10 +63,11 @@ public class AggregationStrategyBeanInfo { } // must not have annotations as they are not supported (yet) - for (int i = 0; i < size; i++) { - Class<?> type = parameterTypes[i]; - if (type.getAnnotations().length > 0) { - throw new IllegalArgumentException("Parameter annotations at index " + i + " is not supported on method: " + method); + Annotation[][] parameterAnnotations = method.getParameterAnnotations(); + for (int i = 0; i < parameterAnnotations.length; i++) { + Annotation[] annotations = parameterAnnotations[i]; + if (annotations.length > 0) { + throw new IllegalArgumentException("Method parameter annotation: " + annotations[0] + " at index: " + i + " is not supported on method: " + method); } }
bugs-dot-jar/camel_extracted_diff/developer-patch_bugs-dot-jar_CAMEL-7513_85ced066.diff
bugs-dot-jar_data_CAMEL-8584_dd0f74c0
--- BugID: CAMEL-8584 Summary: Circuit breaker does not honour halfOpenAfter period Description: |- The CircuitBreakerLoadBalancer will always switch to a half-open state immediately after the first rejected message instead of honouring the halfOpenAfter period. It's due to the failed message count getting reset in the rejectExchange method: https://github.com/apache/camel/blob/master/camel-core/src/main/java/org/apache/camel/processor/loadbalancer/CircuitBreakerLoadBalancer.java#L207 diff --git a/camel-core/src/main/java/org/apache/camel/processor/loadbalancer/CircuitBreakerLoadBalancer.java b/camel-core/src/main/java/org/apache/camel/processor/loadbalancer/CircuitBreakerLoadBalancer.java index f760311..645b477 100644 --- a/camel-core/src/main/java/org/apache/camel/processor/loadbalancer/CircuitBreakerLoadBalancer.java +++ b/camel-core/src/main/java/org/apache/camel/processor/loadbalancer/CircuitBreakerLoadBalancer.java @@ -200,11 +200,6 @@ public class CircuitBreakerLoadBalancer extends LoadBalancerSupport implements T private boolean rejectExchange(final Exchange exchange, final AsyncCallback callback) { exchange.setException(new RejectedExecutionException("CircuitBreaker Open: failures: " + failures + ", lastFailure: " + lastFailure)); - /* - * If the circuit opens, we have to prevent the execution of any - * processor. The failures count can be set to 0. - */ - failures.set(0); callback.done(true); return true; }
bugs-dot-jar/camel_extracted_diff/developer-patch_bugs-dot-jar_CAMEL-8584_dd0f74c0.diff
bugs-dot-jar_data_CAMEL-3428_320545cd
--- BugID: CAMEL-3428 Summary: DefaultCamelContext.getEndpoint(String name, Class<T> endpointType) throws Nullpointer for unknown endpoint Description: "The method getEndpoint throws an NullPointerException when it's called with an unknown endpoint name:\n\njava.lang.NullPointerException\n\tat org.apache.camel.impl.DefaultCamelContext.getEndpoint(DefaultCamelContext.java:480)\n\tat org.apache.camel.impl.DefaultCamelContextTest.testGetEndPointByTypeUnknown(DefaultCamelContextTest.java:95)\n\nThe patch is attached.\n" diff --git a/camel-core/src/main/java/org/apache/camel/impl/DefaultCamelContext.java b/camel-core/src/main/java/org/apache/camel/impl/DefaultCamelContext.java index 751e35b..5454442 100644 --- a/camel-core/src/main/java/org/apache/camel/impl/DefaultCamelContext.java +++ b/camel-core/src/main/java/org/apache/camel/impl/DefaultCamelContext.java @@ -16,6 +16,8 @@ */ package org.apache.camel.impl; +import static java.lang.String.format; + import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; @@ -465,7 +467,9 @@ public class DefaultCamelContext extends ServiceSupport implements CamelContext, public <T extends Endpoint> T getEndpoint(String name, Class<T> endpointType) { Endpoint endpoint = getEndpoint(name); - + if(endpoint == null){ + throw new IllegalArgumentException("No endpoint found with name: " + name); + } if (endpoint instanceof InterceptSendToEndpoint) { endpoint = ((InterceptSendToEndpoint) endpoint).getDelegate(); }
bugs-dot-jar/camel_extracted_diff/developer-patch_bugs-dot-jar_CAMEL-3428_320545cd.diff
bugs-dot-jar_data_CAMEL-9238_169b981e
--- BugID: CAMEL-9238 Summary: NPE while GenericFile.changeFileName Description: "If a relative file path is specified for the {{move}} or {{moveFailed}} Attribute of the file2 component, a NullPointerException is thrown while processing the onCompletion commit resp. rollback strategy.\n\nAnd because the processed file cannot be moved away, the processing is restarted again and so on...\n\nWrong code line (GenericFile.java:203 in camel-core V2.15.3):\n{code:java}\nObjectHelper.after(newFileName, newEndpointPath + File.separatorChar);\n{code}\nwhen {{newFileName}} and {{newEndpointPath}} are both relative paths.\n\n\nStacktrace:\n{code:java}\njava.lang.NullPointerException\n\tat java.io.File.<init>(File.java:277) ~[?:1.8.0_60]\n\tat org.apache.camel.component.file.GenericFile.changeFileName(GenericFile.java:207) ~[camel-core-2.15.3.jar:2.15.3]\n\tat org.apache.camel.component.file.strategy.GenericFileExpressionRenamer.renameFile(GenericFileExpressionRenamer.java:41) ~[camel-core-2.15.3.jar:2.15.3]\n\tat org.apache.camel.component.file.strategy.GenericFileRenameProcessStrategy.commit(GenericFileRenameProcessStrategy.java:87) ~[camel-core-2.15.3.jar:2.15.3]\n\tat org.apache.camel.component.file.GenericFileOnCompletion.processStrategyCommit(GenericFileOnCompletion.java:124) [camel-core-2.15.3.jar:2.15.3]\n\tat org.apache.camel.component.file.GenericFileOnCompletion.onCompletion(GenericFileOnCompletion.java:80) [camel-core-2.15.3.jar:2.15.3]\n\tat org.apache.camel.component.file.GenericFileOnCompletion.onComplete(GenericFileOnCompletion.java:54) [camel-core-2.15.3.jar:2.15.3]\n\tat org.apache.camel.util.UnitOfWorkHelper.doneSynchronizations(UnitOfWorkHelper.java:104) [camel-core-2.15.3.jar:2.15.3]\n\tat org.apache.camel.impl.DefaultUnitOfWork.done(DefaultUnitOfWork.java:229) [camel-core-2.15.3.jar:2.15.3]\n\tat org.apache.camel.util.UnitOfWorkHelper.doneUow(UnitOfWorkHelper.java:65) [camel-core-2.15.3.jar:2.15.3]\n\tat org.apache.camel.processor.CamelInternalProcessor$UnitOfWorkProcessorAdvice.after(CamelInternalProcessor.java:637) [camel-core-2.15.3.jar:2.15.3]\n\tat org.apache.camel.processor.CamelInternalProcessor$UnitOfWorkProcessorAdvice.after(CamelInternalProcessor.java:605) [camel-core-2.15.3.jar:2.15.3]\n\tat org.apache.camel.processor.CamelInternalProcessor$InternalCallback.done(CamelInternalProcessor.java:239) [camel-core-2.15.3.jar:2.15.3]\n\tat org.apache.camel.processor.Pipeline.process(Pipeline.java:106) [camel-core-2.15.3.jar:2.15.3]\n\tat org.apache.camel.processor.CamelInternalProcessor.process(CamelInternalProcessor.java:190) [camel-core-2.15.3.jar:2.15.3]\n\tat org.apache.camel.component.file.GenericFileConsumer.processExchange(GenericFileConsumer.java:439) [camel-core-2.15.3.jar:2.15.3]\n\tat org.apache.camel.component.file.GenericFileConsumer.processBatch(GenericFileConsumer.java:211) [camel-core-2.15.3.jar:2.15.3]\n\tat org.apache.camel.component.file.GenericFileConsumer.poll(GenericFileConsumer.java:175) [camel-core-2.15.3.jar:2.15.3]\n\tat org.apache.camel.impl.ScheduledPollConsumer.doRun(ScheduledPollConsumer.java:174) [camel-core-2.15.3.jar:2.15.3]\n\tat org.apache.camel.impl.ScheduledPollConsumer.run(ScheduledPollConsumer.java:101) [camel-core-2.15.3.jar:2.15.3]\n\tat java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511) [?:1.8.0_60]\n\tat java.util.concurrent.FutureTask.runAndReset(FutureTask.java:308) [?:1.8.0_60]\n\tat java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$301(ScheduledThreadPoolExecutor.java:180) [?:1.8.0_60]\n\tat java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:294) [?:1.8.0_60]\n\tat java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [?:1.8.0_60]\n\tat java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [?:1.8.0_60]\n{code}" diff --git a/camel-core/src/main/java/org/apache/camel/component/file/GenericFile.java b/camel-core/src/main/java/org/apache/camel/component/file/GenericFile.java index 907de21..e517550 100644 --- a/camel-core/src/main/java/org/apache/camel/component/file/GenericFile.java +++ b/camel-core/src/main/java/org/apache/camel/component/file/GenericFile.java @@ -185,7 +185,7 @@ public class GenericFile<T> implements WrappedFile<T> { // Make sure the names is normalized. String newFileName = FileUtil.normalizePath(newName); - String newEndpointPath = FileUtil.normalizePath(endpointPath); + String newEndpointPath = FileUtil.normalizePath(endpointPath.endsWith("" + File.separatorChar) ? endpointPath : endpointPath + File.separatorChar); LOG.trace("Normalized endpointPath: {}", newEndpointPath); LOG.trace("Normalized newFileName: ()", newFileName);
bugs-dot-jar/camel_extracted_diff/developer-patch_bugs-dot-jar_CAMEL-9238_169b981e.diff
bugs-dot-jar_data_CAMEL-7018_3244c1e5
--- BugID: CAMEL-7018 Summary: Using custom beans with @ManagedResource shows unavailable standard attributes Description: |- If you have a custom bean with @ManagedResource and your own attr/ops then Camel adds its default attrs/ops which it should not as they are not available. See screenshot diff --git a/camel-core/src/main/java/org/apache/camel/component/seda/SedaEndpoint.java b/camel-core/src/main/java/org/apache/camel/component/seda/SedaEndpoint.java index 9d4ade2..ffe2f6d 100644 --- a/camel-core/src/main/java/org/apache/camel/component/seda/SedaEndpoint.java +++ b/camel-core/src/main/java/org/apache/camel/component/seda/SedaEndpoint.java @@ -308,6 +308,7 @@ public class SedaEndpoint extends DefaultEndpoint implements BrowsableEndpoint, this.purgeWhenStopping = purgeWhenStopping; } + @ManagedAttribute(description = "Singleton") public boolean isSingleton() { return true; } @@ -425,6 +426,11 @@ public class SedaEndpoint extends DefaultEndpoint implements BrowsableEndpoint, return getCamelContext().getManagementName(); } + @ManagedAttribute(description = "Endpoint URI", mask = true) + public String getEndpointUri() { + return super.getEndpointUri(); + } + @ManagedAttribute(description = "Endpoint service state") public String getState() { return getStatus().name(); diff --git a/camel-core/src/main/java/org/apache/camel/management/DefaultManagementMBeanAssembler.java b/camel-core/src/main/java/org/apache/camel/management/DefaultManagementMBeanAssembler.java index 262b520..fde3592 100644 --- a/camel-core/src/main/java/org/apache/camel/management/DefaultManagementMBeanAssembler.java +++ b/camel-core/src/main/java/org/apache/camel/management/DefaultManagementMBeanAssembler.java @@ -60,7 +60,7 @@ public class DefaultManagementMBeanAssembler implements ManagementMBeanAssembler if (custom != null && ObjectHelper.hasAnnotation(custom.getClass().getAnnotations(), ManagedResource.class)) { LOG.trace("Assembling MBeanInfo for: {} from custom @ManagedResource object: {}", name, custom); // get the mbean info from the custom managed object - mbi = assembler.getMBeanInfo(obj, custom, name.toString()); + mbi = assembler.getMBeanInfo(null, custom, name.toString()); // and let the custom object be registered in JMX obj = custom; } diff --git a/camel-core/src/main/java/org/apache/camel/management/MBeanInfoAssembler.java b/camel-core/src/main/java/org/apache/camel/management/MBeanInfoAssembler.java index 56b5a14..84f0470 100644 --- a/camel-core/src/main/java/org/apache/camel/management/MBeanInfoAssembler.java +++ b/camel-core/src/main/java/org/apache/camel/management/MBeanInfoAssembler.java @@ -97,7 +97,7 @@ public class MBeanInfoAssembler implements Service { */ public ModelMBeanInfo getMBeanInfo(Object defaultManagedBean, Object customManagedBean, String objectName) throws JMException { // skip proxy classes - if (Proxy.isProxyClass(defaultManagedBean.getClass())) { + if (defaultManagedBean != null && Proxy.isProxyClass(defaultManagedBean.getClass())) { LOG.trace("Skip creating ModelMBeanInfo due proxy class {}", defaultManagedBean.getClass()); return null; } @@ -110,10 +110,12 @@ public class MBeanInfoAssembler implements Service { Set<ModelMBeanNotificationInfo> mBeanNotifications = new LinkedHashSet<ModelMBeanNotificationInfo>(); // extract details from default managed bean - extractAttributesAndOperations(defaultManagedBean.getClass(), attributes, operations); - extractMbeanAttributes(defaultManagedBean, attributes, mBeanAttributes, mBeanOperations); - extractMbeanOperations(defaultManagedBean, operations, mBeanOperations); - extractMbeanNotifications(defaultManagedBean, mBeanNotifications); + if (defaultManagedBean != null) { + extractAttributesAndOperations(defaultManagedBean.getClass(), attributes, operations); + extractMbeanAttributes(defaultManagedBean, attributes, mBeanAttributes, mBeanOperations); + extractMbeanOperations(defaultManagedBean, operations, mBeanOperations); + extractMbeanNotifications(defaultManagedBean, mBeanNotifications); + } // extract details from custom managed bean if (customManagedBean != null) {
bugs-dot-jar/camel_extracted_diff/developer-patch_bugs-dot-jar_CAMEL-7018_3244c1e5.diff
bugs-dot-jar_data_CAMEL-4467_79168a23
--- BugID: CAMEL-4467 Summary: LifecycleStrategy should be started/stopped when CamelContext is starting/stopping Description: The LifecycleStrategy strategies is not start/stopped if they are a Service, such as the DefaultManagementLifecycleStrategy diff --git a/camel-core/src/main/java/org/apache/camel/impl/DefaultCamelContext.java b/camel-core/src/main/java/org/apache/camel/impl/DefaultCamelContext.java index c5dbd5c..ee33f8e 100644 --- a/camel-core/src/main/java/org/apache/camel/impl/DefaultCamelContext.java +++ b/camel-core/src/main/java/org/apache/camel/impl/DefaultCamelContext.java @@ -1415,6 +1415,7 @@ public class DefaultCamelContext extends ServiceSupport implements ModelCamelCon getManagementStrategy().start(); // start lifecycle strategies + ServiceHelper.startServices(lifecycleStrategies); Iterator<LifecycleStrategy> it = lifecycleStrategies.iterator(); while (it.hasNext()) { LifecycleStrategy strategy = it.next(); @@ -1526,6 +1527,8 @@ public class DefaultCamelContext extends ServiceSupport implements ModelCamelCon // shutdown management as the last one shutdownServices(managementStrategy); + shutdownServices(lifecycleStrategies); + lifecycleStrategies.clear(); // stop the lazy created so they can be re-created on restart forceStopLazyInitialization();
bugs-dot-jar/camel_extracted_diff/developer-patch_bugs-dot-jar_CAMEL-4467_79168a23.diff
bugs-dot-jar_data_CAMEL-8954_7b1253db
--- BugID: CAMEL-8954 Summary: Lock information is not handovered together with Exchange on-completion synchronizations Description: | This applies to the file components when using common read-lock strategies: - *markerFile* - org.apache.camel.component.file.strategy.MarkerFileExclusiveReadLockStrategy - *fileLock* - org.apache.camel.component.file.strategy.FileLockExclusiveReadLockStrategy This strategies stores lock information in the Exchange properties: - *Exchange.FILE_LOCK_FILE_ACQUIRED* == "CamelFileLockFileAcquired" - *Exchange.FILE_LOCK_FILE_NAME* == "CamelFileLockFileName" - *Exchange.FILE_LOCK_EXCLUSIVE_LOCK* == "CamelFileLockExclusiveLock" - *Exchange.FILE_LOCK_RANDOM_ACCESS_FILE* == "CamelFileLockRandomAccessFile" Lock information is stored as scalar values and can hold information about _only one single lock_. When there are two Exchanges participates in the route, share UoW, and synchronizations are handovered from one Exchange to another, information about both locks can't be stored in the Exchange properties and lost. Consequently when on-completion synchronizations are performed, read-lock strategies can't access information about all the locks and they are not released. For example, after completing this route lock for file1.dat is not released: {code:java} from("file:data/input-a?fileName=file1.dat&readLock=markerFile") .pollEnrich("file:data/input-b?fileName=file2.dat&readLock=markerFile") .to("mock:result"); {code} diff --git a/camel-core/src/main/java/org/apache/camel/component/file/GenericFile.java b/camel-core/src/main/java/org/apache/camel/component/file/GenericFile.java index 343d836..907de21 100644 --- a/camel-core/src/main/java/org/apache/camel/component/file/GenericFile.java +++ b/camel-core/src/main/java/org/apache/camel/component/file/GenericFile.java @@ -35,6 +35,7 @@ import org.slf4j.LoggerFactory; public class GenericFile<T> implements WrappedFile<T> { private static final Logger LOG = LoggerFactory.getLogger(GenericFile.class); + private String copyFromAbsoluteFilePath; private String endpointPath; private String fileName; private String fileNameOnly; @@ -66,6 +67,7 @@ public class GenericFile<T> implements WrappedFile<T> { } catch (Exception e) { throw ObjectHelper.wrapRuntimeCamelException(e); } + result.setCopyFromAbsoluteFilePath(source.getAbsoluteFilePath()); result.setEndpointPath(source.getEndpointPath()); result.setAbsolute(source.isAbsolute()); result.setDirectory(source.isDirectory()); @@ -365,6 +367,14 @@ public class GenericFile<T> implements WrappedFile<T> { this.directory = directory; } + public String getCopyFromAbsoluteFilePath() { + return copyFromAbsoluteFilePath; + } + + public void setCopyFromAbsoluteFilePath(String copyFromAbsoluteFilePath) { + this.copyFromAbsoluteFilePath = copyFromAbsoluteFilePath; + } + /** * Fixes the path separator to be according to the protocol */ diff --git a/camel-core/src/main/java/org/apache/camel/component/file/strategy/FileLockExclusiveReadLockStrategy.java b/camel-core/src/main/java/org/apache/camel/component/file/strategy/FileLockExclusiveReadLockStrategy.java index 8fd94f5..de5101f 100644 --- a/camel-core/src/main/java/org/apache/camel/component/file/strategy/FileLockExclusiveReadLockStrategy.java +++ b/camel-core/src/main/java/org/apache/camel/component/file/strategy/FileLockExclusiveReadLockStrategy.java @@ -127,10 +127,11 @@ public class FileLockExclusiveReadLockStrategy extends MarkerFileExclusiveReadLo } } - // we grabbed the lock - exchange.setProperty(Exchange.FILE_LOCK_EXCLUSIVE_LOCK, lock); - exchange.setProperty(Exchange.FILE_LOCK_RANDOM_ACCESS_FILE, randomAccessFile); + // store read-lock state + exchange.setProperty(asReadLockKey(file, Exchange.FILE_LOCK_EXCLUSIVE_LOCK), lock); + exchange.setProperty(asReadLockKey(file, Exchange.FILE_LOCK_RANDOM_ACCESS_FILE), randomAccessFile); + // we grabbed the lock return true; } @@ -140,10 +141,10 @@ public class FileLockExclusiveReadLockStrategy extends MarkerFileExclusiveReadLo // must call super super.doReleaseExclusiveReadLock(operations, file, exchange); - String target = file.getFileName(); - FileLock lock = exchange.getProperty(Exchange.FILE_LOCK_EXCLUSIVE_LOCK, FileLock.class); - RandomAccessFile rac = exchange.getProperty(Exchange.FILE_LOCK_RANDOM_ACCESS_FILE, RandomAccessFile.class); + FileLock lock = exchange.getProperty(asReadLockKey(file, Exchange.FILE_LOCK_EXCLUSIVE_LOCK), FileLock.class); + RandomAccessFile rac = exchange.getProperty(asReadLockKey(file, Exchange.FILE_LOCK_EXCLUSIVE_LOCK), RandomAccessFile.class); + String target = file.getFileName(); if (lock != null) { Channel channel = lock.acquiredBy(); try { @@ -186,4 +187,12 @@ public class FileLockExclusiveReadLockStrategy extends MarkerFileExclusiveReadLo this.readLockLoggingLevel = readLockLoggingLevel; } + private static String asReadLockKey(GenericFile file, String key) { + // use the copy from absolute path as that was the original path of the file when the lock was acquired + // for example if the file consumer uses preMove then the file is moved and therefore has another name + // that would no longer match + String path = file.getCopyFromAbsoluteFilePath() != null ? file.getCopyFromAbsoluteFilePath() : file.getAbsoluteFilePath(); + return path + "-" + key; + } + } diff --git a/camel-core/src/main/java/org/apache/camel/component/file/strategy/MarkerFileExclusiveReadLockStrategy.java b/camel-core/src/main/java/org/apache/camel/component/file/strategy/MarkerFileExclusiveReadLockStrategy.java index ceabd01..1c92bbd 100644 --- a/camel-core/src/main/java/org/apache/camel/component/file/strategy/MarkerFileExclusiveReadLockStrategy.java +++ b/camel-core/src/main/java/org/apache/camel/component/file/strategy/MarkerFileExclusiveReadLockStrategy.java @@ -73,8 +73,10 @@ public class MarkerFileExclusiveReadLockStrategy implements GenericFileExclusive // create a plain file as marker filer for locking (do not use FileLock) boolean acquired = FileUtil.createNewFile(new File(lockFileName)); - exchange.setProperty(Exchange.FILE_LOCK_FILE_ACQUIRED, acquired); - exchange.setProperty(Exchange.FILE_LOCK_FILE_NAME, lockFileName); + + // store read-lock state + exchange.setProperty(asReadLockKey(file, Exchange.FILE_LOCK_FILE_ACQUIRED), acquired); + exchange.setProperty(asReadLockKey(file, Exchange.FILE_LOCK_FILE_NAME), lockFileName); return acquired; } @@ -101,9 +103,11 @@ public class MarkerFileExclusiveReadLockStrategy implements GenericFileExclusive return; } + boolean acquired = exchange.getProperty(asReadLockKey(file, Exchange.FILE_LOCK_FILE_ACQUIRED), false, Boolean.class); + // only release the file if camel get the lock before - if (exchange.getProperty(Exchange.FILE_LOCK_FILE_ACQUIRED, false, Boolean.class)) { - String lockFileName = exchange.getProperty(Exchange.FILE_LOCK_FILE_NAME, getLockFileName(file), String.class); + if (acquired) { + String lockFileName = exchange.getProperty(asReadLockKey(file, Exchange.FILE_LOCK_FILE_NAME), String.class); File lock = new File(lockFileName); if (lock.exists()) { @@ -162,4 +166,12 @@ public class MarkerFileExclusiveReadLockStrategy implements GenericFileExclusive return file.getAbsoluteFilePath() + FileComponent.DEFAULT_LOCK_FILE_POSTFIX; } + private static String asReadLockKey(GenericFile file, String key) { + // use the copy from absolute path as that was the original path of the file when the lock was acquired + // for example if the file consumer uses preMove then the file is moved and therefore has another name + // that would no longer match + String path = file.getCopyFromAbsoluteFilePath() != null ? file.getCopyFromAbsoluteFilePath() : file.getAbsoluteFilePath(); + return path + "-" + key; + } + }
bugs-dot-jar/camel_extracted_diff/developer-patch_bugs-dot-jar_CAMEL-8954_7b1253db.diff
bugs-dot-jar_data_CAMEL-7622_faa20255
--- BugID: CAMEL-7622 Summary: advice-with - No outputs found matching id when upgrading from 2.13 to 2.14 Description: "I have the following route defined with the Java DSL: \n\nfrom(\"direct:localMemberLookup\").routeId(\"localMemberLookup\") \n .process(new MemberLookupToSqlParametersProcessor()).id(\"sqlParams\") \n .recipientList(simple(\"sql:{{sql.memberLookup}}\")).delimiter(\"false\") \n .to(\"log:output\") \n .process(new MemberLookupProcessor()) \n \ // do more processing \n .to(\"log:output\"); \n\nI'm testing it with a test that looks as follows: \n\n@EndpointInject(uri = \"mock:lookupHeaders\") \nMockEndpoint lookupHeaders; \n\n@EndpointInject(uri = \"mock:searchResult\") \nMockEndpoint searchResult; \n\n@EndpointInject(uri = \"mock:lookupResult\") \nMockEndpoint lookupResult; \n\n@Autowired \nCamelContext camelContext; \n\n@Before \npublic void before() throws Exception { \n ModelCamelContext context = (ModelCamelContext) camelContext; \n context.setTracing(true); \n RouteDefinition searchRoute = context.getRouteDefinition(\"memberSearchRequest\"); \n searchRoute.to(searchResult); \n\n RouteDefinition lookupRoute = context.getRouteDefinition(\"localMemberLookup\"); \n lookupRoute.adviceWith(context, new AdviceWithRouteBuilder() { \n @Override \n public void configure() throws Exception { \n weaveById(\"sqlParams\").after().to(lookupHeaders); \n } \n }); \n lookupRoute.to(lookupResult); \n context.start(); \n} \n\nWith Camel 2.13.1, this works fine. However, with 2.14-SNAPSHOT, I get the following error: \n\njava.lang.IllegalArgumentException: There are no outputs which matches: sqlParams in the route \n\nMailing list thread: http://camel.465427.n5.nabble.com/weaveById-works-with-2-13-1-not-with-2-14-SNAPSHOT-td5753809.html" diff --git a/camel-core/src/main/java/org/apache/camel/builder/AdviceWithTasks.java b/camel-core/src/main/java/org/apache/camel/builder/AdviceWithTasks.java index 69f5a0a..694841c 100644 --- a/camel-core/src/main/java/org/apache/camel/builder/AdviceWithTasks.java +++ b/camel-core/src/main/java/org/apache/camel/builder/AdviceWithTasks.java @@ -312,7 +312,7 @@ public final class AdviceWithTasks { /** * Gets the outputs from the given parent. * <p/> - * This implementation deals with that outputs can be abstract and retrieves the correct non-nested output. + * This implementation deals with that outputs can be abstract and retrieves the <i>correct</i> parent output. * * @param parent the parent * @return <tt>null</tt> if no parent @@ -323,12 +323,9 @@ public final class AdviceWithTasks { return null; } List<ProcessorDefinition> outputs = parent.getOutputs(); - if (outputs.size() >= 1) { - // if the 1st output is abstract, then its onException,transacted,intercept etc so we should - // get the 'actual' outputs from that - if (outputs.get(0).isAbstract()) { - outputs = outputs.get(0).getOutputs(); - } + if (outputs.size() == 1 && outputs.get(0).isAbstract()) { + // if the output is abstract then get its output, as + outputs = outputs.get(0).getOutputs(); } return outputs; }
bugs-dot-jar/camel_extracted_diff/developer-patch_bugs-dot-jar_CAMEL-7622_faa20255.diff
bugs-dot-jar_data_CAMEL-9700_4d03e9de
--- BugID: CAMEL-9700 Summary: 'seda - discardIfNoConsumers=true do not call on completions ' Description: |- See SO http://stackoverflow.com/questions/35938139/how-to-release-file-lock-with-camel-when-not-consuming-from-seda-queue/35940850#35940850 diff --git a/camel-core/src/main/java/org/apache/camel/component/seda/SedaProducer.java b/camel-core/src/main/java/org/apache/camel/component/seda/SedaProducer.java index a87ddf3..1e28eaa 100644 --- a/camel-core/src/main/java/org/apache/camel/component/seda/SedaProducer.java +++ b/camel-core/src/main/java/org/apache/camel/component/seda/SedaProducer.java @@ -122,7 +122,8 @@ public class SedaProducer extends DefaultAsyncProducer { log.trace("Adding Exchange to queue: {}", copy); try { - addToQueue(copy); + // do not copy as we already did the copy + addToQueue(copy, false); } catch (SedaConsumerNotAvailableException e) { exchange.setException(e); callback.done(true); @@ -160,11 +161,8 @@ public class SedaProducer extends DefaultAsyncProducer { } } else { // no wait, eg its a InOnly then just add to queue and return - // handover the completion so its the copy which performs that, as we do not wait - Exchange copy = prepareCopy(exchange, true); - log.trace("Adding Exchange to queue: {}", copy); try { - addToQueue(copy); + addToQueue(exchange, true); } catch (SedaConsumerNotAvailableException e) { exchange.setException(e); callback.done(true); @@ -205,8 +203,9 @@ public class SedaProducer extends DefaultAsyncProducer { * simply add which will throw exception if the queue is full * * @param exchange the exchange to add to the queue + * @param copy whether to create a copy of the exchange to use for adding to the queue */ - protected void addToQueue(Exchange exchange) throws SedaConsumerNotAvailableException { + protected void addToQueue(Exchange exchange, boolean copy) throws SedaConsumerNotAvailableException { BlockingQueue<Exchange> queue = null; QueueReference queueReference = endpoint.getQueueReference(); if (queueReference != null) { @@ -226,15 +225,23 @@ public class SedaProducer extends DefaultAsyncProducer { } } + Exchange target = exchange; + + // handover the completion so its the copy which performs that, as we do not wait + if (copy) { + target = prepareCopy(exchange, true); + } + + log.trace("Adding Exchange to queue: {}", target); if (blockWhenFull) { try { - queue.put(exchange); + queue.put(target); } catch (InterruptedException e) { // ignore log.debug("Put interrupted, are we stopping? {}", isStopping() || isStopped()); } } else { - queue.add(exchange); + queue.add(target); } }
bugs-dot-jar/camel_extracted_diff/developer-patch_bugs-dot-jar_CAMEL-9700_4d03e9de.diff
bugs-dot-jar_data_CAMEL-7359_e6fbbf04
--- BugID: CAMEL-7359 Summary: Simple Language - Additional after text after inbuilt function call is ignored Description: |- The following Simple expression is valid and runs OK - however it may have been appropriate to report an error to the developer. {code:xml} <setBody> <simple>${bodyAs(java.lang.String) Additional text ignored...}</simple> </setBody> {code} The above seems a somewhat contrived example; However this is a more 'realistic' scenario in which the behaviour is not unexpected - {code:xml} <setBody> <simple>${bodyAs(java.lang.String).toUpperCase()}</simple> </setBody> {code} The above simple expression will simply set the body to be of type java.lang.String, however will not invoke the subsequent toUpperCase() call - likewise no error is reported to the developer. Camel has the same issue when using the function of headerAs and mandatoryBodyAs. diff --git a/camel-core/src/main/java/org/apache/camel/language/simple/ast/SimpleFunctionExpression.java b/camel-core/src/main/java/org/apache/camel/language/simple/ast/SimpleFunctionExpression.java index d02f050..32a22b2 100644 --- a/camel-core/src/main/java/org/apache/camel/language/simple/ast/SimpleFunctionExpression.java +++ b/camel-core/src/main/java/org/apache/camel/language/simple/ast/SimpleFunctionExpression.java @@ -195,9 +195,11 @@ public class SimpleFunctionExpression extends LiteralExpression { String remainder = ifStartsWithReturnRemainder("bodyAs", function); if (remainder != null) { String type = ObjectHelper.between(remainder, "(", ")"); - if (type == null) { + remainder = ObjectHelper.after(remainder, ")"); + if (type == null || ObjectHelper.isNotEmpty(remainder)) { throw new SimpleParserException("Valid syntax: ${bodyAs(type)} was: " + function, token.getIndex()); } + type = StringHelper.removeQuotes(type); return ExpressionBuilder.bodyExpression(type); } @@ -205,7 +207,8 @@ public class SimpleFunctionExpression extends LiteralExpression { remainder = ifStartsWithReturnRemainder("mandatoryBodyAs", function); if (remainder != null) { String type = ObjectHelper.between(remainder, "(", ")"); - if (type == null) { + remainder = ObjectHelper.after(remainder, ")"); + if (type == null || ObjectHelper.isNotEmpty(remainder)) { throw new SimpleParserException("Valid syntax: ${mandatoryBodyAs(type)} was: " + function, token.getIndex()); } type = StringHelper.removeQuotes(type);
bugs-dot-jar/camel_extracted_diff/developer-patch_bugs-dot-jar_CAMEL-7359_e6fbbf04.diff
bugs-dot-jar_data_CAMEL-7990_d581c4a4
--- BugID: CAMEL-7990 Summary: IdempotentConsumer - If no messageId should allow Camel error handler to react Description: |- See SO http://stackoverflow.com/questions/26453348/camel-onexception-doesnt-catch-nomessageidexception-of-idempotentconsumer The idempotent consumer should set the exchange on the exchange and invoke the callback, that is an internal routing engine bug in the implementation of that eip. diff --git a/camel-core/src/main/java/org/apache/camel/processor/idempotent/IdempotentConsumer.java b/camel-core/src/main/java/org/apache/camel/processor/idempotent/IdempotentConsumer.java index 100a660..d3afe7a 100644 --- a/camel-core/src/main/java/org/apache/camel/processor/idempotent/IdempotentConsumer.java +++ b/camel-core/src/main/java/org/apache/camel/processor/idempotent/IdempotentConsumer.java @@ -80,7 +80,9 @@ public class IdempotentConsumer extends ServiceSupport implements AsyncProcessor public boolean process(Exchange exchange, AsyncCallback callback) { final String messageId = messageIdExpression.evaluate(exchange, String.class); if (messageId == null) { - throw new NoMessageIdException(exchange, messageIdExpression); + exchange.setException(new NoMessageIdException(exchange, messageIdExpression)); + callback.done(true); + return true; } boolean newKey;
bugs-dot-jar/camel_extracted_diff/developer-patch_bugs-dot-jar_CAMEL-7990_d581c4a4.diff
bugs-dot-jar_data_CAMEL-5844_e775071b
--- BugID: CAMEL-5844 Summary: Camel Tracer not showing some EIP names Description: "In order to debug Camel routes, I have enabled the Tracer as follows: \ getContext().setTracing(true);\n\nHowever, I have observed that some EIP names and routes are not being printed on console, making it a bit confusing to follow. As far as I know, this happens with:\n* process(): the processor is not printed in the tracer; it's just empty (see below)\n* marshall(): the marshaller name is not printed in the tracer; it's just empty (see below)\n* setBody(): this step is also printed empty\n* from(\"activiti:...\"): this route step is not printed altogether\n\nFor simplicity, I only provide the examples for process() and marshall(), bit I can provide more information if needed.\n\n{panel:title=Route2 Config}\nfrom(\"vm:processIncomingOrders\")\n \ .process(new IncomingOrdersProcessor())\n .split(body())\t// iterate list of Orders\n .to(\"log:incomingOrder1?showExchangeId=true\")\n .process(new ActivitiStarterProcessor())\n \ .to(\"log:incomingOrder2?showExchangeId=true\")\t\t\t\n .to(\"activiti:activiti-camel-example\");\n{panel}\n\n{panel:title=Route2 Tracer}\nINFO 03-12 12:09:31,899 (MarkerIgnoringBase.java:info:96) -ID-ES-CNU2113RXH-51211-1354532898719-0-3 >>> (route2) from(vm://processIncomingOrders) --> <<< Pattern:InOnly, [...]\nINFO \ 03-12 12:09:34,899 (IncomingOrdersProcessor.java:process:39) -Processing incoming orders (from Web Services)\n[ORDER id:120 partName: wheel amount: 2 customerName: Honda Mechanics]\n[ORDER id:121 partName: engine amount: 4 customerName: Volvo]\n[ORDER id:122 partName: steering wheel amount: 3 customerName: Renault]\nINFO 03-12 12:09:34,900 (MarkerIgnoringBase.java:info:96) -ID-ES-CNU2113RXH-51211-1354532898719-0-3 >>> (route2) --> split[body] <<< Pattern:InOnly, [...]\n{panel}\n\n\n\n{panel:title=Route6 config}\nfrom(\"direct:ordercsv\")\n .marshal().bindy(BindyType.Csv, \"net.atos.camel.entities\")\n \ .to(\"file:d://cameldata/orders?fileName=orders-$\\{date:now:yyyyMMdd-hhmmss}.csv\");\n{panel}\n\n{panel:title=Route6 Tracer}\nINFO 03-12 12:09:37,313 (MarkerIgnoringBase.java:info:96) -ID-ES-CNU2113RXH-51211-1354532898719-0-8 >>> (route6) direct://ordercsv --> <<< Pattern:InOnly, [...]\nINFO 03-12 12:09:37,320 (MarkerIgnoringBase.java:info:96) -ID-ES-CNU2113RXH-51211-1354532898719-0-8 >>> (route6) --> file://d://cameldata/orders?fileName=orders-%24%7Bdate%3Anow%3AyyyyMMdd-hhmmss%7D.csv <<< Pattern:InOnly, [...]\n{panel}\n\n" diff --git a/camel-core/src/main/java/org/apache/camel/processor/WrapProcessor.java b/camel-core/src/main/java/org/apache/camel/processor/WrapProcessor.java index cb7eb9f..adb508a 100644 --- a/camel-core/src/main/java/org/apache/camel/processor/WrapProcessor.java +++ b/camel-core/src/main/java/org/apache/camel/processor/WrapProcessor.java @@ -19,14 +19,14 @@ package org.apache.camel.processor; import java.util.List; import org.apache.camel.Processor; -import org.apache.camel.Traceable; import org.apache.camel.util.ServiceHelper; /** * A processor which ensures wrapping processors is having lifecycle handled. + * + * @version */ -public class WrapProcessor extends DelegateAsyncProcessor implements Traceable { - +public class WrapProcessor extends DelegateAsyncProcessor { private final Processor wrapped; public WrapProcessor(Processor processor, Processor wrapped) { @@ -38,10 +38,6 @@ public class WrapProcessor extends DelegateAsyncProcessor implements Traceable { public String toString() { return "Wrap[" + wrapped + "] -> " + processor; } - - public String getTraceLabel() { - return "wrap[" + wrapped + "]"; - } @Override public List<Processor> next() {
bugs-dot-jar/camel_extracted_diff/developer-patch_bugs-dot-jar_CAMEL-5844_e775071b.diff
bugs-dot-jar_data_CAMEL-3448_b345dd82
--- BugID: CAMEL-3448 Summary: Route scoped onException may pick onException from another route if they are the same class type Description: | If you have a clash with route scoped onException and have the exact same class, then the key in the map isn't catering for this. And thus a 2nd route could override the 1st route onException definition. For example: from X route A onException IOException from Y route B onException IOException The map should contain 2 entries, but unfortunately it only contain 1. This only happens when its an exact type match. diff --git a/camel-core/src/main/java/org/apache/camel/processor/ErrorHandlerSupport.java b/camel-core/src/main/java/org/apache/camel/processor/ErrorHandlerSupport.java index aa00fbb..a7904e8 100644 --- a/camel-core/src/main/java/org/apache/camel/processor/ErrorHandlerSupport.java +++ b/camel-core/src/main/java/org/apache/camel/processor/ErrorHandlerSupport.java @@ -24,6 +24,8 @@ import org.apache.camel.Exchange; import org.apache.camel.Processor; import org.apache.camel.impl.ServiceSupport; import org.apache.camel.model.OnExceptionDefinition; +import org.apache.camel.model.ProcessorDefinitionHelper; +import org.apache.camel.model.RouteDefinition; import org.apache.camel.processor.exceptionpolicy.DefaultExceptionPolicyStrategy; import org.apache.camel.processor.exceptionpolicy.ExceptionPolicyKey; import org.apache.camel.processor.exceptionpolicy.ExceptionPolicyStrategy; @@ -49,7 +51,9 @@ public abstract class ErrorHandlerSupport extends ServiceSupport implements Erro List<Class> list = exceptionType.getExceptionClasses(); for (Class clazz : list) { - ExceptionPolicyKey key = new ExceptionPolicyKey(clazz, exceptionType.getOnWhen()); + RouteDefinition route = ProcessorDefinitionHelper.getRoute(exceptionType); + String routeId = route != null ? route.getId() : null; + ExceptionPolicyKey key = new ExceptionPolicyKey(routeId, clazz, exceptionType.getOnWhen()); exceptionPolicies.put(key, exceptionType); } } diff --git a/camel-core/src/main/java/org/apache/camel/processor/exceptionpolicy/DefaultExceptionPolicyStrategy.java b/camel-core/src/main/java/org/apache/camel/processor/exceptionpolicy/DefaultExceptionPolicyStrategy.java index 01d86e3..d727e17 100644 --- a/camel-core/src/main/java/org/apache/camel/processor/exceptionpolicy/DefaultExceptionPolicyStrategy.java +++ b/camel-core/src/main/java/org/apache/camel/processor/exceptionpolicy/DefaultExceptionPolicyStrategy.java @@ -17,6 +17,7 @@ package org.apache.camel.processor.exceptionpolicy; import java.util.Iterator; +import java.util.LinkedHashMap; import java.util.Map; import java.util.Set; import java.util.TreeMap; @@ -61,17 +62,29 @@ public class DefaultExceptionPolicyStrategy implements ExceptionPolicyStrategy { Exchange exchange, Throwable exception) { Map<Integer, OnExceptionDefinition> candidates = new TreeMap<Integer, OnExceptionDefinition>(); + Map<ExceptionPolicyKey, OnExceptionDefinition> routeScoped = new LinkedHashMap<ExceptionPolicyKey, OnExceptionDefinition>(); + Map<ExceptionPolicyKey, OnExceptionDefinition> contextScoped = new LinkedHashMap<ExceptionPolicyKey, OnExceptionDefinition>(); + // split policies into route and context scoped + initRouteAndContextScopedExceptionPolicies(exceptionPolicies, routeScoped, contextScoped); + + // at first check route scoped as we prefer them over context scoped // recursive up the tree using the iterator boolean exactMatch = false; Iterator<Throwable> it = createExceptionIterator(exception); while (!exactMatch && it.hasNext()) { // we should stop looking if we have found an exact match - exactMatch = findMatchedExceptionPolicy(exceptionPolicies, exchange, it.next(), candidates); + exactMatch = findMatchedExceptionPolicy(routeScoped, exchange, it.next(), candidates); } - // now go through the candidates and find the best + // fallback to check context scoped (only do this if there was no exact match) + it = createExceptionIterator(exception); + while (!exactMatch && it.hasNext()) { + // we should stop looking if we have found an exact match + exactMatch = findMatchedExceptionPolicy(contextScoped, exchange, it.next(), candidates); + } + // now go through the candidates and find the best if (LOG.isTraceEnabled()) { LOG.trace("Found " + candidates.size() + " candidates"); } @@ -80,11 +93,26 @@ public class DefaultExceptionPolicyStrategy implements ExceptionPolicyStrategy { // no type found return null; } else { - // return the first in the map as its sorted and + // return the first in the map as its sorted and we checked route scoped first, which we prefer return candidates.values().iterator().next(); } } + private void initRouteAndContextScopedExceptionPolicies(Map<ExceptionPolicyKey, OnExceptionDefinition> exceptionPolicies, + Map<ExceptionPolicyKey, OnExceptionDefinition> routeScoped, + Map<ExceptionPolicyKey, OnExceptionDefinition> contextScoped) { + + // loop through all the entries and split into route and context scoped + Set<Map.Entry<ExceptionPolicyKey, OnExceptionDefinition>> entries = exceptionPolicies.entrySet(); + for (Map.Entry<ExceptionPolicyKey, OnExceptionDefinition> entry : entries) { + if (entry.getKey().getRouteId() != null) { + routeScoped.put(entry.getKey(), entry.getValue()); + } else { + contextScoped.put(entry.getKey(), entry.getValue()); + } + } + } + private boolean findMatchedExceptionPolicy(Map<ExceptionPolicyKey, OnExceptionDefinition> exceptionPolicies, Exchange exchange, Throwable exception, diff --git a/camel-core/src/main/java/org/apache/camel/processor/exceptionpolicy/ExceptionPolicyKey.java b/camel-core/src/main/java/org/apache/camel/processor/exceptionpolicy/ExceptionPolicyKey.java index cbd1fa1..3c79baa 100644 --- a/camel-core/src/main/java/org/apache/camel/processor/exceptionpolicy/ExceptionPolicyKey.java +++ b/camel-core/src/main/java/org/apache/camel/processor/exceptionpolicy/ExceptionPolicyKey.java @@ -20,16 +20,30 @@ import org.apache.camel.model.WhenDefinition; /** * Exception policy key is a compound key for storing: - * <b>exception class</b> + <b>when</b> => <b>exception type</b>. + * <b>route id </b> + <b>exception class</b> + <b>when</b> => <b>exception type</b>. * <p/> * This is used by Camel to store the onException types configured that has or has not predicates attached (when). */ public final class ExceptionPolicyKey { + private final String routeId; private final Class exceptionClass; private final WhenDefinition when; + @Deprecated public ExceptionPolicyKey(Class exceptionClass, WhenDefinition when) { + this(null, exceptionClass, when); + } + + /** + * Key for exception clause + * + * @param routeId the route, or use <tt>null</tt> for a global scoped + * @param exceptionClass the exception class + * @param when optional predicate when the exception clause should trigger + */ + public ExceptionPolicyKey(String routeId, Class exceptionClass, WhenDefinition when) { + this.routeId = routeId; this.exceptionClass = exceptionClass; this.when = when; } @@ -42,10 +56,16 @@ public final class ExceptionPolicyKey { return when; } + public String getRouteId() { + return routeId; + } + + @Deprecated public static ExceptionPolicyKey newInstance(Class exceptionClass) { return new ExceptionPolicyKey(exceptionClass, null); } + @Deprecated public static ExceptionPolicyKey newInstance(Class exceptionClass, WhenDefinition when) { return new ExceptionPolicyKey(exceptionClass, when); } @@ -61,7 +81,10 @@ public final class ExceptionPolicyKey { ExceptionPolicyKey that = (ExceptionPolicyKey) o; - if (!exceptionClass.equals(that.exceptionClass)) { + if (exceptionClass != null ? !exceptionClass.equals(that.exceptionClass) : that.exceptionClass != null) { + return false; + } + if (routeId != null ? !routeId.equals(that.routeId) : that.routeId != null) { return false; } if (when != null ? !when.equals(that.when) : that.when != null) { @@ -73,13 +96,14 @@ public final class ExceptionPolicyKey { @Override public int hashCode() { - int result = exceptionClass.hashCode(); + int result = routeId != null ? routeId.hashCode() : 0; + result = 31 * result + (exceptionClass != null ? exceptionClass.hashCode() : 0); result = 31 * result + (when != null ? when.hashCode() : 0); return result; } @Override public String toString() { - return "ExceptionPolicyKey[" + exceptionClass + (when != null ? " " + when : "") + "]"; + return "ExceptionPolicyKey[route: " + (routeId != null ? routeId : "<global>") + ", " + exceptionClass + (when != null ? " " + when : "") + "]"; } }
bugs-dot-jar/camel_extracted_diff/developer-patch_bugs-dot-jar_CAMEL-3448_b345dd82.diff
bugs-dot-jar_data_CAMEL-4486_f98ac676
--- BugID: CAMEL-4486 Summary: Exceptions are not propagated to the parent route when endpoint cannot be resolved in the RoutingSlip EIP Description: |- Here is the unit test to reproduce the issue {code} package org.test; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.component.mock.MockEndpoint; import org.apache.camel.test.junit4.CamelTestSupport; import org.junit.Test; public class RecipientListTest extends CamelTestSupport { public static class Router { public String findEndpoint() { return "unresolved://endpoint"; } } @Test public void recipientList() throws Exception { MockEndpoint endpoint = getMockEndpoint("mock://error"); endpoint.expectedMessageCount(1); sendBody("direct://parent", "Hello World!"); assertMockEndpointsSatisfied(); } @Override protected RouteBuilder createRouteBuilder() throws Exception { return new RouteBuilder() { @Override public void configure() throws Exception { from("direct://parent") .onException(Throwable.class) .to("mock://error") .end() .to("direct://child"); from("direct://child") .errorHandler(noErrorHandler()) .routingSlip(bean(Router.class)); } }; } } {code} diff --git a/camel-core/src/main/java/org/apache/camel/processor/RoutingSlip.java b/camel-core/src/main/java/org/apache/camel/processor/RoutingSlip.java index 2c99425..24bcf36 100644 --- a/camel-core/src/main/java/org/apache/camel/processor/RoutingSlip.java +++ b/camel-core/src/main/java/org/apache/camel/processor/RoutingSlip.java @@ -170,7 +170,7 @@ public class RoutingSlip extends ServiceSupport implements AsyncProcessor, Trace }; } - private boolean doRoutingSlip(Exchange exchange, AsyncCallback callback) { + private boolean doRoutingSlip(final Exchange exchange, final AsyncCallback callback) { Exchange current = exchange; RoutingSlipIterator iter; try { @@ -196,8 +196,8 @@ public class RoutingSlip extends ServiceSupport implements AsyncProcessor, Trace } } catch (Exception e) { // error resolving endpoint so we should break out - exchange.setException(e); - return true; + current.setException(e); + break; } // prepare and process the routing slip
bugs-dot-jar/camel_extracted_diff/developer-patch_bugs-dot-jar_CAMEL-4486_f98ac676.diff
bugs-dot-jar_data_CAMEL-7344_91228815
--- BugID: CAMEL-7344 Summary: Some endpoints configured using beans may result in NPE under DEBUG mode Description: |- CAMEL-6130 seems to have introduced this issue or more precisely speaking, it has made this issue visible. DefaultEndpoint's toString() method seems to require its endpoint string value to be set. If it's not set, the toString method throws an exception. A fully built endpoint always has its endpoint string value set, thus there is no issue. However, an endpoint being manually set up may not have its endpoint string value set from the beginning (e.g., when its super class uses the DefaultEndpoint's default constructor to instantiate using a bean based instantiation). The debug log statement introduced in CAMEL-6130 invokes this toString method during the endpoint setup. That means, a spring based CXF endpoint may result in the following exception under the debug mode. SLF4J: Failed toString() invocation on an object of type [org.apache.camel.component.cxf.CxfSpringEndpoint] java.lang.IllegalArgumentException: endpointUri is not specified and org.apache.camel.component.cxf.CxfSpringEndpoint does not implement createEndpointUri() to create a default value at org.apache.camel.impl.DefaultEndpoint.getEndpointUri(DefaultEndpoint.java:154) at org.apache.camel.impl.DefaultEndpoint.toString(DefaultEndpoint.java:139) at org.slf4j.helpers.MessageFormatter.safeObjectAppend(MessageFormatter.java:304) at org.slf4j.helpers.MessageFormatter.deeplyAppendParameter(MessageFormatter.java:276) at org.slf4j.helpers.MessageFormatter.arrayFormat(MessageFormatter.java:230) at org.slf4j.impl.Log4jLoggerAdapter.debug(Log4jLoggerAdapter.java:271) at org.apache.camel.util.IntrospectionSupport.setProperty(IntrospectionSupport.java:528) at org.apache.camel.util.IntrospectionSupport.setProperty(IntrospectionSupport.java:570) at org.apache.camel.util.IntrospectionSupport.setProperties(IntrospectionSupport.java:454) at org.apache.camel.util.EndpointHelper.setProperties(EndpointHelper.java:249) at org.apache.camel.component.cxf.CxfEndpoint.setCamelContext(CxfEndpoint.java:840) I wonder whether we really need DefaultEndpoint's getEndpointUri() to throw an exception when it's endpoint string value is not set. But if we keep this rule, we must catch the exception in its toString() method so that we won't throw the above exception when the toString() method is called during the endpoint setup I would propose to add the exception catching in the toString method. If we decide to change the getEndpointUri() method to not throw the exception (that change will likely require the NPE check at the users of this method), we can make that change and remove the exception catch from the toString method This issue affects camel 2.11.0 and later versions. diff --git a/camel-core/src/main/java/org/apache/camel/impl/DefaultEndpoint.java b/camel-core/src/main/java/org/apache/camel/impl/DefaultEndpoint.java index 3dae289..badd48e 100644 --- a/camel-core/src/main/java/org/apache/camel/impl/DefaultEndpoint.java +++ b/camel-core/src/main/java/org/apache/camel/impl/DefaultEndpoint.java @@ -136,7 +136,13 @@ public abstract class DefaultEndpoint extends ServiceSupport implements Endpoint @Override public String toString() { - return String.format("Endpoint[%s]", URISupport.sanitizeUri(getEndpointUri())); + String value = null; + try { + value = getEndpointUri(); + } catch (RuntimeException e) { + // ignore any exception and use null for building the string value + } + return String.format("Endpoint[%s]", URISupport.sanitizeUri(value)); } /**
bugs-dot-jar/camel_extracted_diff/developer-patch_bugs-dot-jar_CAMEL-7344_91228815.diff
bugs-dot-jar_data_CAMEL-5224_2db5570f
--- BugID: CAMEL-5224 Summary: The done file got deleted, when using the file component even if noop property set to true Description: | We are consuming a feed from a mounted windows network drive, where we have rw access. During the download we shouldn't touch anything so other users see the directory intact. However even if we turn noop=true the done file got deleted after successfull conumptions diff --git a/camel-core/src/main/java/org/apache/camel/component/file/GenericFileOnCompletion.java b/camel-core/src/main/java/org/apache/camel/component/file/GenericFileOnCompletion.java index 58c825f..726df83 100644 --- a/camel-core/src/main/java/org/apache/camel/component/file/GenericFileOnCompletion.java +++ b/camel-core/src/main/java/org/apache/camel/component/file/GenericFileOnCompletion.java @@ -109,8 +109,8 @@ public class GenericFileOnCompletion<T> implements Synchronization { endpoint.getIdempotentRepository().add(absoluteFileName); } - // delete done file if used - if (endpoint.getDoneFileName() != null) { + // delete done file if used (and not noop=true) + if (endpoint.getDoneFileName() != null && !endpoint.isNoop()) { // done file must be in same path as the original input file String doneFileName = endpoint.createDoneFileName(absoluteFileName); ObjectHelper.notEmpty(doneFileName, "doneFileName", endpoint); @@ -133,7 +133,6 @@ public class GenericFileOnCompletion<T> implements Synchronization { } catch (Exception e) { handleException(e); } - } /**
bugs-dot-jar/camel_extracted_diff/developer-patch_bugs-dot-jar_CAMEL-5224_2db5570f.diff
bugs-dot-jar_data_CAMEL-9480_0ead2cac
--- BugID: CAMEL-9480 Summary: IdempotentConsumer - If exception from repo it should be able to handle by onException Description: |- See nabble http://camel.465427.n5.nabble.com/Exception-from-idempotentConsumer-not-propagating-to-onException-tp5775779.html diff --git a/camel-core/src/main/java/org/apache/camel/processor/idempotent/IdempotentConsumer.java b/camel-core/src/main/java/org/apache/camel/processor/idempotent/IdempotentConsumer.java index e28a214..7b64546 100644 --- a/camel-core/src/main/java/org/apache/camel/processor/idempotent/IdempotentConsumer.java +++ b/camel-core/src/main/java/org/apache/camel/processor/idempotent/IdempotentConsumer.java @@ -91,51 +91,65 @@ public class IdempotentConsumer extends ServiceSupport implements AsyncProcessor } public boolean process(final Exchange exchange, final AsyncCallback callback) { - final String messageId = messageIdExpression.evaluate(exchange, String.class); - if (messageId == null) { - exchange.setException(new NoMessageIdException(exchange, messageIdExpression)); + final AsyncCallback target; + + final String messageId; + try { + messageId = messageIdExpression.evaluate(exchange, String.class); + if (messageId == null) { + exchange.setException(new NoMessageIdException(exchange, messageIdExpression)); + callback.done(true); + return true; + } + } catch (Exception e) { + exchange.setException(e); callback.done(true); return true; } - boolean newKey; - if (eager) { - // add the key to the repository - if (idempotentRepository instanceof ExchangeIdempotentRepository) { - newKey = ((ExchangeIdempotentRepository<String>) idempotentRepository).add(exchange, messageId); - } else { - newKey = idempotentRepository.add(messageId); - } - } else { - // check if we already have the key - if (idempotentRepository instanceof ExchangeIdempotentRepository) { - newKey = ((ExchangeIdempotentRepository<String>) idempotentRepository).contains(exchange, messageId); + try { + boolean newKey; + if (eager) { + // add the key to the repository + if (idempotentRepository instanceof ExchangeIdempotentRepository) { + newKey = ((ExchangeIdempotentRepository<String>) idempotentRepository).add(exchange, messageId); + } else { + newKey = idempotentRepository.add(messageId); + } } else { - newKey = !idempotentRepository.contains(messageId); + // check if we already have the key + if (idempotentRepository instanceof ExchangeIdempotentRepository) { + newKey = ((ExchangeIdempotentRepository<String>) idempotentRepository).contains(exchange, messageId); + } else { + newKey = !idempotentRepository.contains(messageId); + } } - } + if (!newKey) { + // mark the exchange as duplicate + exchange.setProperty(Exchange.DUPLICATE_MESSAGE, Boolean.TRUE); - if (!newKey) { - // mark the exchange as duplicate - exchange.setProperty(Exchange.DUPLICATE_MESSAGE, Boolean.TRUE); + // we already have this key so its a duplicate message + onDuplicate(exchange, messageId); - // we already have this key so its a duplicate message - onDuplicate(exchange, messageId); - - if (skipDuplicate) { - // if we should skip duplicate then we are done - LOG.debug("Ignoring duplicate message with id: {} for exchange: {}", messageId, exchange); - callback.done(true); - return true; + if (skipDuplicate) { + // if we should skip duplicate then we are done + LOG.debug("Ignoring duplicate message with id: {} for exchange: {}", messageId, exchange); + callback.done(true); + return true; + } } - } - final Synchronization onCompletion = new IdempotentOnCompletion(idempotentRepository, messageId, eager, removeOnFailure); - final AsyncCallback target = new IdempotentConsumerCallback(exchange, onCompletion, callback, completionEager); - if (!completionEager) { - // the scope is to do the idempotent completion work as an unit of work on the exchange when its done being routed - exchange.addOnCompletion(onCompletion); + final Synchronization onCompletion = new IdempotentOnCompletion(idempotentRepository, messageId, eager, removeOnFailure); + target = new IdempotentConsumerCallback(exchange, onCompletion, callback, completionEager); + if (!completionEager) { + // the scope is to do the idempotent completion work as an unit of work on the exchange when its done being routed + exchange.addOnCompletion(onCompletion); + } + } catch (Exception e) { + exchange.setException(e); + callback.done(true); + return true; } // process the exchange
bugs-dot-jar/camel_extracted_diff/developer-patch_bugs-dot-jar_CAMEL-9480_0ead2cac.diff
bugs-dot-jar_data_CAMEL-9641_9a6e6d8a
--- BugID: CAMEL-9641 Summary: Simple backwards parser bug if using file Description: |- See nabble http://camel.465427.n5.nabble.com/Unknown-File-Language-Syntax-tp5778208.html diff --git a/camel-core/src/main/java/org/apache/camel/language/simple/ast/SimpleFunctionExpression.java b/camel-core/src/main/java/org/apache/camel/language/simple/ast/SimpleFunctionExpression.java index be5e4ac..5110ae9 100644 --- a/camel-core/src/main/java/org/apache/camel/language/simple/ast/SimpleFunctionExpression.java +++ b/camel-core/src/main/java/org/apache/camel/language/simple/ast/SimpleFunctionExpression.java @@ -141,8 +141,8 @@ public class SimpleFunctionExpression extends LiteralExpression { // file: prefix remainder = ifStartsWithReturnRemainder("file:", function); if (remainder != null) { - Expression fileExpression = createSimpleFileExpression(remainder); - if (function != null) { + Expression fileExpression = createSimpleFileExpression(remainder, strict); + if (fileExpression != null) { return fileExpression; } } @@ -388,7 +388,7 @@ public class SimpleFunctionExpression extends LiteralExpression { return null; } - private Expression createSimpleFileExpression(String remainder) { + private Expression createSimpleFileExpression(String remainder, boolean strict) { if (ObjectHelper.equal(remainder, "name")) { return ExpressionBuilder.fileNameExpression(); } else if (ObjectHelper.equal(remainder, "name.noext")) { @@ -418,7 +418,10 @@ public class SimpleFunctionExpression extends LiteralExpression { } else if (ObjectHelper.equal(remainder, "modified")) { return ExpressionBuilder.fileLastModifiedExpression(); } - throw new SimpleParserException("Unknown file language syntax: " + remainder, token.getIndex()); + if (strict) { + throw new SimpleParserException("Unknown file language syntax: " + remainder, token.getIndex()); + } + return null; } private String ifStartsWithReturnRemainder(String prefix, String text) {
bugs-dot-jar/camel_extracted_diff/developer-patch_bugs-dot-jar_CAMEL-9641_9a6e6d8a.diff
bugs-dot-jar_data_CAMEL-4388_f39bc60d
--- BugID: CAMEL-4388 Summary: Exeptions cannot be propagated to the parent route when using LogEIP Description: |- Here is unit test that demonstrates the problem. For the unit test pass successfully it's necessary to delete LogEIP from the route. {code} package org.apache.camel.impl; import org.apache.camel.Exchange; import org.apache.camel.Processor; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.test.junit4.CamelTestSupport; import org.junit.Test; public class PropagateExceptionTest extends CamelTestSupport { @Test public void failure() throws Exception { getMockEndpoint("mock:handleFailure").whenAnyExchangeReceived(new Processor() { @Override public void process(Exchange exchange) throws Exception { throw new RuntimeException("TEST EXCEPTION"); } }); getMockEndpoint("mock:exceptionFailure").expectedMessageCount(1); sendBody("direct:startFailure", "Hello World"); assertMockEndpointsSatisfied(); } @Test public void success() throws Exception { getMockEndpoint("mock:handleSuccess").whenAnyExchangeReceived(new Processor() { @Override public void process(Exchange exchange) throws Exception { throw new RuntimeException("TEST EXCEPTION"); } }); getMockEndpoint("mock:exceptionSuccess").expectedMessageCount(1); sendBody("direct:startSuccess", "Hello World"); assertMockEndpointsSatisfied(); } @Override protected RouteBuilder[] createRouteBuilders() throws Exception { return new RouteBuilder[] { new RouteBuilder() { public void configure() throws Exception { from("direct:startFailure") .onException(Throwable.class) .to("mock:exceptionFailure") .end() .to("direct:handleFailure") .to("mock:resultFailure"); from("direct:handleFailure") .errorHandler(noErrorHandler()) .log("FAULTY LOG") .to("mock:handleFailure"); } }, new RouteBuilder() { public void configure() throws Exception { from("direct:startSuccess") .onException(Throwable.class) .to("mock:exceptionSuccess") .end() .to("direct:handleSuccess") .to("mock:resultSuccess"); from("direct:handleSuccess") .errorHandler(noErrorHandler()) .to("mock:handleSuccess"); } } }; } } {code} diff --git a/camel-core/src/main/java/org/apache/camel/processor/LogProcessor.java b/camel-core/src/main/java/org/apache/camel/processor/LogProcessor.java index 94a4246..ced8977 100644 --- a/camel-core/src/main/java/org/apache/camel/processor/LogProcessor.java +++ b/camel-core/src/main/java/org/apache/camel/processor/LogProcessor.java @@ -43,8 +43,15 @@ public class LogProcessor implements AsyncProcessor, Traceable { @Override public boolean process(Exchange exchange, AsyncCallback callback) { - String msg = expression.evaluate(exchange, String.class); - logger.log(msg); + try { + String msg = expression.evaluate(exchange, String.class); + logger.log(msg); + } catch (Exception e) { + exchange.setException(e); + } finally { + // callback must be invoked + callback.done(true); + } return true; }
bugs-dot-jar/camel_extracted_diff/developer-patch_bugs-dot-jar_CAMEL-4388_f39bc60d.diff
bugs-dot-jar_data_CAMEL-5357_4cf7e80e
--- BugID: CAMEL-5357 Summary: URI normalization - Should detect already percent encoded values Description: |- If an uri has a percent encoded value, eg using %20, %25 etc, then the normalization logic in Camel should detect this and keep the value as is. Currently it would end up double encoding %25, that becomes %2525, and so forth. Its the code in UnsafeUriCharactersEncoder that has the bug diff --git a/camel-core/src/main/java/org/apache/camel/util/UnsafeUriCharactersEncoder.java b/camel-core/src/main/java/org/apache/camel/util/UnsafeUriCharactersEncoder.java index 39659e4..4bc707f 100644 --- a/camel-core/src/main/java/org/apache/camel/util/UnsafeUriCharactersEncoder.java +++ b/camel-core/src/main/java/org/apache/camel/util/UnsafeUriCharactersEncoder.java @@ -20,6 +20,8 @@ import java.util.BitSet; /** * Encoder for unsafe URI characters. + * <p/> + * A good source for details is <a href="http://en.wikipedia.org/wiki/Url_encode">wikipedia url encode</a> article. */ public final class UnsafeUriCharactersEncoder { private static BitSet unsafeCharacters; @@ -33,7 +35,7 @@ public final class UnsafeUriCharactersEncoder { unsafeCharacters.set('<'); unsafeCharacters.set('>'); unsafeCharacters.set('#'); - // unsafeCharacters.set('%'); + unsafeCharacters.set('%'); unsafeCharacters.set('{'); unsafeCharacters.set('}'); unsafeCharacters.set('|'); @@ -70,16 +72,32 @@ public final class UnsafeUriCharactersEncoder { } // okay there are some unsafe characters so we do need to encode + // see details at: http://en.wikipedia.org/wiki/Url_encode StringBuilder sb = new StringBuilder(); - for (char ch : chars) { + for (int i = 0; i < chars.length; i++) { + char ch = chars[i]; if (ch > 0 && ch < 128 && unsafeCharacters.get(ch)) { - appendEscape(sb, (byte)ch); + // special for % sign as it may be a decimal encoded value + if (ch == '%') { + char next = i + 1 < chars.length ? chars[i + 1] : ' '; + char next2 = i + 2 < chars.length ? chars[i + 2] : ' '; + + if (isHexDigit(next) && isHexDigit(next2)) { + // its already encoded (decimal encoded) so just append as is + sb.append(ch); + } else { + // must escape then, as its an unsafe character + appendEscape(sb, (byte)ch); + } + } else { + // must escape then, as its an unsafe character + appendEscape(sb, (byte)ch); + } } else { sb.append(ch); } } return sb.toString(); - } private static void appendEscape(StringBuilder sb, byte b) { @@ -88,4 +106,13 @@ public final class UnsafeUriCharactersEncoder { sb.append(HEX_DIGITS[(b >> 0) & 0x0f]); } + private static boolean isHexDigit(char ch) { + for (char hex : HEX_DIGITS) { + if (hex == ch) { + return true; + } + } + return false; + } + }
bugs-dot-jar/camel_extracted_diff/developer-patch_bugs-dot-jar_CAMEL-5357_4cf7e80e.diff
bugs-dot-jar_data_CAMEL-4542_c408c3ed
--- BugID: CAMEL-4542 Summary: Can't find splitter bean in registry using multiple camel contexts with "vm" endpoint Description: "The splitter component can use a bean with a \"split method\". It seems that this \"split bean\" is handled as expression and resolved lately using Camel Context from current exchange.\n\nIf I send an exchange using a separate CamelContext (\"client\")\n\n<camelContext id=\"client\" xmlns=\"http://camel.apache.org/schema/spring\">\n</camelContext>\n\nto a route defined in another CamelContext (\"server\") using in-memory transport like \"direct\" or \"vm\"\n\n<camelContext id=\"server\" xmlns=\"http://camel.apache.org/schema/spring\">\n\n \ <route id=\"route02\" trace=\"false\" streamCache=\"false\">\n <from uri=\"vm:route02\"/>\n \ <split>\n <method bean =\"stringLineSplitter\" method=\"split\"/>\n \ <log message=\"before sending: ${body}\"/>\n <inOut uri =\"vm:route04\"/>\n \ <log message=\"after sending\"/>\n </split>\n <to uri=\"mock:route02\"/>\n \ </route>\n\n</camelContext>\n\nthe test fails with \n\n\"Cannot find class: stringLineSplitter\" (Camel 2.8.0). \n\"org.apache.camel.NoSuchBeanException - No bean could be found in the registry for: stringLineSplitter\" (Camel 2.9-SNAPSHOT)\n\nIf I understood Camel right it fails\nbecause it tries to resolve this bean based on client Camel Context\nwhich is still set at the current exchange send from \"client\" to \"server\" but it\ndoesn't contain the bean.\n\nIf I send an exchange using same \"client\" CamelContext to another route in\n\"server\" CamelContext involving \"external\" components like \"jms\" (ActiveMQ)\n\n<camelContext id=\"server\" xmlns=\"http://camel.apache.org/schema/spring\">\n\n \ <route id=\"route03\" trace=\"false\" streamCache=\"false\">\n <from uri=\"jms:queue:route03\"/>\n \ <split>\n <method bean =\"stringLineSplitter\" method=\"split\"/>\n \ <log message=\"before sending: ${body}\"/>\n <inOut uri =\"vm:route04\"/>\n \ <log message=\"after sending\"/>\n </split>\n <to uri=\"mock:route03\"/>\n \ </route>\n\n</camelContext>\n\nthe test passed successfully. It seems that \"jms\" component creates a\nnew exchange using \"server\" CamelContext.\n" diff --git a/camel-core/src/main/java/org/apache/camel/model/language/MethodCallExpression.java b/camel-core/src/main/java/org/apache/camel/model/language/MethodCallExpression.java index 796cbdd..2ac12c3 100644 --- a/camel-core/src/main/java/org/apache/camel/model/language/MethodCallExpression.java +++ b/camel-core/src/main/java/org/apache/camel/model/language/MethodCallExpression.java @@ -170,7 +170,7 @@ public class MethodCallExpression extends ExpressionDefinition { BeanHolder holder = new RegistryBean(camelContext, ref); // get the bean which will check that it exists instance = holder.getBean(); - answer = new BeanExpression(ref, getMethod()); + answer = new BeanExpression(instance, getMethod()); } validateHasMethod(camelContext, instance, beanType, getMethod());
bugs-dot-jar/camel_extracted_diff/developer-patch_bugs-dot-jar_CAMEL-4542_c408c3ed.diff
bugs-dot-jar_data_CAMEL-7459_57ba1bde
--- BugID: CAMEL-7459 Summary: parseQuery Drops Char When Last Parameter is RAW with value ending in ')' Description: "org.apache.camel.util.URISupport\n\nWhen processing RAW parameters as part of parseQuery a look ahead to the next char is needed in order to determine the end of the RAW value. The logic to prevent a _StringIndexOutOfBoundsException_ drops the last char when evaluating for _next_ char when the current char (_i_) is the second to last char of the string.\n\nThis becomes an issue when the RAW value ends in ')' \n\nConsider:\nuri = \"foo=RAW(ba(r))\"\nuri.length() = 14\ni = 12\nuri.charAt(12) = ')'\nuri.charAt(13) = ')'\n\n(i < uri.legnth() - 2) = 12 < (14 - 2) = 12 < 12 = false\nthus next = \"\\u0000\"\n\nThe RAW value now ends satisfying the requirements and the char at index 13 is never read. The resulting parameter is \"foo=RAW(ba(r)\".\n\nThe logic to prevent the index exception should be \"(i <*=* uri.legnth() -2)\" or \"(i < uri.legnth() - *1*)\"" diff --git a/camel-core/src/main/java/org/apache/camel/util/URISupport.java b/camel-core/src/main/java/org/apache/camel/util/URISupport.java index 4b06a13..0f37a2c 100644 --- a/camel-core/src/main/java/org/apache/camel/util/URISupport.java +++ b/camel-core/src/main/java/org/apache/camel/util/URISupport.java @@ -155,7 +155,7 @@ public final class URISupport { char ch = uri.charAt(i); // look ahead of the next char char next; - if (i < uri.length() - 2) { + if (i <= uri.length() - 2) { next = uri.charAt(i + 1); } else { next = '\u0000';
bugs-dot-jar/camel_extracted_diff/developer-patch_bugs-dot-jar_CAMEL-7459_57ba1bde.diff
bugs-dot-jar_data_CAMEL-3727_ff2713d1
--- BugID: CAMEL-3727 Summary: Recipient list with parallel processing doesn't reuse aggregation threads Description: | When I'm using recipient list in parallel mode {{aggregateExecutorService}} in {{MulticastProcessor}} doesn't reuse threads and is creating one new thread per each request. To reproduce this bug simply add a loop to {{RecipientListParallelTest.testRecipientListParallel()}} test: {code:title=RecipientListParallelTest.java|borderStyle=solid} public void testRecipientListParallel() throws Exception { for (int i = 0; i < 10000; i++) { MockEndpoint mock = getMockEndpoint("mock:result"); mock.reset(); mock.expectedBodiesReceivedInAnyOrder("c", "b", "a"); template.sendBodyAndHeader("direct:start", "Hello World", "foo", "direct:a,direct:b,direct:c"); assertMockEndpointsSatisfied(); } } {code} In the logs you can find: {code} 2011-02-28 13:22:30,984 [) thread #0 - RecipientListProcessor-AggregateTask] DEBUG MulticastProcessor - Done aggregating 3 exchanges on the fly. 2011-02-28 13:22:31,984 [) thread #4 - RecipientListProcessor-AggregateTask] DEBUG MulticastProcessor - Done aggregating 3 exchanges on the fly. 2011-02-28 13:22:32,984 [) thread #8 - RecipientListProcessor-AggregateTask] DEBUG MulticastProcessor - Done aggregating 3 exchanges on the fly. 2011-02-28 13:22:34,000 [ thread #12 - RecipientListProcessor-AggregateTask] DEBUG MulticastProcessor - Done aggregating 3 exchanges on the fly. 2011-02-28 13:22:35,000 [ thread #14 - RecipientListProcessor-AggregateTask] DEBUG MulticastProcessor - Done aggregating 3 exchanges on the fly. 2011-02-28 13:22:36,000 [ thread #15 - RecipientListProcessor-AggregateTask] DEBUG MulticastProcessor - Done aggregating 3 exchanges on the fly. 2011-02-28 13:22:37,015 [ thread #16 - RecipientListProcessor-AggregateTask] DEBUG MulticastProcessor - Done aggregating 3 exchanges on the fly. 2011-02-28 13:22:38,015 [ thread #17 - RecipientListProcessor-AggregateTask] DEBUG MulticastProcessor - Done aggregating 3 exchanges on the fly. {code} diff --git a/camel-core/src/main/java/org/apache/camel/processor/MulticastProcessor.java b/camel-core/src/main/java/org/apache/camel/processor/MulticastProcessor.java index a427b25..3d4fec2 100644 --- a/camel-core/src/main/java/org/apache/camel/processor/MulticastProcessor.java +++ b/camel-core/src/main/java/org/apache/camel/processor/MulticastProcessor.java @@ -888,11 +888,22 @@ public class MulticastProcessor extends ServiceSupport implements AsyncProcessor // keep at least one thread in the pool so we re-use the thread avoiding to create new threads because // the pool shrank to zero. String name = getClass().getSimpleName() + "-AggregateTask"; - aggregateExecutorService = camelContext.getExecutorServiceStrategy().newThreadPool(this, name, 1, Integer.MAX_VALUE); + aggregateExecutorService = createAggregateExecutorService(name); } ServiceHelper.startServices(processors); } + /** + * Strategy to create the thread pool for the aggregator background task which waits for and aggregates + * completed tasks when running in parallel mode. + * + * @param name the suggested name for the background thread + * @return the thread pool + */ + protected ExecutorService createAggregateExecutorService(String name) { + return camelContext.getExecutorServiceStrategy().newThreadPool(this, name, 1, Integer.MAX_VALUE); + } + protected void doStop() throws Exception { ServiceHelper.stopServices(processors); errorHandlers.clear(); diff --git a/camel-core/src/main/java/org/apache/camel/processor/RecipientList.java b/camel-core/src/main/java/org/apache/camel/processor/RecipientList.java index 8260c93..f2a163f 100644 --- a/camel-core/src/main/java/org/apache/camel/processor/RecipientList.java +++ b/camel-core/src/main/java/org/apache/camel/processor/RecipientList.java @@ -55,6 +55,7 @@ public class RecipientList extends ServiceSupport implements AsyncProcessor { private boolean streaming; private long timeout; private ExecutorService executorService; + private ExecutorService aggregateExecutorService; private AggregationStrategy aggregationStrategy = new UseLatestAggregationStrategy(); public RecipientList(CamelContext camelContext) { @@ -108,7 +109,16 @@ public class RecipientList extends ServiceSupport implements AsyncProcessor { Iterator<Object> iter = ObjectHelper.createIterator(recipientList, delimiter); RecipientListProcessor rlp = new RecipientListProcessor(exchange.getContext(), producerCache, iter, getAggregationStrategy(), - isParallelProcessing(), getExecutorService(), isStreaming(), isStopOnException(), getTimeout()); + isParallelProcessing(), getExecutorService(), isStreaming(), isStopOnException(), getTimeout()) { + @Override + protected ExecutorService createAggregateExecutorService(String name) { + // use a shared executor service to avoid creating new thread pools + if (aggregateExecutorService == null) { + aggregateExecutorService = super.createAggregateExecutorService("RecipientList-AggregateTask"); + } + return aggregateExecutorService; + } + }; rlp.setIgnoreInvalidEndpoints(isIgnoreInvalidEndpoints()); // start the service @@ -144,7 +154,7 @@ public class RecipientList extends ServiceSupport implements AsyncProcessor { protected void doStop() throws Exception { ServiceHelper.stopService(producerCache); } - + public boolean isStreaming() { return streaming; } @@ -200,4 +210,5 @@ public class RecipientList extends ServiceSupport implements AsyncProcessor { public void setTimeout(long timeout) { this.timeout = timeout; } + }
bugs-dot-jar/camel_extracted_diff/developer-patch_bugs-dot-jar_CAMEL-3727_ff2713d1.diff
bugs-dot-jar_data_CAMEL-8081_2e985f9b
--- BugID: CAMEL-8081 Summary: Multicast Aggregator should keep processing other exchange which is not timeout Description: "It makes sense the multicast aggregator keep processing the exchange even some exchange are timeout. \nHere is [a thread|http://camel.465427.n5.nabble.com/Multicast-with-multiple-timeouts-tp5759576p5759646.html] in the camel user mailing list talks about it." diff --git a/camel-core/src/main/java/org/apache/camel/processor/MulticastProcessor.java b/camel-core/src/main/java/org/apache/camel/processor/MulticastProcessor.java index 1d579cd..38e70bb 100644 --- a/camel-core/src/main/java/org/apache/camel/processor/MulticastProcessor.java +++ b/camel-core/src/main/java/org/apache/camel/processor/MulticastProcessor.java @@ -442,10 +442,7 @@ public class MulticastProcessor extends ServiceSupport implements AsyncProcessor } } - if (future == null && timedOut) { - // we are timed out and no more tasks complete so break out - break; - } else if (future == null) { + if (future == null) { // timeout occurred AggregationStrategy strategy = getAggregationStrategy(null); if (strategy instanceof TimeoutAwareAggregationStrategy) {
bugs-dot-jar/camel_extracted_diff/developer-patch_bugs-dot-jar_CAMEL-8081_2e985f9b.diff
bugs-dot-jar_data_CAMEL-7562_689147e9
--- BugID: CAMEL-7562 Summary: camel-test - AdviceWith in CBR may add twice Description: |- See nabble http://camel.465427.n5.nabble.com/Camel-AdviceWith-issues-tp5752786.html When using advice-with for a CBR it may add to the when clauses 2 times. diff --git a/camel-core/src/main/java/org/apache/camel/model/ProcessorDefinitionHelper.java b/camel-core/src/main/java/org/apache/camel/model/ProcessorDefinitionHelper.java index 5575d36..2ae283b 100644 --- a/camel-core/src/main/java/org/apache/camel/model/ProcessorDefinitionHelper.java +++ b/camel-core/src/main/java/org/apache/camel/model/ProcessorDefinitionHelper.java @@ -198,9 +198,6 @@ public final class ProcessorDefinitionHelper { } for (ProcessorDefinition out : outputs) { - if (type.isInstance(out)) { - found.add((T)out); - } // send is much common if (out instanceof SendDefinition) { @@ -222,6 +219,9 @@ public final class ProcessorDefinitionHelper { List<ProcessorDefinition<?>> children = choice.getOtherwise().getOutputs(); doFindType(children, type, found); } + + // do not check children as we already did that + continue; } // special for try ... catch ... finally @@ -253,6 +253,10 @@ public final class ProcessorDefinitionHelper { continue; } + if (type.isInstance(out)) { + found.add((T)out); + } + // try children as well List<ProcessorDefinition<?>> children = out.getOutputs(); doFindType(children, type, found);
bugs-dot-jar/camel_extracted_diff/developer-patch_bugs-dot-jar_CAMEL-7562_689147e9.diff
bugs-dot-jar_data_CAMEL-3388_0919a0f6
--- BugID: CAMEL-3388 Summary: "@OutHeaders in bean binding issue with InOnly MEP" Description: |- When you invoke a bean with a method signature like this in Camel 2.5.0/HEAD, the in and out message both are null (the "Hello!" value just disappears): {code:java} public String doTest(@Body Object body, @Headers Map headers, @OutHeaders Map outHeaders) { return "Hello!"; } {code} The same thing without the headers works OK: {code:java} public String doTest(@Body Object body) { return "Hello!"; } {code} See camel-core/src/test/java/org/apache/camel/component/bean/BeanWithHeadersAndBodyInject3Test.java diff --git a/camel-core/src/main/java/org/apache/camel/builder/ExpressionBuilder.java b/camel-core/src/main/java/org/apache/camel/builder/ExpressionBuilder.java index cdcfa6a..5f73fe3 100644 --- a/camel-core/src/main/java/org/apache/camel/builder/ExpressionBuilder.java +++ b/camel-core/src/main/java/org/apache/camel/builder/ExpressionBuilder.java @@ -254,12 +254,18 @@ public final class ExpressionBuilder { /** * Returns an expression for the outbound message headers * - * @return an expression object which will return the headers + * @return an expression object which will return the headers, will be <tt>null</tt> if the + * exchange is not out capable. */ public static Expression outHeadersExpression() { return new ExpressionAdapter() { public Object evaluate(Exchange exchange) { - return exchange.getOut().getHeaders(); + // only get out headers if the MEP is out capable + if (ExchangeHelper.isOutCapable(exchange)) { + return exchange.getOut().getHeaders(); + } else { + return null; + } } @Override
bugs-dot-jar/camel_extracted_diff/developer-patch_bugs-dot-jar_CAMEL-3388_0919a0f6.diff
bugs-dot-jar_data_CAMEL-7167_1e33fcbc
--- BugID: CAMEL-7167 Summary: 'AbstractListAggregationStrategy : at the end of the split, the body is not replaced by the agregated list' Description: "Using a class that extends AbstractListAggregationStrategy to rebuild a List after the completion of the split cause the body not to be replaced by the agregated list at the end of the split.\n\nIn other words (AbstractListAggregationStrategy.onCompletion(Exchange exchange) is never called.\n\n\nHere is what I do :\n\nfrom(HANDLE_A_LIST)//\n .split(body(), new ListAggregationStrategy())// body is an arrayList of String\n .to(\"log:foo\")//\n \ .end()// end split\n // the body is a string instead of a List\n .end()// end route\n\n \nclass ListAggregationStrategy extends AbstractListAggregationStrategy<String>\n {\n\n @Override\n public String getValue(Exchange exchange)\n {\n return exchange.getIn().getBody();\n \ }\n }\n\nAs workaround, I use .setBody(property(Exchange.GROUPED_EXCHANGE)) after the end of the split." diff --git a/camel-core/src/main/java/org/apache/camel/processor/MulticastProcessor.java b/camel-core/src/main/java/org/apache/camel/processor/MulticastProcessor.java index 84c488a..69e4667 100644 --- a/camel-core/src/main/java/org/apache/camel/processor/MulticastProcessor.java +++ b/camel-core/src/main/java/org/apache/camel/processor/MulticastProcessor.java @@ -47,6 +47,7 @@ import org.apache.camel.Processor; import org.apache.camel.Producer; import org.apache.camel.Traceable; import org.apache.camel.processor.aggregate.AggregationStrategy; +import org.apache.camel.processor.aggregate.CompletionAwareAggregationStrategy; import org.apache.camel.processor.aggregate.TimeoutAwareAggregationStrategy; import org.apache.camel.spi.RouteContext; import org.apache.camel.spi.TracedRouteNodes; @@ -747,6 +748,12 @@ public class MulticastProcessor extends ServiceSupport implements AsyncProcessor IOHelper.close((Closeable) pairs, "pairs", LOG); } + AggregationStrategy strategy = getAggregationStrategy(subExchange); + // invoke the on completion callback + if (strategy instanceof CompletionAwareAggregationStrategy) { + ((CompletionAwareAggregationStrategy) strategy).onCompletion(subExchange); + } + // cleanup any per exchange aggregation strategy removeAggregationStrategyFromExchange(original);
bugs-dot-jar/camel_extracted_diff/developer-patch_bugs-dot-jar_CAMEL-7167_1e33fcbc.diff
bugs-dot-jar_data_CAMEL-3789_9319e139
--- BugID: CAMEL-3789 Summary: org.apache.camel.component.file.strategy.MarkerFileExclusiveReadLockStrategy is not thread-safe Description: "MarkerFileExclusiveReadLockStrategy is not thread-safe. When I run a File endpoint with more than one thread the MarkerFileExclusiveReadLockStrategy only deletes the last file to start being processed. \n\nThe MarkerFileExclusiveReadLockStrategy uses global variables: \nprivate File lock; \nprivate String lockFileName; \nand gives them values on the acquireExclusiveReadLock method. When another thread calls the releaseExclusiveReadLock method it uses the global variables to delete the locked file. That means that if another thread came and called the acquireExclusiveReadLock it would have changed the values on the global variables. \n\nIf lock and lockFileName are not global variables the problem seems to disappear and I can a multithreaded File endpoint and not locked file is left undeleted. \n" diff --git a/camel-core/src/main/java/org/apache/camel/component/file/FileOperations.java b/camel-core/src/main/java/org/apache/camel/component/file/FileOperations.java index 206bb98..1c28345 100644 --- a/camel-core/src/main/java/org/apache/camel/component/file/FileOperations.java +++ b/camel-core/src/main/java/org/apache/camel/component/file/FileOperations.java @@ -54,7 +54,7 @@ public class FileOperations implements GenericFileOperations<File> { this.endpoint = (FileEndpoint) endpoint; } - public boolean deleteFile(String name) throws GenericFileOperationFailedException { + public boolean deleteFile(String name) throws GenericFileOperationFailedException { File file = new File(name); return FileUtil.deleteFile(file); } @@ -71,7 +71,7 @@ public class FileOperations implements GenericFileOperations<File> { } public boolean buildDirectory(String directory, boolean absolute) throws GenericFileOperationFailedException { - ObjectHelper.notNull(endpoint, "endpoint"); + ObjectHelper.notNull(endpoint, "endpoint"); // always create endpoint defined directory if (endpoint.isAutoCreate() && !endpoint.getFile().exists()) { @@ -106,12 +106,17 @@ public class FileOperations implements GenericFileOperations<File> { } } - if (path.isDirectory() && path.exists()) { - // the directory already exists - return true; - } else { - LOG.trace("Building directory: {}", path); - return path.mkdirs(); + // We need to make sure that this is thread-safe and only one thread tries to create the path directory at the same time. + synchronized (this) { + if (path.isDirectory() && path.exists()) { + // the directory already exists + return true; + } else { + if (LOG.isTraceEnabled()) { + LOG.trace("Building directory: " + path); + } + return path.mkdirs(); + } } } @@ -152,7 +157,9 @@ public class FileOperations implements GenericFileOperations<File> { if (file.exists()) { if (endpoint.getFileExist() == GenericFileExist.Ignore) { // ignore but indicate that the file was written - LOG.trace("An existing file already exists: {}. Ignore and do not override it.", file); + if (LOG.isTraceEnabled()) { + LOG.trace("An existing file already exists: " + file + ". Ignore and do not override it."); + } return true; } else if (endpoint.getFileExist() == GenericFileExist.Fail) { throw new GenericFileOperationFailedException("File already exist: " + file + ". Cannot write new file."); @@ -168,7 +175,7 @@ public class FileOperations implements GenericFileOperations<File> { // is the body file based File source = null; // get the File Object from in message - source = exchange.getIn().getBody(File.class); + source = exchange.getIn().getBody(File.class); if (source != null) { // okay we know the body is a file type @@ -222,13 +229,17 @@ public class FileOperations implements GenericFileOperations<File> { } if (last != null) { boolean result = file.setLastModified(last); - LOG.trace("Keeping last modified timestamp: {} on file: {} with result: {}", new Object[]{last, file, result}); + if (LOG.isTraceEnabled()) { + LOG.trace("Keeping last modified timestamp: " + last + " on file: " + file + " with result: " + result); + } } } } private boolean writeFileByLocalWorkPath(File source, File file) { - LOG.trace("Using local work file being renamed from: {} to: {}", source, file); + if (LOG.isTraceEnabled()) { + LOG.trace("Using local work file being renamed from: " + source + " to: " + file); + } return FileUtil.renameFile(source, file); } @@ -239,7 +250,9 @@ public class FileOperations implements GenericFileOperations<File> { try { out = prepareOutputFileChannel(target, out); - LOG.trace("Using FileChannel to transfer from: {} to: {}", in, out); + if (LOG.isTraceEnabled()) { + LOG.trace("Using FileChannel to transfer from: " + in + " to: " + out); + } long size = in.size(); long position = 0; @@ -257,7 +270,9 @@ public class FileOperations implements GenericFileOperations<File> { try { out = prepareOutputFileChannel(target, out); - LOG.trace("Using InputStream to transfer from: {} to: {}", in, out); + if (LOG.isTraceEnabled()) { + LOG.trace("Using InputStream to transfer from: " + in + " to: " + out); + } int size = endpoint.getBufferSize(); byte[] buffer = new byte[size]; ByteBuffer byteBuffer = ByteBuffer.wrap(buffer); @@ -277,7 +292,7 @@ public class FileOperations implements GenericFileOperations<File> { /** * Creates and prepares the output file channel. Will position itself in correct position if the file is writable - * eg. it should append or override any existing content. + * eg. it should append or override any existing content. */ private FileChannel prepareOutputFileChannel(File target, FileChannel out) throws IOException { if (endpoint.getFileExist() == GenericFileExist.Append) { diff --git a/camel-core/src/main/java/org/apache/camel/component/file/strategy/GenericFileDeleteProcessStrategy.java b/camel-core/src/main/java/org/apache/camel/component/file/strategy/GenericFileDeleteProcessStrategy.java index 9235dcc..8f5ff7b 100644 --- a/camel-core/src/main/java/org/apache/camel/component/file/strategy/GenericFileDeleteProcessStrategy.java +++ b/camel-core/src/main/java/org/apache/camel/component/file/strategy/GenericFileDeleteProcessStrategy.java @@ -29,19 +29,22 @@ public class GenericFileDeleteProcessStrategy<T> extends GenericFileProcessStrat @Override public boolean begin(GenericFileOperations<T> operations, GenericFileEndpoint<T> endpoint, Exchange exchange, GenericFile<T> file) throws Exception { - // must invoke super - boolean result = super.begin(operations, endpoint, exchange, file); - if (!result) { - return false; - } + + // We need to invoke super, but to the file that we are going to use for processing, so we do super after renaming. + GenericFile<T> to = file; if (beginRenamer != null) { GenericFile<T> newName = beginRenamer.renameFile(exchange, file); - GenericFile<T> to = renameFile(operations, file, newName); + to = renameFile(operations, file, newName); if (to != null) { to.bindToExchange(exchange); } } + // must invoke super + boolean result = super.begin(operations, endpoint, exchange, to); + if (!result) { + return false; + } return true; } @@ -79,7 +82,7 @@ public class GenericFileDeleteProcessStrategy<T> extends GenericFileProcessStrat throw new GenericFileOperationFailedException("Cannot delete file: " + file); } } - + @Override public void rollback(GenericFileOperations<T> operations, GenericFileEndpoint<T> endpoint, Exchange exchange, GenericFile<T> file) throws Exception { // must invoke super @@ -98,7 +101,7 @@ public class GenericFileDeleteProcessStrategy<T> extends GenericFileProcessStrat renameFile(operations, file, newName); } } - + public GenericFileRenamer<T> getFailureRenamer() { return failureRenamer; } @@ -114,4 +117,4 @@ public class GenericFileDeleteProcessStrategy<T> extends GenericFileProcessStrat public void setBeginRenamer(GenericFileRenamer<T> beginRenamer) { this.beginRenamer = beginRenamer; } -} \ No newline at end of file +} diff --git a/camel-core/src/main/java/org/apache/camel/component/file/strategy/GenericFileRenameProcessStrategy.java b/camel-core/src/main/java/org/apache/camel/component/file/strategy/GenericFileRenameProcessStrategy.java index 1e32688..943e71f 100644 --- a/camel-core/src/main/java/org/apache/camel/component/file/strategy/GenericFileRenameProcessStrategy.java +++ b/camel-core/src/main/java/org/apache/camel/component/file/strategy/GenericFileRenameProcessStrategy.java @@ -31,19 +31,22 @@ public class GenericFileRenameProcessStrategy<T> extends GenericFileProcessStrat @Override public boolean begin(GenericFileOperations<T> operations, GenericFileEndpoint<T> endpoint, Exchange exchange, GenericFile<T> file) throws Exception { - // must invoke super - boolean result = super.begin(operations, endpoint, exchange, file); - if (!result) { - return false; - } + + // We need to invoke super, but to the file that we are going to use for processing, so we do super after renaming. + GenericFile<T> to = file; if (beginRenamer != null) { GenericFile<T> newName = beginRenamer.renameFile(exchange, file); - GenericFile<T> to = renameFile(operations, file, newName); + to = renameFile(operations, file, newName); if (to != null) { to.bindToExchange(exchange); } } + // must invoke super + boolean result = super.begin(operations, endpoint, exchange, to); + if (!result) { + return false; + } return true; } diff --git a/camel-core/src/main/java/org/apache/camel/component/file/strategy/MarkerFileExclusiveReadLockStrategy.java b/camel-core/src/main/java/org/apache/camel/component/file/strategy/MarkerFileExclusiveReadLockStrategy.java index 6d72d19..734a654 100644 --- a/camel-core/src/main/java/org/apache/camel/component/file/strategy/MarkerFileExclusiveReadLockStrategy.java +++ b/camel-core/src/main/java/org/apache/camel/component/file/strategy/MarkerFileExclusiveReadLockStrategy.java @@ -34,8 +34,6 @@ import org.slf4j.LoggerFactory; */ public class MarkerFileExclusiveReadLockStrategy implements GenericFileExclusiveReadLockStrategy<File> { private static final transient Logger LOG = LoggerFactory.getLogger(MarkerFileExclusiveReadLockStrategy.class); - private File lock; - private String lockFileName; public void prepareOnStartup(GenericFileOperations<File> operations, GenericFileEndpoint<File> endpoint) { String dir = endpoint.getConfiguration().getDirectory(); @@ -50,28 +48,25 @@ public class MarkerFileExclusiveReadLockStrategy implements GenericFileExclusive public boolean acquireExclusiveReadLock(GenericFileOperations<File> operations, GenericFile<File> file, Exchange exchange) throws Exception { - lockFileName = file.getAbsoluteFilePath() + FileComponent.DEFAULT_LOCK_FILE_POSTFIX; + String lockFileName = getLockFileName(file); LOG.trace("Locking the file: {} using the lock file name: {}", file, lockFileName); // create a plain file as marker filer for locking (do not use FileLock) - lock = new File(lockFileName); + File lock = new File(lockFileName); boolean acquired = lock.createNewFile(); - if (!acquired) { - lock = null; - - } return acquired; } public void releaseExclusiveReadLock(GenericFileOperations<File> operations, GenericFile<File> file, Exchange exchange) throws Exception { - if (lock != null) { - LOG.trace("Unlocking file: {}", lockFileName); + String lockFileName = getLockFileName(file); + File lock = new File(lockFileName); - boolean deleted = FileUtil.deleteFile(lock); - LOG.trace("Lock file: {} was deleted: {}", lockFileName, deleted); - } + LOG.trace("Unlocking file: {}", lockFileName); + + boolean deleted = FileUtil.deleteFile(lock); + LOG.trace("Lock file: {} was deleted: {}", lockFileName, deleted); } public void setTimeout(long timeout) { @@ -101,4 +96,8 @@ public class MarkerFileExclusiveReadLockStrategy implements GenericFileExclusive } } + private static String getLockFileName(GenericFile<File> file) { + return file.getAbsoluteFilePath() + FileComponent.DEFAULT_LOCK_FILE_POSTFIX; + } + }
bugs-dot-jar/camel_extracted_diff/developer-patch_bugs-dot-jar_CAMEL-3789_9319e139.diff
bugs-dot-jar_data_CAMEL-7568_b3377b16
--- BugID: CAMEL-7568 Summary: OnComplete does not work on transactioned route after rollback Description: "Example:\n{code:title=Route Sample|borderStyle=solid}\nthis.from(\"servlet:///test\").routeId(\"CamelTestRoute\") \n .onCompletion() \n .bean(this.logCompletionRoute) \n .end() \n .onException(Exception.class) \n .log(LoggingLevel.ERROR, this.log, \"Error on processing message. Sending Rollback command!\") \n .log(LoggingLevel.ERROR, this.log, \"${exception.stacktrace}\") \n .rollback()\n .handled(true) \n .end() \n .transacted(RouteTransactionConfiguration.PROPAGATION_REQUIRED) \n .process(new Processor() { \n @Override \n public void process(Exchange exchange) throws Exception { \n throw new Exception(); \n }}); \n{code}\n\nIn this sample, the OnCompletion bean never is executed. But, if I remove the \"rollback()\" call, it is executed properly.\n\nthanks," diff --git a/camel-core/src/main/java/org/apache/camel/processor/OnCompletionProcessor.java b/camel-core/src/main/java/org/apache/camel/processor/OnCompletionProcessor.java index abbdcd0..6575cb2 100644 --- a/camel-core/src/main/java/org/apache/camel/processor/OnCompletionProcessor.java +++ b/camel-core/src/main/java/org/apache/camel/processor/OnCompletionProcessor.java @@ -131,6 +131,8 @@ public class OnCompletionProcessor extends ServiceSupport implements AsyncProces Object failureHandled = exchange.removeProperty(Exchange.FAILURE_HANDLED); Object caught = exchange.removeProperty(Exchange.EXCEPTION_CAUGHT); Object errorhandlerHandled = exchange.removeProperty(Exchange.ERRORHANDLER_HANDLED); + Object rollbackOnly = exchange.removeProperty(Exchange.ROLLBACK_ONLY); + Object rollbackOnlyLast = exchange.removeProperty(Exchange.ROLLBACK_ONLY_LAST); Exception cause = exchange.getException(); exchange.setException(null); @@ -153,6 +155,12 @@ public class OnCompletionProcessor extends ServiceSupport implements AsyncProces if (errorhandlerHandled != null) { exchange.setProperty(Exchange.ERRORHANDLER_HANDLED, errorhandlerHandled); } + if (rollbackOnly != null) { + exchange.setProperty(Exchange.ROLLBACK_ONLY, rollbackOnly); + } + if (rollbackOnlyLast != null) { + exchange.setProperty(Exchange.ROLLBACK_ONLY, rollbackOnlyLast); + } if (cause != null) { exchange.setException(cause); }
bugs-dot-jar/camel_extracted_diff/developer-patch_bugs-dot-jar_CAMEL-7568_b3377b16.diff
bugs-dot-jar_data_CAMEL-7478_69b00a31
--- BugID: CAMEL-7478 Summary: Simple Language - Length of array properties is not correctly evaluated Description: |- If the exchange body is an array, then {{body.length}} returns correctly the length of the array. However, if the array is a property of an object, then not the correct value is returned: {code:title=MyClass.java} public class MyClass { public Object[] getMyArray() { return new Object[]{"Hallo", "World", "!"}; } } {code} Accessing the property {{myArray}} with Simple: {code} <setHeader headerName="mySimpleHeader"> <simple>body.myArray.length</simple> </setHeader> <log message="mySimpleHeader = ${header.mySimpleHeader}" /> {code} Java: {code} final ProducerTemplate template = main.getCamelTemplate(); template.sendBody("direct:start", new MyClass()); {code} Log: {noformat} [main] route1 INFO mySimpleHeader = 1 {noformat} The return value should be {{3}} instead of {{1}}. diff --git a/camel-core/src/main/java/org/apache/camel/component/bean/BeanInfo.java b/camel-core/src/main/java/org/apache/camel/component/bean/BeanInfo.java index 53c1254..5b8804d 100644 --- a/camel-core/src/main/java/org/apache/camel/component/bean/BeanInfo.java +++ b/camel-core/src/main/java/org/apache/camel/component/bean/BeanInfo.java @@ -228,6 +228,8 @@ public class BeanInfo { List<ParameterInfo> lpi = new ArrayList<ParameterInfo>(1); lpi.add(pi); methodInfo = new MethodInfo(exchange.getContext(), pojo.getClass(), method, lpi, lpi, false, false); + // Need to update the message body to be pojo for the invocation + exchange.getIn().setBody(pojo); } catch (NoSuchMethodException e) { throw new MethodNotFoundException(exchange, pojo, "getClass"); } diff --git a/camel-core/src/main/java/org/apache/camel/language/bean/BeanExpression.java b/camel-core/src/main/java/org/apache/camel/language/bean/BeanExpression.java index 1092f6e..3cbc2fa 100644 --- a/camel-core/src/main/java/org/apache/camel/language/bean/BeanExpression.java +++ b/camel-core/src/main/java/org/apache/camel/language/bean/BeanExpression.java @@ -300,8 +300,6 @@ public class BeanExpression implements Expression, Predicate { // prepare for next bean to invoke beanToCall = result; - // we need to set the result to the exchange for further processing - resultExchange.getIn().setBody(result); } }
bugs-dot-jar/camel_extracted_diff/developer-patch_bugs-dot-jar_CAMEL-7478_69b00a31.diff
bugs-dot-jar_data_CAMEL-5644_15d0fd9b
--- BugID: CAMEL-5644 Summary: Bean component - Should use try conversion when choosing method based on parameter type matching Description: | When the bean component has to pick among overloaded methods, then it does best matching on parameter types etc. We should relax the type conversion to try attempt. diff --git a/camel-core/src/main/java/org/apache/camel/component/bean/BeanInfo.java b/camel-core/src/main/java/org/apache/camel/component/bean/BeanInfo.java index 4a8ddef..880c400 100644 --- a/camel-core/src/main/java/org/apache/camel/component/bean/BeanInfo.java +++ b/camel-core/src/main/java/org/apache/camel/component/bean/BeanInfo.java @@ -52,8 +52,6 @@ import org.apache.camel.util.ObjectHelper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import static org.apache.camel.util.ExchangeHelper.convertToType; - /** * Represents the metadata about a bean type created via a combination of * introspection and annotations together with some useful sensible defaults @@ -571,8 +569,9 @@ public class BeanInfo { if (methodInfo.getBodyParameterType().isInstance(body)) { return methodInfo; } - - Object value = convertToType(exchange, methodInfo.getBodyParameterType(), body); + + // we should only try to convert, as we are looking for best match + Object value = exchange.getContext().getTypeConverter().tryConvertTo(methodInfo.getBodyParameterType(), exchange, body); if (value != null) { if (LOG.isTraceEnabled()) { LOG.trace("Converted body from: {} to: {}",
bugs-dot-jar/camel_extracted_diff/developer-patch_bugs-dot-jar_CAMEL-5644_15d0fd9b.diff
bugs-dot-jar_data_CAMEL-7275_44cad623
--- BugID: CAMEL-7275 Summary: Using doTry .. doCatch with recipient list should not trigger error handler during recipient list work Description: |- When you have a route like this {code} from("direct:start") .doTry() .recipientList(constant("direct:foo")).end() .doCatch(Exception.class) .to("mock:catch") .transform().constant("doCatch") .end() .to("mock:result"); {code} Then if an exception was thrown it should be catch by doCatch A similar route with to instead works as expected. diff --git a/camel-core/src/main/java/org/apache/camel/Exchange.java b/camel-core/src/main/java/org/apache/camel/Exchange.java index 506ba29..f9f3fe3 100644 --- a/camel-core/src/main/java/org/apache/camel/Exchange.java +++ b/camel-core/src/main/java/org/apache/camel/Exchange.java @@ -194,6 +194,7 @@ public interface Exchange { String TRACE_EVENT_NODE_ID = "CamelTraceEventNodeId"; String TRACE_EVENT_TIMESTAMP = "CamelTraceEventTimestamp"; String TRACE_EVENT_EXCHANGE = "CamelTraceEventExchange"; + String TRY_ROUTE_BLOCK = "TryRouteBlock"; String TRANSFER_ENCODING = "Transfer-Encoding"; String UNIT_OF_WORK_EXHAUSTED = "CamelUnitOfWorkExhausted"; diff --git a/camel-core/src/main/java/org/apache/camel/processor/MulticastProcessor.java b/camel-core/src/main/java/org/apache/camel/processor/MulticastProcessor.java index 69e4667..697ae32 100644 --- a/camel-core/src/main/java/org/apache/camel/processor/MulticastProcessor.java +++ b/camel-core/src/main/java/org/apache/camel/processor/MulticastProcessor.java @@ -885,7 +885,10 @@ public class MulticastProcessor extends ServiceSupport implements AsyncProcessor protected Processor createErrorHandler(RouteContext routeContext, Exchange exchange, Processor processor) { Processor answer; - if (routeContext != null) { + boolean tryBlock = exchange.getProperty(Exchange.TRY_ROUTE_BLOCK, false, boolean.class); + + // do not wrap in error handler if we are inside a try block + if (!tryBlock && routeContext != null) { // wrap the producer in error handler so we have fine grained error handling on // the output side instead of the input side // this is needed to support redelivery on that output alone and not doing redelivery diff --git a/camel-core/src/main/java/org/apache/camel/processor/TryProcessor.java b/camel-core/src/main/java/org/apache/camel/processor/TryProcessor.java index 1bfe5dd..b53a14e 100644 --- a/camel-core/src/main/java/org/apache/camel/processor/TryProcessor.java +++ b/camel-core/src/main/java/org/apache/camel/processor/TryProcessor.java @@ -73,6 +73,7 @@ public class TryProcessor extends ServiceSupport implements AsyncProcessor, Navi exchange.setProperty(Exchange.EXCEPTION_HANDLED, null); while (continueRouting(processors, exchange)) { + exchange.setProperty(Exchange.TRY_ROUTE_BLOCK, true); ExchangeHelper.prepareOutToIn(exchange); // process the next processor @@ -92,6 +93,7 @@ public class TryProcessor extends ServiceSupport implements AsyncProcessor, Navi } ExchangeHelper.prepareOutToIn(exchange); + exchange.removeProperty(Exchange.TRY_ROUTE_BLOCK); exchange.setProperty(Exchange.EXCEPTION_HANDLED, lastHandled); LOG.trace("Processing complete for exchangeId: {} >>> {}", exchange.getExchangeId(), exchange); callback.done(true); @@ -115,6 +117,7 @@ public class TryProcessor extends ServiceSupport implements AsyncProcessor, Navi // continue processing the try .. catch .. finally asynchronously while (continueRouting(processors, exchange)) { + exchange.setProperty(Exchange.TRY_ROUTE_BLOCK, true); ExchangeHelper.prepareOutToIn(exchange); // process the next processor @@ -130,6 +133,7 @@ public class TryProcessor extends ServiceSupport implements AsyncProcessor, Navi } ExchangeHelper.prepareOutToIn(exchange); + exchange.removeProperty(Exchange.TRY_ROUTE_BLOCK); exchange.setProperty(Exchange.EXCEPTION_HANDLED, lastHandled); LOG.trace("Processing complete for exchangeId: {} >>> {}", exchange.getExchangeId(), exchange); callback.done(false);
bugs-dot-jar/camel_extracted_diff/developer-patch_bugs-dot-jar_CAMEL-7275_44cad623.diff
bugs-dot-jar_data_MATH-320_b2f3f6db
--- BugID: MATH-320 Summary: NaN singular value from SVD Description: "The following jython code\nStart code\n\nfrom org.apache.commons.math.linear import *\n \nAlist = [[1.0, 2.0, 3.0],[2.0,3.0,4.0],[3.0,5.0,7.0]]\n \nA = Array2DRowRealMatrix(Alist)\n \ndecomp = SingularValueDecompositionImpl(A)\n \nprint decomp.getSingularValues()\n\nEnd code\n\nprints\narray('d', [11.218599757513008, 0.3781791648535976, nan])\nThe last singular value should be something very close to 0 since the matrix\nis rank deficient. \ When i use the result from getSolver() to solve a system, i end \nup with a bunch of NaNs in the solution. I assumed i would get back a least squares solution.\n\nDoes this SVD implementation require that the matrix be full rank? If so, then i would expect\nan exception to be thrown from the constructor or one of the methods.\n\n\n" diff --git a/src/main/java/org/apache/commons/math/linear/SingularValueDecompositionImpl.java b/src/main/java/org/apache/commons/math/linear/SingularValueDecompositionImpl.java index 6003ed6..e418c08 100644 --- a/src/main/java/org/apache/commons/math/linear/SingularValueDecompositionImpl.java +++ b/src/main/java/org/apache/commons/math/linear/SingularValueDecompositionImpl.java @@ -159,27 +159,28 @@ public class SingularValueDecompositionImpl implements SingularValueDecompositio if (m >= n) { // the tridiagonal matrix is Bt.B, where B is upper bidiagonal final RealMatrix e = - eigenDecomposition.getV().getSubMatrix(0, p - 1, 0, p - 1); + eigenDecomposition.getV().getSubMatrix(0, n - 1, 0, p - 1); final double[][] eData = e.getData(); final double[][] wData = new double[m][p]; double[] ei1 = eData[0]; - for (int i = 0; i < p - 1; ++i) { + for (int i = 0; i < p; ++i) { // compute W = B.E.S^(-1) where E is the eigenvectors matrix final double mi = mainBidiagonal[i]; - final double si = secondaryBidiagonal[i]; final double[] ei0 = ei1; final double[] wi = wData[i]; - ei1 = eData[i + 1]; - for (int j = 0; j < p; ++j) { - wi[j] = (mi * ei0[j] + si * ei1[j]) / singularValues[j]; + if (i < n - 1) { + ei1 = eData[i + 1]; + final double si = secondaryBidiagonal[i]; + for (int j = 0; j < p; ++j) { + wi[j] = (mi * ei0[j] + si * ei1[j]) / singularValues[j]; + } + } else { + for (int j = 0; j < p; ++j) { + wi[j] = mi * ei0[j] / singularValues[j]; + } } } - // last row - final double lastMain = mainBidiagonal[p - 1]; - final double[] wr1 = wData[p - 1]; - for (int j = 0; j < p; ++j) { - wr1[j] = ei1[j] * lastMain / singularValues[j]; - } + for (int i = p; i < m; ++i) { wData[i] = new double[p]; } @@ -247,26 +248,26 @@ public class SingularValueDecompositionImpl implements SingularValueDecompositio // the tridiagonal matrix is B.Bt, where B is lower bidiagonal // compute W = Bt.E.S^(-1) where E is the eigenvectors matrix final RealMatrix e = - eigenDecomposition.getV().getSubMatrix(0, p - 1, 0, p - 1); + eigenDecomposition.getV().getSubMatrix(0, m - 1, 0, p - 1); final double[][] eData = e.getData(); final double[][] wData = new double[n][p]; double[] ei1 = eData[0]; - for (int i = 0; i < p - 1; ++i) { + for (int i = 0; i < p; ++i) { final double mi = mainBidiagonal[i]; - final double si = secondaryBidiagonal[i]; final double[] ei0 = ei1; final double[] wi = wData[i]; - ei1 = eData[i + 1]; - for (int j = 0; j < p; ++j) { - wi[j] = (mi * ei0[j] + si * ei1[j]) / singularValues[j]; + if (i < m - 1) { + ei1 = eData[i + 1]; + final double si = secondaryBidiagonal[i]; + for (int j = 0; j < p; ++j) { + wi[j] = (mi * ei0[j] + si * ei1[j]) / singularValues[j]; + } + } else { + for (int j = 0; j < p; ++j) { + wi[j] = mi * ei0[j] / singularValues[j]; + } } } - // last row - final double lastMain = mainBidiagonal[p - 1]; - final double[] wr1 = wData[p - 1]; - for (int j = 0; j < p; ++j) { - wr1[j] = ei1[j] * lastMain / singularValues[j]; - } for (int i = p; i < n; ++i) { wData[i] = new double[p]; }
bugs-dot-jar/commons-math_extracted_diff/developer-patch_bugs-dot-jar_MATH-320_b2f3f6db.diff
bugs-dot-jar_data_MATH-482_6d6649ef
--- BugID: MATH-482 Summary: FastMath.max(50.0f, -50.0f) => -50.0f; should be +50.0f Description: |- FastMath.max(50.0f, -50.0f) => -50.0f; should be +50.0f. This is because the wrong variable is returned. The bug was not detected by the test case "testMinMaxFloat()" because that has a bug too - it tests doubles, not floats. diff --git a/src/main/java/org/apache/commons/math/util/FastMath.java b/src/main/java/org/apache/commons/math/util/FastMath.java index 8cba4d4..4f7d447 100644 --- a/src/main/java/org/apache/commons/math/util/FastMath.java +++ b/src/main/java/org/apache/commons/math/util/FastMath.java @@ -3479,7 +3479,7 @@ public class FastMath { * @return b if a is lesser or equal to b, a otherwise */ public static float max(final float a, final float b) { - return (a <= b) ? b : (Float.isNaN(a + b) ? Float.NaN : b); + return (a <= b) ? b : (Float.isNaN(a + b) ? Float.NaN : a); } /** Compute the maximum of two values
bugs-dot-jar/commons-math_extracted_diff/developer-patch_bugs-dot-jar_MATH-482_6d6649ef.diff
bugs-dot-jar_data_MATH-631_ebc61de9
--- BugID: MATH-631 Summary: '"RegulaFalsiSolver" failure' Description: | The following unit test: {code} @Test public void testBug() { final UnivariateRealFunction f = new UnivariateRealFunction() { @Override public double value(double x) { return Math.exp(x) - Math.pow(Math.PI, 3.0); } }; UnivariateRealSolver solver = new RegulaFalsiSolver(); double root = solver.solve(100, f, 1, 10); } {code} fails with {noformat} illegal state: maximal count (100) exceeded: evaluations {noformat} Using "PegasusSolver", the answer is found after 17 evaluations. diff --git a/src/main/java/org/apache/commons/math/analysis/solvers/BaseSecantSolver.java b/src/main/java/org/apache/commons/math/analysis/solvers/BaseSecantSolver.java index b3a23a1..c781a90 100644 --- a/src/main/java/org/apache/commons/math/analysis/solvers/BaseSecantSolver.java +++ b/src/main/java/org/apache/commons/math/analysis/solvers/BaseSecantSolver.java @@ -183,14 +183,7 @@ public abstract class BaseSecantSolver f0 *= f1 / (f1 + fx); break; case REGULA_FALSI: - if (x == x1) { - final double delta = FastMath.max(rtol * FastMath.abs(x1), - atol); - // Update formula cannot make any progress: Update the - // search interval. - x0 = 0.5 * (x0 + x1 - delta); - f0 = computeObjectiveValue(x0); - } + // Nothing. break; default: // Should never happen.
bugs-dot-jar/commons-math_extracted_diff/developer-patch_bugs-dot-jar_MATH-631_ebc61de9.diff
bugs-dot-jar_data_MATH-367_3a15d8ce
--- BugID: MATH-367 Summary: AbstractRealVector.sparseIterator fails when vector has exactly one non-zero entry Description: "The following program:\n===\nimport java.util.Iterator;\nimport org.apache.commons.math.linear.*;\n\npublic class SparseIteratorTester\n{\n public static void main(String[] args) {\n double vdata[] = { 0.0, 1.0, 0.0 };\n RealVector v = new ArrayRealVector(vdata);\n \ Iterator<RealVector.Entry> iter = v.sparseIterator();\n while(iter.hasNext()) {\n RealVector.Entry entry = iter.next();\n System.out.printf(\"%d: %f\\n\", entry.getIndex(), entry.getValue());\n } \n } \n} \n===\ngenerates this output:\n\n1: 1.000000\nException in thread \"main\" java.lang.ArrayIndexOutOfBoundsException: -1\n\tat org.apache.commons.math.linear.ArrayRealVector.getEntry(ArrayRealVector.java:995)\n\tat org.apache.commons.math.linear.AbstractRealVector$EntryImpl.getValue(AbstractRealVector.java:850)\n\tat test.SparseIteratorTester.main(SparseIteratorTester.java:13)\n===\n\nThis patch fixes it, and simplifies AbstractRealVector.SparseEntryIterator (sorry, i don't see any form entry for attaching a file)\n===\nIndex: src/main/java/org/apache/commons/math/linear/AbstractRealVector.java\n===================================================================\n--- src/main/java/org/apache/commons/math/linear/AbstractRealVector.java\t(revision 936985)\n+++ src/main/java/org/apache/commons/math/linear/AbstractRealVector.java\t(working copy)\n@@ -18,6 +18,7 @@\n package org.apache.commons.math.linear;\n \n import java.util.Iterator;\n+import java.util.NoSuchElementException;\n \n import org.apache.commons.math.FunctionEvaluationException;\n import org.apache.commons.math.MathRuntimeException;\n@@ -875,40 +876,25 @@\n /** Dimension of the vector. */\n private final int dim;\n \n- /** Temporary entry (reused on each call to {@link #next()}. */\n- private EntryImpl tmp = new EntryImpl();\n-\n- /** Current entry. */\n+ /** Last entry returned by #next(). */\n private EntryImpl current;\n \n- /** Next entry. */\n+ /** Next entry for #next() to return. */\n private EntryImpl next;\n \n /** Simple constructor. */\n protected SparseEntryIterator() {\n dim = getDimension();\n current = new EntryImpl();\n- \ if (current.getValue() == 0) {\n- advance(current);\n- \ }\n- if(current.getIndex() >= 0){\n- // There is at least one non-zero entry\n- next = new EntryImpl();\n- next.setIndex(current.getIndex());\n+ \ next = new EntryImpl();\n+ if(next.getValue() == 0)\n advance(next);\n- \ } else {\n- // The vector consists of only zero entries, so deny having a next\n- current = null;\n- }\n }\n \n- /** Advance an entry up to the next non null one.\n+ /** Advance an entry up to the next nonzero value.\n * @param e entry to advance\n \ */\n protected void advance(EntryImpl e) {\n- if (e == null) {\n- return;\n- }\n do {\n e.setIndex(e.getIndex() + 1);\n } while (e.getIndex() < dim && e.getValue() == 0);\n@@ -919,22 +905,17 @@\n \n /** {@inheritDoc} */\n public boolean hasNext() {\n- return current != null;\n+ return next.getIndex() >= 0;\n }\n \n /** {@inheritDoc} */\n public Entry next() {\n- \ tmp.setIndex(current.getIndex());\n- if (next != null) {\n- \ current.setIndex(next.getIndex());\n- advance(next);\n- \ if (next.getIndex() < 0) {\n- next = null;\n- \ }\n- } else {\n- current = null;\n- }\n- \ return tmp;\n+ int index = next.getIndex();\n+ if(index < 0)\n+ throw new NoSuchElementException();\n+ current.setIndex(index);\n+ \ advance(next);\n+ return current;\n }\n \n /** {@inheritDoc} */\n" diff --git a/src/main/java/org/apache/commons/math/linear/AbstractRealVector.java b/src/main/java/org/apache/commons/math/linear/AbstractRealVector.java index 023648d..e172543 100644 --- a/src/main/java/org/apache/commons/math/linear/AbstractRealVector.java +++ b/src/main/java/org/apache/commons/math/linear/AbstractRealVector.java @@ -18,6 +18,7 @@ package org.apache.commons.math.linear; import java.util.Iterator; +import java.util.NoSuchElementException; import org.apache.commons.math.FunctionEvaluationException; import org.apache.commons.math.MathRuntimeException; @@ -875,34 +876,23 @@ public abstract class AbstractRealVector implements RealVector { /** Dimension of the vector. */ private final int dim; - /** Temporary entry (reused on each call to {@link #next()}. */ - private EntryImpl tmp = new EntryImpl(); - - /** Current entry. */ + /** last entry returned by {@link #next()} */ private EntryImpl current; - /** Next entry. */ + /** Next entry for {@link #next()} to return. */ private EntryImpl next; /** Simple constructor. */ protected SparseEntryIterator() { dim = getDimension(); current = new EntryImpl(); - if (current.getValue() == 0) { - advance(current); - } - if(current.getIndex() >= 0){ - // There is at least one non-zero entry - next = new EntryImpl(); - next.setIndex(current.getIndex()); - advance(next); - } else { - // The vector consists of only zero entries, so deny having a next - current = null; + next = new EntryImpl(); + if(next.getValue() == 0){ + advance(next); } } - /** Advance an entry up to the next non null one. + /** Advance an entry up to the next nonzero one. * @param e entry to advance */ protected void advance(EntryImpl e) { @@ -919,22 +909,18 @@ public abstract class AbstractRealVector implements RealVector { /** {@inheritDoc} */ public boolean hasNext() { - return current != null; + return next.getIndex() >= 0; } /** {@inheritDoc} */ public Entry next() { - tmp.setIndex(current.getIndex()); - if (next != null) { - current.setIndex(next.getIndex()); - advance(next); - if (next.getIndex() < 0) { - next = null; - } - } else { - current = null; - } - return tmp; + int index = next.getIndex(); + if(index < 0){ + throw new NoSuchElementException(); + } + current.setIndex(index); + advance(next); + return current; } /** {@inheritDoc} */
bugs-dot-jar/commons-math_extracted_diff/developer-patch_bugs-dot-jar_MATH-367_3a15d8ce.diff
bugs-dot-jar_data_MATH-957_9aabf587
--- BugID: MATH-957 Summary: Use analytical function for UniformRealDistribution.inverseCumulativeProbability Description: |- The inverse CDF is currently solved by a root finding function. It would be much simpler (and faster) to use the analytical expression. This would save the user from having to set the inverseCumAccuracy correctly. I've attached a patch that implements this. diff --git a/src/main/java/org/apache/commons/math3/distribution/UniformRealDistribution.java b/src/main/java/org/apache/commons/math3/distribution/UniformRealDistribution.java index 0d279de..62ccb0c 100644 --- a/src/main/java/org/apache/commons/math3/distribution/UniformRealDistribution.java +++ b/src/main/java/org/apache/commons/math3/distribution/UniformRealDistribution.java @@ -18,6 +18,7 @@ package org.apache.commons.math3.distribution; import org.apache.commons.math3.exception.NumberIsTooLargeException; +import org.apache.commons.math3.exception.OutOfRangeException; import org.apache.commons.math3.exception.util.LocalizedFormats; import org.apache.commons.math3.random.RandomGenerator; import org.apache.commons.math3.random.Well19937c; @@ -32,7 +33,10 @@ import org.apache.commons.math3.random.Well19937c; * @since 3.0 */ public class UniformRealDistribution extends AbstractRealDistribution { - /** Default inverse cumulative probability accuracy. */ + /** Default inverse cumulative probability accuracy. + * @deprecated as of 3.2 not used anymore, will be removed in 4.0 + */ + @Deprecated public static final double DEFAULT_INVERSE_ABSOLUTE_ACCURACY = 1e-9; /** Serializable version identifier. */ private static final long serialVersionUID = 20120109L; @@ -40,8 +44,6 @@ public class UniformRealDistribution extends AbstractRealDistribution { private final double lower; /** Upper bound of this distribution (exclusive). */ private final double upper; - /** Inverse cumulative probability accuracy. */ - private final double solverAbsoluteAccuracy; /** * Create a standard uniform real distribution with lower bound (inclusive) @@ -61,7 +63,7 @@ public class UniformRealDistribution extends AbstractRealDistribution { */ public UniformRealDistribution(double lower, double upper) throws NumberIsTooLargeException { - this(lower, upper, DEFAULT_INVERSE_ABSOLUTE_ACCURACY); + this(new Well19937c(), lower, upper); } /** @@ -71,10 +73,13 @@ public class UniformRealDistribution extends AbstractRealDistribution { * @param upper Upper bound of this distribution (exclusive). * @param inverseCumAccuracy Inverse cumulative probability accuracy. * @throws NumberIsTooLargeException if {@code lower >= upper}. + * @deprecated as of 3.2, inverse CDF is now calculated analytically, use + * {@link #UniformRealDistribution(double, double)} instead. */ + @Deprecated public UniformRealDistribution(double lower, double upper, double inverseCumAccuracy) throws NumberIsTooLargeException { - this(new Well19937c(), lower, upper, inverseCumAccuracy); + this(new Well19937c(), lower, upper); } /** @@ -86,11 +91,30 @@ public class UniformRealDistribution extends AbstractRealDistribution { * @param inverseCumAccuracy Inverse cumulative probability accuracy. * @throws NumberIsTooLargeException if {@code lower >= upper}. * @since 3.1 + * @deprecated as of 3.2, inverse CDF is now calculated analytically, use + * {@link #UniformRealDistribution(RandomGenerator, double, double)} + * instead. */ + @Deprecated public UniformRealDistribution(RandomGenerator rng, double lower, double upper, - double inverseCumAccuracy) + double inverseCumAccuracy){ + this(rng, lower, upper); + } + + /** + * Creates a uniform distribution. + * + * @param rng Random number generator. + * @param lower Lower bound of this distribution (inclusive). + * @param upper Upper bound of this distribution (exclusive). + * @throws NumberIsTooLargeException if {@code lower >= upper}. + * @since 3.1 + */ + public UniformRealDistribution(RandomGenerator rng, + double lower, + double upper) throws NumberIsTooLargeException { super(rng); if (lower >= upper) { @@ -101,7 +125,6 @@ public class UniformRealDistribution extends AbstractRealDistribution { this.lower = lower; this.upper = upper; - solverAbsoluteAccuracy = inverseCumAccuracy; } /** {@inheritDoc} */ @@ -123,10 +146,13 @@ public class UniformRealDistribution extends AbstractRealDistribution { return (x - lower) / (upper - lower); } - /** {@inheritDoc} */ @Override - protected double getSolverAbsoluteAccuracy() { - return solverAbsoluteAccuracy; + public double inverseCumulativeProbability(final double p) + throws OutOfRangeException { + if (p < 0.0 || p > 1.0) { + throw new OutOfRangeException(p, 0, 1); + } + return p * (upper - lower) + lower; } /**
bugs-dot-jar/commons-math_extracted_diff/developer-patch_bugs-dot-jar_MATH-957_9aabf587.diff
bugs-dot-jar_data_MATH-1241_471e6b07
--- BugID: MATH-1241 Summary: Digamma calculation produces SOE on NaN argument Description: |- Digamma doesn't work particularly well with NaNs. How to reproduce: call Gamma.digamma(Double.NaN) Expected outcome: returns NaN or throws a meaningful exception Real outcome: crashes with StackOverflowException, as digamma enters infinite recursion. diff --git a/src/main/java/org/apache/commons/math4/special/Gamma.java b/src/main/java/org/apache/commons/math4/special/Gamma.java index eb3fb5b..aa0e90c 100644 --- a/src/main/java/org/apache/commons/math4/special/Gamma.java +++ b/src/main/java/org/apache/commons/math4/special/Gamma.java @@ -442,6 +442,10 @@ public class Gamma { * @since 2.0 */ public static double digamma(double x) { + if (Double.isNaN(x) || Double.isInfinite(x)) { + return x; + } + if (x > 0 && x <= S_LIMIT) { // use method 5 from Bernardo AS103 // accurate to O(x) @@ -472,6 +476,10 @@ public class Gamma { * @since 2.0 */ public static double trigamma(double x) { + if (Double.isNaN(x) || Double.isInfinite(x)) { + return x; + } + if (x > 0 && x <= S_LIMIT) { return 1 / (x * x); }
bugs-dot-jar/commons-math_extracted_diff/developer-patch_bugs-dot-jar_MATH-1241_471e6b07.diff
bugs-dot-jar_data_MATH-724_9c8bb934
--- BugID: MATH-724 Summary: RandomDataImpl.nextInt does not distribute uniformly for negative lower bound Description: |- When using the RandomDataImpl.nextInt function to get a uniform sample in a [lower, upper] interval, when the lower value is less than zero, the output is not uniformly distributed, as the lowest value is practically never returned. See the attached NextIntUniformTest.java file. It uses a [-3, 5] interval. For several values between 0 and 1, testNextIntUniform1 prints the return value of RandomDataImpl.nextInt (as double and as int). We see that -2 through 5 are returned several times. The -3 value however, is only returned for 0.0, and is thus under-respresented in the integer samples. The output of test method testNextIntUniform2 also clearly shows that value -3 is never sampled. diff --git a/src/main/java/org/apache/commons/math/exception/util/LocalizedFormats.java b/src/main/java/org/apache/commons/math/exception/util/LocalizedFormats.java index cfec8ca..c5c14a9 100644 --- a/src/main/java/org/apache/commons/math/exception/util/LocalizedFormats.java +++ b/src/main/java/org/apache/commons/math/exception/util/LocalizedFormats.java @@ -116,6 +116,7 @@ public enum LocalizedFormats implements Localizable { INDEX_OUT_OF_RANGE("index {0} out of allowed range [{1}, {2}]"), INDEX("index ({0})"), /* keep */ NOT_FINITE_NUMBER("{0} is not a finite number"), /* keep */ + INFINITE_BOUND("interval bounds must be finite"), ARRAY_ELEMENT("value {0} at index {1}"), /* keep */ INFINITE_ARRAY_ELEMENT("Array contains an infinite element, {0} at index {1}"), INFINITE_VALUE_CONVERSION("cannot convert infinite value"), @@ -240,6 +241,7 @@ public enum LocalizedFormats implements Localizable { NO_REGRESSORS("Regression model must include at least one regressor"), NO_RESULT_AVAILABLE("no result available"), NO_SUCH_MATRIX_ENTRY("no entry at indices ({0}, {1}) in a {2}x{3} matrix"), + NAN_NOT_ALLOWED("NaN is not allowed"), NULL_NOT_ALLOWED("null is not allowed"), /* keep */ ARRAY_ZERO_LENGTH_OR_NULL_NOTALLOWED("A null or zero length array not allowed"), COVARIANCE_MATRIX("covariance matrix"), /* keep */ diff --git a/src/main/java/org/apache/commons/math/random/RandomDataImpl.java b/src/main/java/org/apache/commons/math/random/RandomDataImpl.java index 0fda688..16d655b 100644 --- a/src/main/java/org/apache/commons/math/random/RandomDataImpl.java +++ b/src/main/java/org/apache/commons/math/random/RandomDataImpl.java @@ -36,6 +36,7 @@ import org.apache.commons.math.distribution.PascalDistribution; import org.apache.commons.math.distribution.TDistribution; import org.apache.commons.math.distribution.WeibullDistribution; import org.apache.commons.math.distribution.ZipfDistribution; +import org.apache.commons.math.exception.MathIllegalArgumentException; import org.apache.commons.math.exception.MathInternalError; import org.apache.commons.math.exception.NotStrictlyPositiveException; import org.apache.commons.math.exception.NumberIsTooLargeException; @@ -250,7 +251,8 @@ public class RandomDataImpl implements RandomData, Serializable { lower, upper, false); } double r = getRan().nextDouble(); - return (int) ((r * upper) + ((1.0 - r) * lower) + r); + double scaled = r * upper + (1.0 - r) * lower + r; + return (int)FastMath.floor(scaled); } /** @@ -270,7 +272,8 @@ public class RandomDataImpl implements RandomData, Serializable { lower, upper, false); } double r = getRan().nextDouble(); - return (long) ((r * upper) + ((1.0 - r) * lower) + r); + double scaled = r * upper + (1.0 - r) * lower + r; + return (long)FastMath.floor(scaled); } /** @@ -361,7 +364,9 @@ public class RandomDataImpl implements RandomData, Serializable { lower, upper, false); } SecureRandom sec = getSecRan(); - return lower + (int) (sec.nextDouble() * (upper - lower + 1)); + double r = sec.nextDouble(); + double scaled = r * upper + (1.0 - r) * lower + r; + return (int)FastMath.floor(scaled); } /** @@ -382,7 +387,9 @@ public class RandomDataImpl implements RandomData, Serializable { lower, upper, false); } SecureRandom sec = getSecRan(); - return lower + (long) (sec.nextDouble() * (upper - lower + 1)); + double r = sec.nextDouble(); + double scaled = r * upper + (1.0 - r) * lower + r; + return (long)FastMath.floor(scaled); } /** @@ -579,19 +586,26 @@ public class RandomDataImpl implements RandomData, Serializable { * provide a symmetric output interval (both endpoints excluded). * </p> * - * @param lower - * the lower bound. - * @param upper - * the upper bound. - * @return a uniformly distributed random value from the interval (lower, - * upper) - * @throws NumberIsTooLargeException if {@code lower >= upper}. + * @param lower the lower bound. + * @param upper the upper bound. + * @return a uniformly distributed random value from the interval (lower, upper) + * @throws MathIllegalArgumentException if {@code lower >= upper} + * or either bound is infinite or NaN */ public double nextUniform(double lower, double upper) { if (lower >= upper) { - throw new NumberIsTooLargeException(LocalizedFormats.LOWER_BOUND_NOT_BELOW_UPPER_BOUND, - lower, upper, false); + throw new MathIllegalArgumentException(LocalizedFormats.LOWER_BOUND_NOT_BELOW_UPPER_BOUND, + lower, upper); + } + + if (Double.isInfinite(lower) || Double.isInfinite(upper)) { + throw new MathIllegalArgumentException(LocalizedFormats.INFINITE_BOUND); } + + if (Double.isNaN(lower) || Double.isNaN(upper)) { + throw new MathIllegalArgumentException(LocalizedFormats.NAN_NOT_ALLOWED); + } + final RandomGenerator generator = getRan(); // ensure nextDouble() isn't 0.0 @@ -600,7 +614,7 @@ public class RandomDataImpl implements RandomData, Serializable { u = generator.nextDouble(); } - return lower + u * (upper - lower); + return u * upper + (1.0 - u) * lower; } /**
bugs-dot-jar/commons-math_extracted_diff/developer-patch_bugs-dot-jar_MATH-724_9c8bb934.diff
bugs-dot-jar_data_MATH-1117_f4c926ea
--- BugID: MATH-1117 Summary: twod.PolygonsSet.getSize produces NullPointerException if BSPTree has no nodes Description: |- org.apache.commons.math3.geometry.euclidean.twod.PolygonsSet.getSize() uses a tree internally: final BSPTree<Euclidean2D> tree = getTree(false); However, if that tree contains no data, it seems that the reference returned is null, which causes a subsequent NullPointerException. Probably an exception with a message ("tree has no data") would clarify that this is an API usage error. diff --git a/src/main/java/org/apache/commons/math3/geometry/euclidean/twod/PolygonsSet.java b/src/main/java/org/apache/commons/math3/geometry/euclidean/twod/PolygonsSet.java index 3c1b26c..4d0c9d8 100644 --- a/src/main/java/org/apache/commons/math3/geometry/euclidean/twod/PolygonsSet.java +++ b/src/main/java/org/apache/commons/math3/geometry/euclidean/twod/PolygonsSet.java @@ -64,6 +64,16 @@ public class PolygonsSet extends AbstractRegion<Euclidean2D, Euclidean1D> { * cells). In order to avoid building too many small objects, it is * recommended to use the predefined constants * {@code Boolean.TRUE} and {@code Boolean.FALSE}</p> + * <p> + * This constructor is aimed at expert use, as building the tree may + * be a difficult taks. It is not intended for general use and for + * performances reasons does not check thoroughly its input, as this would + * require walking the full tree each time. Failing to provide a tree with + * the proper attributes, <em>will</em> therefore generate problems like + * {@link NullPointerException} or {@link ClassCastException} only later on. + * This limitation is known and explains why this constructor is for expert + * use only. The caller does have the responsibility to provided correct arguments. + * </p> * @param tree inside/outside BSP tree representing the region * @param tolerance tolerance below which points are considered identical * @since 3.3 @@ -219,6 +229,10 @@ public class PolygonsSet extends AbstractRegion<Euclidean2D, Euclidean1D> { private static Line[] boxBoundary(final double xMin, final double xMax, final double yMin, final double yMax, final double tolerance) { + if ((xMin >= xMax - tolerance) || (yMin >= yMax - tolerance)) { + // too thin box, build an empty polygons set + return null; + } final Vector2D minMin = new Vector2D(xMin, yMin); final Vector2D minMax = new Vector2D(xMin, yMax); final Vector2D maxMin = new Vector2D(xMax, yMin);
bugs-dot-jar/commons-math_extracted_diff/developer-patch_bugs-dot-jar_MATH-1117_f4c926ea.diff
bugs-dot-jar_data_MATH-1272_26e878ab
--- BugID: MATH-1272 Summary: FastMath.pow(double, long) enters an infinite loop with Long.MIN_VALUE Description: FastMath.pow(double, long) enters an infinite loop with Long.MIN_VALUE. It cannot be negated, so unsigned shift (>>>) is required instead of a signed one (>>). diff --git a/src/main/java/org/apache/commons/math4/util/FastMath.java b/src/main/java/org/apache/commons/math4/util/FastMath.java index a4a9a1b..46c8752 100644 --- a/src/main/java/org/apache/commons/math4/util/FastMath.java +++ b/src/main/java/org/apache/commons/math4/util/FastMath.java @@ -1711,7 +1711,7 @@ public class FastMath { } /** Computes this^e. - * @param e exponent (beware, here it MUST be > 0) + * @param e exponent (beware, here it MUST be > 0; the only exclusion is Long.MIN_VALUE) * @return d^e, split in high and low bits * @since 4.0 */ @@ -1723,7 +1723,7 @@ public class FastMath { // d^(2p) Split d2p = new Split(full, high, low); - for (long p = e; p != 0; p >>= 1) { + for (long p = e; p != 0; p >>>= 1) { if ((p & 0x1) != 0) { // accurate multiplication result = result * d^(2p) using Veltkamp TwoProduct algorithm
bugs-dot-jar/commons-math_extracted_diff/developer-patch_bugs-dot-jar_MATH-1272_26e878ab.diff
bugs-dot-jar_data_MATH-290_b01fcc31
--- BugID: MATH-290 Summary: NullPointerException in SimplexTableau.initialize Description: |- SimplexTableau throws a NullPointerException when no solution can be found instead of a NoFeasibleSolutionException Here is the code that causes the NullPointerException: LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 1, 5 }, 0 ); Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); constraints.add(new LinearConstraint(new double[] { 2, 0 }, Relationship.GEQ, -1.0)); RealPointValuePair solution = new SimplexSolver().optimize(f, constraints, GoalType.MINIMIZE, true); Note: Tested both with Apache Commons Math 2.0 release and SVN trunk diff --git a/src/main/java/org/apache/commons/math/optimization/linear/SimplexTableau.java b/src/main/java/org/apache/commons/math/optimization/linear/SimplexTableau.java index b387767..97d8061 100644 --- a/src/main/java/org/apache/commons/math/optimization/linear/SimplexTableau.java +++ b/src/main/java/org/apache/commons/math/optimization/linear/SimplexTableau.java @@ -69,7 +69,7 @@ class SimplexTableau implements Serializable { private final LinearObjectiveFunction f; /** Linear constraints. */ - private final Collection<LinearConstraint> constraints; + private final List<LinearConstraint> constraints; /** Whether to restrict the variables to non-negative values. */ private final boolean restrictToNonNegative; @@ -103,7 +103,7 @@ class SimplexTableau implements Serializable { final GoalType goalType, final boolean restrictToNonNegative, final double epsilon) { this.f = f; - this.constraints = constraints; + this.constraints = normalizeConstraints(constraints); this.restrictToNonNegative = restrictToNonNegative; this.epsilon = epsilon; this.numDecisionVariables = getNumVariables() + (restrictToNonNegative ? 0 : 1); @@ -123,7 +123,6 @@ class SimplexTableau implements Serializable { protected double[][] createTableau(final boolean maximize) { // create a matrix of the correct size - List<LinearConstraint> constraints = getNormalizedConstraints(); int width = numDecisionVariables + numSlackVariables + numArtificialVariables + getNumObjectiveFunctions() + 1; // + 1 is for RHS int height = constraints.size() + getNumObjectiveFunctions(); @@ -192,9 +191,10 @@ class SimplexTableau implements Serializable { /** * Get new versions of the constraints which have positive right hand sides. + * @param constraints original (not normalized) constraints * @return new versions of the constraints */ - public List<LinearConstraint> getNormalizedConstraints() { + public List<LinearConstraint> normalizeConstraints(Collection<LinearConstraint> constraints) { List<LinearConstraint> normalized = new ArrayList<LinearConstraint>(); for (LinearConstraint constraint : constraints) { normalized.add(normalize(constraint));
bugs-dot-jar/commons-math_extracted_diff/developer-patch_bugs-dot-jar_MATH-290_b01fcc31.diff
bugs-dot-jar_data_MATH-338_8dd22390
--- BugID: MATH-338 Summary: Wrong parameter for first step size guess for Embedded Runge Kutta methods Description: "In a space application using DOP853 i detected what seems to be a bad parameter in the call to the method initializeStep of class AdaptiveStepsizeIntegrator.\n\nHere, DormandPrince853Integrator is a subclass for EmbeddedRungeKuttaIntegrator which perform the call to initializeStep at the beginning of its method integrate(...)\n\nThe problem comes from the array \"scale\" that is used as a parameter in the call off initializeStep(..)\n\nFollowing the theory described by Hairer in his book \"Solving Ordinary Differential Equations 1 : Nonstiff Problems\", the scaling should be :\n\nsci = Atol i + |y0i| * Rtoli\n\nWhereas EmbeddedRungeKuttaIntegrator uses : sci = Atoli\n\nNote that the Gragg-Bulirsch-Stoer integrator uses the good implementation \"sci = Atol i + |y0i| * Rtoli \" when he performs the call to the same method initializeStep(..)\n\nIn the method initializeStep, the error leads to a wrong step size h used to perform an Euler step. Most of the time it is unvisible for the user.\nBut in my space application the Euler step with this wrong step size h (much bigger than it should be) makes an exception occur (my satellite hits the ground...)\n\n\nTo fix the bug, one should use the same algorithm as in the rescale method in GraggBulirschStoerIntegrator\nFor exemple :\n\n final double[] scale= new double[y0.length];;\n \n if (vecAbsoluteTolerance == null) {\n for (int i = 0; i < scale.length; ++i) {\n final double yi = Math.max(Math.abs(y0[i]), Math.abs(y0[i]));\n \ scale[i] = scalAbsoluteTolerance + scalRelativeTolerance * yi;\n \ }\n } else {\n for (int i = 0; i < scale.length; ++i) {\n final double yi = Math.max(Math.abs(y0[i]), Math.abs(y0[i]));\n \ scale[i] = vecAbsoluteTolerance[i] + vecRelativeTolerance[i] * yi;\n \ }\n }\n \n hNew = initializeStep(equations, forward, getOrder(), scale,\n stepStart, y, yDotK[0], yTmp, yDotK[1]);\n\n\n\nSorry for the length of this message, looking forward to hearing from you soon\n\nVincent Morand\n\n\n\n\n" diff --git a/src/main/java/org/apache/commons/math/ode/nonstiff/EmbeddedRungeKuttaIntegrator.java b/src/main/java/org/apache/commons/math/ode/nonstiff/EmbeddedRungeKuttaIntegrator.java index 70b2a2b..1bbad3e 100644 --- a/src/main/java/org/apache/commons/math/ode/nonstiff/EmbeddedRungeKuttaIntegrator.java +++ b/src/main/java/org/apache/commons/math/ode/nonstiff/EmbeddedRungeKuttaIntegrator.java @@ -17,8 +17,6 @@ package org.apache.commons.math.ode.nonstiff; -import java.util.Arrays; - import org.apache.commons.math.ode.DerivativeException; import org.apache.commons.math.ode.FirstOrderDifferentialEquations; import org.apache.commons.math.ode.IntegratorException; @@ -244,13 +242,16 @@ public abstract class EmbeddedRungeKuttaIntegrator } if (firstTime) { - final double[] scale; - if (vecAbsoluteTolerance != null) { - scale = vecAbsoluteTolerance; - } else { - scale = new double[y0.length]; - Arrays.fill(scale, scalAbsoluteTolerance); - } + final double[] scale = new double[y0.length]; + if (vecAbsoluteTolerance == null) { + for (int i = 0; i < scale.length; ++i) { + scale[i] = scalAbsoluteTolerance + scalRelativeTolerance * Math.abs(y[i]); + } + } else { + for (int i = 0; i < scale.length; ++i) { + scale[i] = vecAbsoluteTolerance[i] + vecRelativeTolerance[i] * Math.abs(y[i]); + } + } hNew = initializeStep(equations, forward, getOrder(), scale, stepStart, y, yDotK[0], yTmp, yDotK[1]); firstTime = false;
bugs-dot-jar/commons-math_extracted_diff/developer-patch_bugs-dot-jar_MATH-338_8dd22390.diff
bugs-dot-jar_data_MATH-320_c06cc933
--- BugID: MATH-320 Summary: NaN singular value from SVD Description: "The following jython code\nStart code\n\nfrom org.apache.commons.math.linear import *\n \nAlist = [[1.0, 2.0, 3.0],[2.0,3.0,4.0],[3.0,5.0,7.0]]\n \nA = Array2DRowRealMatrix(Alist)\n \ndecomp = SingularValueDecompositionImpl(A)\n \nprint decomp.getSingularValues()\n\nEnd code\n\nprints\narray('d', [11.218599757513008, 0.3781791648535976, nan])\nThe last singular value should be something very close to 0 since the matrix\nis rank deficient. \ When i use the result from getSolver() to solve a system, i end \nup with a bunch of NaNs in the solution. I assumed i would get back a least squares solution.\n\nDoes this SVD implementation require that the matrix be full rank? If so, then i would expect\nan exception to be thrown from the constructor or one of the methods.\n\n\n" diff --git a/src/main/java/org/apache/commons/math/linear/SingularValueDecomposition.java b/src/main/java/org/apache/commons/math/linear/SingularValueDecomposition.java index 5f91636..bbb2057 100644 --- a/src/main/java/org/apache/commons/math/linear/SingularValueDecomposition.java +++ b/src/main/java/org/apache/commons/math/linear/SingularValueDecomposition.java @@ -24,9 +24,17 @@ package org.apache.commons.math.linear; * Singular Value Decomposition of a real matrix. * <p>The Singular Value Decomposition of matrix A is a set of three matrices: * U, &Sigma; and V such that A = U &times; &Sigma; &times; V<sup>T</sup>. - * Let A be an m &times; n matrix, then U is an m &times; n orthogonal matrix, - * &Sigma; is a n &times; n diagonal matrix with positive diagonal elements, - * and V is an n &times; n orthogonal matrix.</p> + * Let A be a m &times; n matrix, then U is a m &times; p orthogonal matrix, + * &Sigma; is a p &times; p diagonal matrix with positive diagonal elements, + * V is a n &times; p orthogonal matrix (hence V<sup>T</sup> is a p &times; n + * orthogonal matrix). The size p depends on the chosen algorithm: + * <ul> + * <li>for full SVD, p is n,</li> + * <li>for compact SVD, p is the rank r of the matrix + * (i. e. the number of positive singular values),</li> + * <li>for truncated SVD p is min(r, t) where t is user-specified.</li> + * </ul> + * </p> * <p>This interface is similar to the class with similar name from the * <a href="http://math.nist.gov/javanumerics/jama/">JAMA</a> library, with the * following changes:</p> diff --git a/src/main/java/org/apache/commons/math/linear/SingularValueDecompositionImpl.java b/src/main/java/org/apache/commons/math/linear/SingularValueDecompositionImpl.java index 0da87ab..6003ed6 100644 --- a/src/main/java/org/apache/commons/math/linear/SingularValueDecompositionImpl.java +++ b/src/main/java/org/apache/commons/math/linear/SingularValueDecompositionImpl.java @@ -21,12 +21,24 @@ import org.apache.commons.math.MathRuntimeException; import org.apache.commons.math.util.MathUtils; /** - * Calculates the Singular Value Decomposition of a matrix. + * Calculates the compact or truncated Singular Value Decomposition of a matrix. * <p>The Singular Value Decomposition of matrix A is a set of three matrices: * U, &Sigma; and V such that A = U &times; &Sigma; &times; V<sup>T</sup>. - * Let A be an m &times; n matrix, then U is an m &times; n orthogonal matrix, - * &Sigma; is a n &times; n diagonal matrix with positive diagonal elements, - * and V is an n &times; n orthogonal matrix.</p> + * Let A be a m &times; n matrix, then U is a m &times; p orthogonal matrix, + * &Sigma; is a p &times; p diagonal matrix with positive diagonal elements, + * V is a n &times; p orthogonal matrix (hence V<sup>T</sup> is a p &times; n + * orthogonal matrix). The size p depends on the chosen algorithm: + * <ul> + * <li>for full SVD, p would be n, but this is not supported by this implementation,</li> + * <li>for compact SVD, p is the rank r of the matrix + * (i. e. the number of positive singular values),</li> + * <li>for truncated SVD p is min(r, t) where t is user-specified.</li> + * </ul> + * </p> + * <p> + * Note that since this class computes only the compact or truncated SVD and not + * the full SVD, the singular values computed are always positive. + * </p> * * @version $Revision$ $Date$ * @since 2.0 @@ -76,12 +88,24 @@ public class SingularValueDecompositionImpl implements SingularValueDecompositio private RealMatrix cachedVt; /** + * Calculates the compact Singular Value Decomposition of the given matrix. + * @param matrix The matrix to decompose. + * @exception InvalidMatrixException (wrapping a {@link + * org.apache.commons.math.ConvergenceException} if algorithm fails to converge + */ + public SingularValueDecompositionImpl(final RealMatrix matrix) + throws InvalidMatrixException { + this(matrix, Math.min(matrix.getRowDimension(), matrix.getColumnDimension())); + } + + /** * Calculates the Singular Value Decomposition of the given matrix. * @param matrix The matrix to decompose. + * @param max maximal number of singular values to compute * @exception InvalidMatrixException (wrapping a {@link * org.apache.commons.math.ConvergenceException} if algorithm fails to converge */ - public SingularValueDecompositionImpl(RealMatrix matrix) + public SingularValueDecompositionImpl(final RealMatrix matrix, final int max) throws InvalidMatrixException { m = matrix.getRowDimension(); @@ -113,10 +137,14 @@ public class SingularValueDecompositionImpl implements SingularValueDecompositio eigenDecomposition = new EigenDecompositionImpl(mainTridiagonal, secondaryTridiagonal, MathUtils.SAFE_MIN); - singularValues = eigenDecomposition.getRealEigenvalues(); - for (int i = 0; i < singularValues.length; ++i) { - final double si = singularValues[i]; - singularValues[i] = (si < 0) ? 0.0 : Math.sqrt(si); + final double[] eigenValues = eigenDecomposition.getRealEigenvalues(); + int p = Math.min(max, eigenValues.length); + while ((p > 0) && (eigenValues[p - 1] <= 0)) { + --p; + } + singularValues = new double[p]; + for (int i = 0; i < p; ++i) { + singularValues[i] = Math.sqrt(eigenValues[i]); } } @@ -127,37 +155,41 @@ public class SingularValueDecompositionImpl implements SingularValueDecompositio if (cachedU == null) { + final int p = singularValues.length; if (m >= n) { // the tridiagonal matrix is Bt.B, where B is upper bidiagonal - final double[][] eData = eigenDecomposition.getV().getData(); - final double[][] iData = new double[m][]; + final RealMatrix e = + eigenDecomposition.getV().getSubMatrix(0, p - 1, 0, p - 1); + final double[][] eData = e.getData(); + final double[][] wData = new double[m][p]; double[] ei1 = eData[0]; - iData[0] = ei1; - for (int i = 0; i < n - 1; ++i) { - // compute B.E.S^(-1) where E is the eigenvectors matrix - // we reuse the array from matrix E to store the result + for (int i = 0; i < p - 1; ++i) { + // compute W = B.E.S^(-1) where E is the eigenvectors matrix final double mi = mainBidiagonal[i]; final double si = secondaryBidiagonal[i]; final double[] ei0 = ei1; + final double[] wi = wData[i]; ei1 = eData[i + 1]; - iData[i + 1] = ei1; - for (int j = 0; j < n; ++j) { - ei0[j] = (mi * ei0[j] + si * ei1[j]) / singularValues[j]; + for (int j = 0; j < p; ++j) { + wi[j] = (mi * ei0[j] + si * ei1[j]) / singularValues[j]; } } // last row - final double lastMain = mainBidiagonal[n - 1]; - for (int j = 0; j < n; ++j) { - ei1[j] *= lastMain / singularValues[j]; + final double lastMain = mainBidiagonal[p - 1]; + final double[] wr1 = wData[p - 1]; + for (int j = 0; j < p; ++j) { + wr1[j] = ei1[j] * lastMain / singularValues[j]; } - for (int i = n; i < m; ++i) { - iData[i] = new double[n]; + for (int i = p; i < m; ++i) { + wData[i] = new double[p]; } cachedU = - transformer.getU().multiply(MatrixUtils.createRealMatrix(iData)); + transformer.getU().multiply(MatrixUtils.createRealMatrix(wData)); } else { // the tridiagonal matrix is B.Bt, where B is lower bidiagonal - cachedU = transformer.getU().multiply(eigenDecomposition.getV()); + final RealMatrix e = + eigenDecomposition.getV().getSubMatrix(0, m - 1, 0, p - 1); + cachedU = transformer.getU().multiply(e); } } @@ -205,37 +237,41 @@ public class SingularValueDecompositionImpl implements SingularValueDecompositio if (cachedV == null) { + final int p = singularValues.length; if (m >= n) { // the tridiagonal matrix is Bt.B, where B is upper bidiagonal - cachedV = transformer.getV().multiply(eigenDecomposition.getV()); + final RealMatrix e = + eigenDecomposition.getV().getSubMatrix(0, n - 1, 0, p - 1); + cachedV = transformer.getV().multiply(e); } else { // the tridiagonal matrix is B.Bt, where B is lower bidiagonal - final double[][] eData = eigenDecomposition.getV().getData(); - final double[][] iData = new double[n][]; + // compute W = Bt.E.S^(-1) where E is the eigenvectors matrix + final RealMatrix e = + eigenDecomposition.getV().getSubMatrix(0, p - 1, 0, p - 1); + final double[][] eData = e.getData(); + final double[][] wData = new double[n][p]; double[] ei1 = eData[0]; - iData[0] = ei1; - for (int i = 0; i < m - 1; ++i) { - // compute Bt.E.S^(-1) where E is the eigenvectors matrix - // we reuse the array from matrix E to store the result + for (int i = 0; i < p - 1; ++i) { final double mi = mainBidiagonal[i]; final double si = secondaryBidiagonal[i]; final double[] ei0 = ei1; + final double[] wi = wData[i]; ei1 = eData[i + 1]; - iData[i + 1] = ei1; - for (int j = 0; j < m; ++j) { - ei0[j] = (mi * ei0[j] + si * ei1[j]) / singularValues[j]; + for (int j = 0; j < p; ++j) { + wi[j] = (mi * ei0[j] + si * ei1[j]) / singularValues[j]; } } // last row - final double lastMain = mainBidiagonal[m - 1]; - for (int j = 0; j < m; ++j) { - ei1[j] *= lastMain / singularValues[j]; + final double lastMain = mainBidiagonal[p - 1]; + final double[] wr1 = wData[p - 1]; + for (int j = 0; j < p; ++j) { + wr1[j] = ei1[j] * lastMain / singularValues[j]; } - for (int i = m; i < n; ++i) { - iData[i] = new double[m]; + for (int i = p; i < n; ++i) { + wData[i] = new double[p]; } cachedV = - transformer.getV().multiply(MatrixUtils.createRealMatrix(iData)); + transformer.getV().multiply(MatrixUtils.createRealMatrix(wData)); } } @@ -262,8 +298,9 @@ public class SingularValueDecompositionImpl implements SingularValueDecompositio public RealMatrix getCovariance(final double minSingularValue) { // get the number of singular values to consider + final int p = singularValues.length; int dimension = 0; - while ((dimension < n) && (singularValues[dimension] >= minSingularValue)) { + while ((dimension < p) && (singularValues[dimension] >= minSingularValue)) { ++dimension; } @@ -273,14 +310,14 @@ public class SingularValueDecompositionImpl implements SingularValueDecompositio minSingularValue, singularValues[0]); } - final double[][] data = new double[dimension][n]; + final double[][] data = new double[dimension][p]; getVT().walkInOptimizedOrder(new DefaultRealMatrixPreservingVisitor() { /** {@inheritDoc} */ @Override public void visit(final int row, final int column, final double value) { data[row][column] = value / singularValues[row]; } - }, 0, dimension - 1, 0, n - 1); + }, 0, dimension - 1, 0, p - 1); RealMatrix jv = new Array2DRowRealMatrix(data, false); return jv.transpose().multiply(jv); @@ -317,20 +354,14 @@ public class SingularValueDecompositionImpl implements SingularValueDecompositio /** {@inheritDoc} */ public DecompositionSolver getSolver() { return new Solver(singularValues, getUT(), getV(), - getRank() == singularValues.length); + getRank() == Math.max(m, n)); } /** Specialized solver. */ private static class Solver implements DecompositionSolver { - /** Singular values. */ - private final double[] singularValues; - - /** U<sup>T</sup> matrix of the decomposition. */ - private final RealMatrix uT; - - /** V matrix of the decomposition. */ - private final RealMatrix v; + /** Pseudo-inverse of the initial matrix. */ + private final RealMatrix pseudoInverse; /** Singularity indicator. */ private boolean nonSingular; @@ -344,10 +375,16 @@ public class SingularValueDecompositionImpl implements SingularValueDecompositio */ private Solver(final double[] singularValues, final RealMatrix uT, final RealMatrix v, final boolean nonSingular) { - this.singularValues = singularValues; - this.uT = uT; - this.v = v; - this.nonSingular = nonSingular; + double[][] suT = uT.getData(); + for (int i = 0; i < singularValues.length; ++i) { + final double a = 1.0 / singularValues[i]; + final double[] suTi = suT[i]; + for (int j = 0; j < suTi.length; ++j) { + suTi[j] *= a; + } + } + pseudoInverse = v.multiply(new Array2DRowRealMatrix(suT, false)); + this.nonSingular = nonSingular; } /** Solve the linear equation A &times; X = B in least square sense. @@ -356,27 +393,10 @@ public class SingularValueDecompositionImpl implements SingularValueDecompositio * @param b right-hand side of the equation A &times; X = B * @return a vector X that minimizes the two norm of A &times; X - B * @exception IllegalArgumentException if matrices dimensions don't match - * @exception InvalidMatrixException if decomposed matrix is singular */ public double[] solve(final double[] b) - throws IllegalArgumentException, InvalidMatrixException { - - if (b.length != uT.getColumnDimension()) { - throw MathRuntimeException.createIllegalArgumentException( - "vector length mismatch: got {0} but expected {1}", - b.length, uT.getColumnDimension()); - } - - final double[] w = uT.operate(b); - for (int i = 0; i < singularValues.length; ++i) { - final double si = singularValues[i]; - if (si == 0) { - throw new SingularMatrixException(); - } - w[i] /= si; - } - return v.operate(w); - + throws IllegalArgumentException { + return pseudoInverse.operate(b); } /** Solve the linear equation A &times; X = B in least square sense. @@ -385,27 +405,10 @@ public class SingularValueDecompositionImpl implements SingularValueDecompositio * @param b right-hand side of the equation A &times; X = B * @return a vector X that minimizes the two norm of A &times; X - B * @exception IllegalArgumentException if matrices dimensions don't match - * @exception InvalidMatrixException if decomposed matrix is singular */ public RealVector solve(final RealVector b) - throws IllegalArgumentException, InvalidMatrixException { - - if (b.getDimension() != uT.getColumnDimension()) { - throw MathRuntimeException.createIllegalArgumentException( - "vector length mismatch: got {0} but expected {1}", - b.getDimension(), uT.getColumnDimension()); - } - - final RealVector w = uT.operate(b); - for (int i = 0; i < singularValues.length; ++i) { - final double si = singularValues[i]; - if (si == 0) { - throw new SingularMatrixException(); - } - w.setEntry(i, w.getEntry(i) / si); - } - return v.operate(w); - + throws IllegalArgumentException { + return pseudoInverse.operate(b); } /** Solve the linear equation A &times; X = B in least square sense. @@ -414,31 +417,10 @@ public class SingularValueDecompositionImpl implements SingularValueDecompositio * @param b right-hand side of the equation A &times; X = B * @return a matrix X that minimizes the two norm of A &times; X - B * @exception IllegalArgumentException if matrices dimensions don't match - * @exception InvalidMatrixException if decomposed matrix is singular */ public RealMatrix solve(final RealMatrix b) - throws IllegalArgumentException, InvalidMatrixException { - - if (b.getRowDimension() != singularValues.length) { - throw MathRuntimeException.createIllegalArgumentException( - "dimensions mismatch: got {0}x{1} but expected {2}x{3}", - b.getRowDimension(), b.getColumnDimension(), - singularValues.length, "n"); - } - - final RealMatrix w = uT.multiply(b); - for (int i = 0; i < singularValues.length; ++i) { - final double si = singularValues[i]; - if (si == 0) { - throw new SingularMatrixException(); - } - final double inv = 1.0 / si; - for (int j = 0; j < b.getColumnDimension(); ++j) { - w.multiplyEntry(i, j, inv); - } - } - return v.multiply(w); - + throws IllegalArgumentException { + return pseudoInverse.multiply(b); } /** @@ -451,17 +433,9 @@ public class SingularValueDecompositionImpl implements SingularValueDecompositio /** Get the pseudo-inverse of the decomposed matrix. * @return inverse matrix - * @throws InvalidMatrixException if decomposed matrix is singular */ - public RealMatrix getInverse() - throws InvalidMatrixException { - - if (!isNonSingular()) { - throw new SingularMatrixException(); - } - - return solve(MatrixUtils.createRealIdentityMatrix(singularValues.length)); - + public RealMatrix getInverse() { + return pseudoInverse; } }
bugs-dot-jar/commons-math_extracted_diff/developer-patch_bugs-dot-jar_MATH-320_c06cc933.diff
bugs-dot-jar_data_MATH-927_185e3033
--- BugID: MATH-927 Summary: GammaDistribution cloning broken Description: |- Serializing a GammaDistribution and deserializing it, does not result in a cloned distribution that produces the same samples. Cause: GammaDistribution inherits from AbstractRealDistribution, which implements Serializable. AbstractRealDistribution has random, in which we have a Well19937c instance, which inherits from AbstractWell. AbstractWell implements Serializable. AbstractWell inherits from BitsStreamGenerator, which is not Serializable, but does have a private field 'nextGaussian'. Solution: Make BitStreamGenerator implement Serializable as well. This probably affects other distributions as well. diff --git a/src/main/java/org/apache/commons/math3/random/BitsStreamGenerator.java b/src/main/java/org/apache/commons/math3/random/BitsStreamGenerator.java index a621d7b..fab295b 100644 --- a/src/main/java/org/apache/commons/math3/random/BitsStreamGenerator.java +++ b/src/main/java/org/apache/commons/math3/random/BitsStreamGenerator.java @@ -16,21 +16,26 @@ */ package org.apache.commons.math3.random; +import java.io.Serializable; + import org.apache.commons.math3.exception.NotStrictlyPositiveException; import org.apache.commons.math3.util.FastMath; /** Base class for random number generators that generates bits streams. - + * * @version $Id$ * @since 2.0 - */ -public abstract class BitsStreamGenerator implements RandomGenerator { - +public abstract class BitsStreamGenerator + implements RandomGenerator, + Serializable { + /** Serializable version identifier */ + private static final long serialVersionUID = 20130104L; /** Next gaussian. */ private double nextGaussian; - /** Creates a new random number generator. + /** + * Creates a new random number generator. */ public BitsStreamGenerator() { nextGaussian = Double.NaN;
bugs-dot-jar/commons-math_extracted_diff/developer-patch_bugs-dot-jar_MATH-927_185e3033.diff
bugs-dot-jar_data_MATH-1106_e2dc384d
--- BugID: MATH-1106 Summary: LevenburgMaquardt switched evaluation and iterations Description: diff --git a/src/main/java/org/apache/commons/math3/fitting/leastsquares/LevenbergMarquardtOptimizer.java b/src/main/java/org/apache/commons/math3/fitting/leastsquares/LevenbergMarquardtOptimizer.java index 5f0527c..864faae 100644 --- a/src/main/java/org/apache/commons/math3/fitting/leastsquares/LevenbergMarquardtOptimizer.java +++ b/src/main/java/org/apache/commons/math3/fitting/leastsquares/LevenbergMarquardtOptimizer.java @@ -506,7 +506,7 @@ public class LevenbergMarquardtOptimizer implements LeastSquaresOptimizer { // tests for convergence. if (checker != null && checker.converged(iterationCounter.getCount(), previous, current)) { - return new OptimumImpl(current, iterationCounter.getCount(), evaluationCounter.getCount()); + return new OptimumImpl(current, evaluationCounter.getCount(), iterationCounter.getCount()); } } else { // failed iteration, reset the previous values @@ -527,7 +527,7 @@ public class LevenbergMarquardtOptimizer implements LeastSquaresOptimizer { preRed <= costRelativeTolerance && ratio <= 2.0) || delta <= parRelativeTolerance * xNorm) { - return new OptimumImpl(current, iterationCounter.getCount(), evaluationCounter.getCount()); + return new OptimumImpl(current, evaluationCounter.getCount(), iterationCounter.getCount()); } // tests for termination and stringent tolerances
bugs-dot-jar/commons-math_extracted_diff/developer-patch_bugs-dot-jar_MATH-1106_e2dc384d.diff
bugs-dot-jar_data_MATH-844_7994d3ee
--- BugID: MATH-844 Summary: '"HarmonicFitter.ParameterGuesser" sometimes fails to return sensible values' Description: 'The inner class "ParameterGuesser" in "HarmonicFitter" (package "o.a.c.m.optimization.fitting") fails to compute a usable guess for the "amplitude" parameter. ' diff --git a/src/main/java/org/apache/commons/math3/exception/util/LocalizedFormats.java b/src/main/java/org/apache/commons/math3/exception/util/LocalizedFormats.java index 1ca5635..04edd0b 100644 --- a/src/main/java/org/apache/commons/math3/exception/util/LocalizedFormats.java +++ b/src/main/java/org/apache/commons/math3/exception/util/LocalizedFormats.java @@ -344,7 +344,7 @@ public enum LocalizedFormats implements Localizable { WRONG_BLOCK_LENGTH("wrong array shape (block length = {0}, expected {1})"), WRONG_NUMBER_OF_POINTS("{0} points are required, got only {1}"), NUMBER_OF_POINTS("number of points ({0})"), /* keep */ - ZERO_DENOMINATOR("denominator must be different from 0"), + ZERO_DENOMINATOR("denominator must be different from 0"), /* keep */ ZERO_DENOMINATOR_IN_FRACTION("zero denominator in fraction {0}/{1}"), ZERO_FRACTION_TO_DIVIDE_BY("the fraction to divide by must not be zero: {0}/{1}"), ZERO_NORM("zero norm"), diff --git a/src/main/java/org/apache/commons/math3/optimization/fitting/HarmonicFitter.java b/src/main/java/org/apache/commons/math3/optimization/fitting/HarmonicFitter.java index ebb36d3..c7af9ae 100644 --- a/src/main/java/org/apache/commons/math3/optimization/fitting/HarmonicFitter.java +++ b/src/main/java/org/apache/commons/math3/optimization/fitting/HarmonicFitter.java @@ -21,6 +21,7 @@ import org.apache.commons.math3.optimization.DifferentiableMultivariateVectorOpt import org.apache.commons.math3.analysis.function.HarmonicOscillator; import org.apache.commons.math3.exception.ZeroException; import org.apache.commons.math3.exception.NumberIsTooSmallException; +import org.apache.commons.math3.exception.MathIllegalStateException; import org.apache.commons.math3.exception.util.LocalizedFormats; import org.apache.commons.math3.util.FastMath; @@ -250,6 +251,8 @@ public class HarmonicFitter extends CurveFitter<HarmonicOscillator.Parametric> { * has been called previously. * * @throws ZeroException if the abscissa range is zero. + * @throws MathIllegalStateException when the guessing procedure cannot + * produce sensible results. */ private void guessAOmega() { // initialize the sums for the linear model between the two integrals @@ -317,6 +320,12 @@ public class HarmonicFitter extends CurveFitter<HarmonicOscillator.Parametric> { } a = 0.5 * (yMax - yMin); } else { + if (c2 == 0) { + // In some ill-conditioned cases (cf. MATH-844), the guesser + // procedure cannot produce sensible results. + throw new MathIllegalStateException(LocalizedFormats.ZERO_DENOMINATOR); + } + a = FastMath.sqrt(c1 / c2); omega = FastMath.sqrt(c2 / c3); }
bugs-dot-jar/commons-math_extracted_diff/developer-patch_bugs-dot-jar_MATH-844_7994d3ee.diff
bugs-dot-jar_data_MATH-864_abe53a53
--- BugID: MATH-864 Summary: CMAESOptimizer does not enforce bounds Description: The CMAESOptimizer can exceed the bounds passed to optimize. Looking at the generationLoop in doOptimize(), it does a bounds check by calling isFeasible() but if checkFeasableCount is zero (the default) then isFeasible() is never even called. Also, even with non-zero checkFeasableCount it may give up before finding an in-bounds offspring and go forward with an out-of-bounds offspring. This is against svn revision 1387637. I can provide an example program where the optimizer ends up with a fit outside the prescribed bounds if that would help. diff --git a/src/main/java/org/apache/commons/math3/optimization/direct/CMAESOptimizer.java b/src/main/java/org/apache/commons/math3/optimization/direct/CMAESOptimizer.java index d01cd15..b54cb37 100644 --- a/src/main/java/org/apache/commons/math3/optimization/direct/CMAESOptimizer.java +++ b/src/main/java/org/apache/commons/math3/optimization/direct/CMAESOptimizer.java @@ -24,9 +24,11 @@ import java.util.List; import org.apache.commons.math3.analysis.MultivariateFunction; import org.apache.commons.math3.exception.DimensionMismatchException; import org.apache.commons.math3.exception.MathUnsupportedOperationException; +import org.apache.commons.math3.exception.MathIllegalStateException; import org.apache.commons.math3.exception.NotPositiveException; import org.apache.commons.math3.exception.OutOfRangeException; import org.apache.commons.math3.exception.TooManyEvaluationsException; +import org.apache.commons.math3.exception.util.LocalizedFormats; import org.apache.commons.math3.linear.Array2DRowRealMatrix; import org.apache.commons.math3.linear.EigenDecomposition; import org.apache.commons.math3.linear.MatrixUtils; @@ -414,7 +416,7 @@ public class CMAESOptimizer bestValue = bestFitness; lastResult = optimum; optimum = new PointValuePair( - fitfun.decode(bestArx.getColumn(0)), + fitfun.repairAndDecode(bestArx.getColumn(0)), isMinimize ? bestFitness : -bestFitness); if (getConvergenceChecker() != null && lastResult != null) { if (getConvergenceChecker().converged(iterations, optimum, lastResult)) { @@ -913,6 +915,16 @@ public class CMAESOptimizer /** * @param x Normalized objective variables. + * @return the original objective variables, possibly repaired. + */ + public double[] repairAndDecode(final double[] x) { + return boundaries != null && isRepairMode ? + decode(repair(x)) : + decode(x); + } + + /** + * @param x Normalized objective variables. * @return the original objective variables. */ public double[] decode(final double[] x) {
bugs-dot-jar/commons-math_extracted_diff/developer-patch_bugs-dot-jar_MATH-864_abe53a53.diff
bugs-dot-jar_data_MATH-1256_41f29780
--- BugID: MATH-1256 Summary: Interval class upper and lower check Description: |+ In class Interval, which is in the package org.apache.commons.math4.geometry.euclidean.oned it is possible to pass the value for variable upper less than the value of variable lower, which is logically incorrect and also causes the method getSize() to return negative value. For example: @Test public void test1() throws Throwable { Interval interval0 = new Interval(0.0, (-1.0)); double double0 = interval0.getSize(); assertEquals((-1.0), double0, 0.01D); } diff --git a/src/main/java/org/apache/commons/math4/geometry/euclidean/oned/Interval.java b/src/main/java/org/apache/commons/math4/geometry/euclidean/oned/Interval.java index 9785776..87dbba1 100644 --- a/src/main/java/org/apache/commons/math4/geometry/euclidean/oned/Interval.java +++ b/src/main/java/org/apache/commons/math4/geometry/euclidean/oned/Interval.java @@ -17,6 +17,8 @@ package org.apache.commons.math4.geometry.euclidean.oned; import org.apache.commons.math4.geometry.partitioning.Region.Location; +import org.apache.commons.math4.exception.NumberIsTooSmallException; +import org.apache.commons.math4.exception.util.LocalizedFormats; /** This class represents a 1D interval. @@ -36,6 +38,10 @@ public class Interval { * @param upper upper bound of the interval */ public Interval(final double lower, final double upper) { + if (upper < lower) { + throw new NumberIsTooSmallException(LocalizedFormats.ENDPOINTS_NOT_AN_INTERVAL, + upper, lower, true); + } this.lower = lower; this.upper = upper; }
bugs-dot-jar/commons-math_extracted_diff/developer-patch_bugs-dot-jar_MATH-1256_41f29780.diff
bugs-dot-jar_data_MATH-1261_4c4b3e2e
--- BugID: MATH-1261 Summary: Overflow checks in Fraction multiply(int) / divide(int) Description: |- The member methods multiply(int) / divide(int) in the class org.apache.commons.math3.fraction.Fraction do not have overflow checks. {code:java} return new Fraction(numerator * i, denominator); {code} should be {code:java} return new Fraction(ArithmeticUtils.mulAndCheck(numerator, i), denominator); {code} or, considering the case gcd(i, denominator) > 1, {code:java} return multiply(new Fraction(i)); {code} diff --git a/src/main/java/org/apache/commons/math4/fraction/Fraction.java b/src/main/java/org/apache/commons/math4/fraction/Fraction.java index 0713b85..39eba8d 100644 --- a/src/main/java/org/apache/commons/math4/fraction/Fraction.java +++ b/src/main/java/org/apache/commons/math4/fraction/Fraction.java @@ -566,7 +566,7 @@ public class Fraction */ @Override public Fraction multiply(final int i) { - return new Fraction(numerator * i, denominator); + return multiply(new Fraction(i)); } /** @@ -597,7 +597,7 @@ public class Fraction * @return this * i */ public Fraction divide(final int i) { - return new Fraction(numerator, denominator * i); + return divide(new Fraction(i)); } /**
bugs-dot-jar/commons-math_extracted_diff/developer-patch_bugs-dot-jar_MATH-1261_4c4b3e2e.diff
bugs-dot-jar_data_MATH-1096_faf99727
--- BugID: MATH-1096 Summary: implementation of smallest enclosing ball algorithm sometime fails Description: |- The algorithm for finding the smallest ball is designed in such a way the radius should be strictly increasing at each iteration. In some cases, it is not true and one iteration has a smaller ball. In most cases, there is no consequence, there is just one or two more iterations. However, in rare cases discovered while testing 3D, this generates an infinite loop. Some very short offending cases have already been identified and added to the test suite. These cases are currently deactivated in the main repository while I am already working on them. The test cases are * WelzlEncloser2DTest.testReducingBall * WelzlEncloser2DTest.testLargeSamples * WelzlEncloser3DTest.testInfiniteLoop * WelzlEncloser3DTest.testLargeSamples diff --git a/src/main/java/org/apache/commons/math3/geometry/enclosing/Encloser.java b/src/main/java/org/apache/commons/math3/geometry/enclosing/Encloser.java index 4e92704..a2e1684 100644 --- a/src/main/java/org/apache/commons/math3/geometry/enclosing/Encloser.java +++ b/src/main/java/org/apache/commons/math3/geometry/enclosing/Encloser.java @@ -16,8 +16,6 @@ */ package org.apache.commons.math3.geometry.enclosing; -import java.util.List; - import org.apache.commons.math3.geometry.Point; import org.apache.commons.math3.geometry.Space; @@ -34,6 +32,6 @@ public interface Encloser<S extends Space, P extends Point<S>> { * @param points points to enclose * @return enclosing ball */ - EnclosingBall<S, P> enclose(List<P> points); + EnclosingBall<S, P> enclose(Iterable<P> points); } diff --git a/src/main/java/org/apache/commons/math3/geometry/enclosing/WelzlEncloser.java b/src/main/java/org/apache/commons/math3/geometry/enclosing/WelzlEncloser.java index ce5c58c..b8ea5d6 100644 --- a/src/main/java/org/apache/commons/math3/geometry/enclosing/WelzlEncloser.java +++ b/src/main/java/org/apache/commons/math3/geometry/enclosing/WelzlEncloser.java @@ -65,9 +65,9 @@ public class WelzlEncloser<S extends Space, P extends Point<S>> implements Enclo } /** {@inheritDoc} */ - public EnclosingBall<S, P> enclose(final List<P> points) { + public EnclosingBall<S, P> enclose(final Iterable<P> points) { - if (points == null || points.isEmpty()) { + if (points == null || !points.iterator().hasNext()) { // return an empty ball return generator.ballOnSupport(new ArrayList<P>()); } @@ -81,14 +81,14 @@ public class WelzlEncloser<S extends Space, P extends Point<S>> implements Enclo * @param points points to be enclosed * @return enclosing ball */ - private EnclosingBall<S, P> pivotingBall(final List<P> points) { + private EnclosingBall<S, P> pivotingBall(final Iterable<P> points) { List<P> extreme = new ArrayList<P>(max); List<P> support = new ArrayList<P>(max); // start with only first point selected as a candidate support - extreme.add(points.get(0)); - EnclosingBall<S, P> ball = moveToFrontBall(extreme, support); + extreme.add(points.iterator().next()); + EnclosingBall<S, P> ball = moveToFrontBall(extreme, extreme.size(), support); while (true) { @@ -103,7 +103,7 @@ public class WelzlEncloser<S extends Space, P extends Point<S>> implements Enclo support.clear(); support.add(farthest); EnclosingBall<S, P> savedBall = ball; - ball = moveToFrontBall(extreme, support); + ball = moveToFrontBall(extreme, extreme.size(), support); if (ball.getRadius() < savedBall.getRadius()) { // TODO: fix this, it should never happen but it does! throw new MathInternalError(); @@ -122,28 +122,31 @@ public class WelzlEncloser<S extends Space, P extends Point<S>> implements Enclo /** Compute enclosing ball using Welzl's move to front heuristic. * @param extreme subset of extreme points + * @param nbExtreme number of extreme points to consider * @param support points that must belong to the ball support * @return enclosing ball, for the extreme subset only */ - private EnclosingBall<S, P> moveToFrontBall(final List<P> extreme, final List<P> support) { + private EnclosingBall<S, P> moveToFrontBall(final List<P> extreme, final int nbExtreme, + final List<P> support) { // create a new ball on the prescribed support EnclosingBall<S, P> ball = generator.ballOnSupport(support); if (ball.getSupportSize() < max) { - for (int i = 0; i < extreme.size(); ++i) { + for (int i = 0; i < nbExtreme; ++i) { final P pi = extreme.get(i); if (!ball.contains(pi, tolerance)) { // we have found an outside point, // enlarge the ball by adding it to the support support.add(pi); - ball = moveToFrontBall(extreme.subList(i + 1, extreme.size()), support); + ball = moveToFrontBall(extreme, i, support); + support.remove(support.size() - 1); // it was an interesting point, move it to the front // according to Welzl's heuristic - for (int j = i; j > 1; --j) { + for (int j = i; j > 0; --j) { extreme.set(j, extreme.get(j - 1)); } extreme.set(0, pi); @@ -162,7 +165,7 @@ public class WelzlEncloser<S extends Space, P extends Point<S>> implements Enclo * @param ball current ball * @return farthest point */ - public P selectFarthest(final List<P> points, final EnclosingBall<S, P> ball) { + public P selectFarthest(final Iterable<P> points, final EnclosingBall<S, P> ball) { final P center = ball.getCenter(); P farthest = null;
bugs-dot-jar/commons-math_extracted_diff/developer-patch_bugs-dot-jar_MATH-1096_faf99727.diff
bugs-dot-jar_data_MATH-899_ce126bdb
--- BugID: MATH-899 Summary: A random crash of MersenneTwister random generator Description: "There is a very small probability that MersenneTwister generator gives a following error: \njava.lang.ArrayIndexOutOfBoundsException: 624\nin MersenneTwister.java line 253\nThe error is completely random and its probability is about 1e-8.\n\nUPD: The problem most probably arises only in multy-thread mode." diff --git a/src/main/java/org/apache/commons/math3/random/SynchronizedRandomGenerator.java b/src/main/java/org/apache/commons/math3/random/SynchronizedRandomGenerator.java index 54c006d..d28f74b 100644 --- a/src/main/java/org/apache/commons/math3/random/SynchronizedRandomGenerator.java +++ b/src/main/java/org/apache/commons/math3/random/SynchronizedRandomGenerator.java @@ -82,7 +82,7 @@ public class SynchronizedRandomGenerator implements RandomGenerator { * {@inheritDoc} */ public synchronized int nextInt(int n) { - return wrapped.nextInt(); + return wrapped.nextInt(n); } /**
bugs-dot-jar/commons-math_extracted_diff/developer-patch_bugs-dot-jar_MATH-899_ce126bdb.diff
bugs-dot-jar_data_MATH-859_66dece12
--- BugID: MATH-859 Summary: Fix and then deprecate isSupportXxxInclusive in RealDistribution interface Description: | The conclusion from [1] was never implemented. We should deprecate these properties from the RealDistribution interface, but since removal will have to wait until 4.0, we should agree on a precise definition and fix the code to match it in the mean time. The definition that I propose is that isSupportXxxInclusive means that when the density function is applied to the upper or lower bound of support returned by getSupportXxxBound, a finite (i.e. not infinite), not NaN value is returned. [1] http://markmail.org/message/dxuxh7eybl7xejde diff --git a/src/main/java/org/apache/commons/math3/distribution/FDistribution.java b/src/main/java/org/apache/commons/math3/distribution/FDistribution.java index 8b0993c..e301e2e 100644 --- a/src/main/java/org/apache/commons/math3/distribution/FDistribution.java +++ b/src/main/java/org/apache/commons/math3/distribution/FDistribution.java @@ -272,7 +272,7 @@ public class FDistribution extends AbstractRealDistribution { /** {@inheritDoc} */ public boolean isSupportLowerBoundInclusive() { - return true; + return false; } /** {@inheritDoc} */ diff --git a/src/main/java/org/apache/commons/math3/distribution/RealDistribution.java b/src/main/java/org/apache/commons/math3/distribution/RealDistribution.java index f09c5ac..90dc8fd 100644 --- a/src/main/java/org/apache/commons/math3/distribution/RealDistribution.java +++ b/src/main/java/org/apache/commons/math3/distribution/RealDistribution.java @@ -137,18 +137,26 @@ public interface RealDistribution { double getSupportUpperBound(); /** - * Use this method to get information about whether the lower bound - * of the support is inclusive or not. - * - * @return whether the lower bound of the support is inclusive or not + * Whether or not the lower bound of support is in the domain of the density + * function. Returns true iff {@code getSupporLowerBound()} is finite and + * {@code density(getSupportLowerBound())} returns a non-NaN, non-infinite + * value. + * + * @return true if the lower bound of support is finite and the density + * function returns a non-NaN, non-infinite value there + * @deprecated to be removed in 4.0 */ boolean isSupportLowerBoundInclusive(); /** - * Use this method to get information about whether the upper bound - * of the support is inclusive or not. - * - * @return whether the upper bound of the support is inclusive or not + * Whether or not the upper bound of support is in the domain of the density + * function. Returns true iff {@code getSupportUpperBound()} is finite and + * {@code density(getSupportUpperBound())} returns a non-NaN, non-infinite + * value. + * + * @return true if the upper bound of support is finite and the density + * function returns a non-NaN, non-infinite value there + * @deprecated to be removed in 4.0 */ boolean isSupportUpperBoundInclusive(); diff --git a/src/main/java/org/apache/commons/math3/distribution/UniformRealDistribution.java b/src/main/java/org/apache/commons/math3/distribution/UniformRealDistribution.java index 5d32f6e..0d279de 100644 --- a/src/main/java/org/apache/commons/math3/distribution/UniformRealDistribution.java +++ b/src/main/java/org/apache/commons/math3/distribution/UniformRealDistribution.java @@ -181,7 +181,7 @@ public class UniformRealDistribution extends AbstractRealDistribution { /** {@inheritDoc} */ public boolean isSupportUpperBoundInclusive() { - return false; + return true; } /**
bugs-dot-jar/commons-math_extracted_diff/developer-patch_bugs-dot-jar_MATH-859_66dece12.diff
bugs-dot-jar_data_MATH-942_0d057fc6
--- BugID: MATH-942 Summary: DiscreteDistribution.sample(int) may throw an exception if first element of singletons of sub-class type Description: |- Creating an array with {{Array.newInstance(singletons.get(0).getClass(), sampleSize)}} in DiscreteDistribution.sample(int) is risky. An exception will be thrown if: * {{singleons.get(0)}} is of type T1, an sub-class of T, and * {{DiscreteDistribution.sample()}} returns an object which is of type T, but not of type T1. To reproduce: {code} List<Pair<Object,Double>> list = new ArrayList<Pair<Object, Double>>(); list.add(new Pair<Object, Double>(new Object() {}, new Double(0))); list.add(new Pair<Object, Double>(new Object() {}, new Double(1))); new DiscreteDistribution<Object>(list).sample(1); {code} Attaching a patch. diff --git a/src/main/java/org/apache/commons/math3/distribution/DiscreteDistribution.java b/src/main/java/org/apache/commons/math3/distribution/DiscreteDistribution.java index 8c08dbe..879eb2a 100644 --- a/src/main/java/org/apache/commons/math3/distribution/DiscreteDistribution.java +++ b/src/main/java/org/apache/commons/math3/distribution/DiscreteDistribution.java @@ -16,9 +16,9 @@ */ package org.apache.commons.math3.distribution; -import java.lang.reflect.Array; import java.util.ArrayList; import java.util.List; + import org.apache.commons.math3.exception.MathArithmeticException; import org.apache.commons.math3.exception.MathIllegalArgumentException; import org.apache.commons.math3.exception.NotPositiveException; @@ -178,13 +178,13 @@ public class DiscreteDistribution<T> { * @throws NotStrictlyPositiveException if {@code sampleSize} is not * positive. */ - public T[] sample(int sampleSize) throws NotStrictlyPositiveException { + public Object[] sample(int sampleSize) throws NotStrictlyPositiveException { if (sampleSize <= 0) { throw new NotStrictlyPositiveException(LocalizedFormats.NUMBER_OF_SAMPLES, sampleSize); } - @SuppressWarnings("unchecked") - final T[]out = (T[]) Array.newInstance(singletons.get(0).getClass(), sampleSize); + + final Object[] out = new Object[sampleSize]; for (int i = 0; i < sampleSize; i++) { out[i] = sample();
bugs-dot-jar/commons-math_extracted_diff/developer-patch_bugs-dot-jar_MATH-942_0d057fc6.diff
bugs-dot-jar_data_MATH-377_c640932d
--- BugID: MATH-377 Summary: weight versus sigma in AbstractLeastSquares Description: |- In AbstractLeastSquares, residualsWeights contains the WEIGHTS assigned to each observation. In the method getRMS(), these weights are multiplicative as they should. unlike in getChiSquare() where it appears at the denominator! If the weight is really the weight of the observation, it should multiply the square of the residual even in the computation of the chi2. Once corrected, getRMS() can even reduce public double getRMS() {return Math.sqrt(getChiSquare()/rows);} diff --git a/src/main/java/org/apache/commons/math/linear/EigenDecompositionImpl.java b/src/main/java/org/apache/commons/math/linear/EigenDecompositionImpl.java index d1531a8..468dca7 100644 --- a/src/main/java/org/apache/commons/math/linear/EigenDecompositionImpl.java +++ b/src/main/java/org/apache/commons/math/linear/EigenDecompositionImpl.java @@ -561,7 +561,7 @@ public class EigenDecompositionImpl implements EigenDecomposition { z[ia][i] = c * z[ia][i] - s * p; } } - if (e[i + 1] == 0.0 && i >= j) + if (t == 0.0 && i >= j) continue; realEigenvalues[j] -= u; e[j] = q; diff --git a/src/main/java/org/apache/commons/math/linear/SingularValueDecompositionImpl.java b/src/main/java/org/apache/commons/math/linear/SingularValueDecompositionImpl.java index 3abf3f0..597f6c4 100644 --- a/src/main/java/org/apache/commons/math/linear/SingularValueDecompositionImpl.java +++ b/src/main/java/org/apache/commons/math/linear/SingularValueDecompositionImpl.java @@ -108,7 +108,7 @@ public class SingularValueDecompositionImpl implements for (int k = 0; k < n; k++) { matAAT[i][j] += localcopy[i][k] * localcopy[j][k]; } - matAAT[j][i]=matAAT[i][j]; + matAAT[j][i]=matAAT[i][j]; } } int p; @@ -119,7 +119,6 @@ public class SingularValueDecompositionImpl implements new Array2DRowRealMatrix(matATA),1.0); singularValues = eigenDecomposition.getRealEigenvalues(); cachedV = eigenDecomposition.getV(); - // compute eigen decomposition of A*A^T eigenDecomposition = new EigenDecompositionImpl( new Array2DRowRealMatrix(matAAT),1.0); @@ -141,7 +140,7 @@ public class SingularValueDecompositionImpl implements singularValues[i] = Math.sqrt(Math.abs(singularValues[i])); } // Up to this point, U and V are computed independently of each other. - // There still an sign indetermination of each column of, say, U. + // There still a sign indetermination of each column of, say, U. // The sign is set such that A.V_i=sigma_i.U_i (i<=p) // The right sign corresponds to a positive dot product of A.V_i and U_i for (int i = 0; i < p; i++) { diff --git a/src/main/java/org/apache/commons/math/optimization/general/AbstractLeastSquaresOptimizer.java b/src/main/java/org/apache/commons/math/optimization/general/AbstractLeastSquaresOptimizer.java index 10f7762..5a60da8 100644 --- a/src/main/java/org/apache/commons/math/optimization/general/AbstractLeastSquaresOptimizer.java +++ b/src/main/java/org/apache/commons/math/optimization/general/AbstractLeastSquaresOptimizer.java @@ -237,23 +237,20 @@ public abstract class AbstractLeastSquaresOptimizer implements DifferentiableMul * @return RMS value */ public double getRMS() { - double criterion = 0; - for (int i = 0; i < rows; ++i) { - final double residual = residuals[i]; - criterion += residualsWeights[i] * residual * residual; - } - return Math.sqrt(criterion / rows); + return Math.sqrt(getChiSquare() / rows); } /** - * Get the Chi-Square value. + * Get a Chi-Square-like value assuming the N residuals follow N + * distinct normal distributions centered on 0 and whose variances are + * the reciprocal of the weights. * @return chi-square value */ public double getChiSquare() { double chiSquare = 0; for (int i = 0; i < rows; ++i) { final double residual = residuals[i]; - chiSquare += residual * residual / residualsWeights[i]; + chiSquare += residual * residual * residualsWeights[i]; } return chiSquare; }
bugs-dot-jar/commons-math_extracted_diff/developer-patch_bugs-dot-jar_MATH-377_c640932d.diff
bugs-dot-jar_data_MATH-1129_d4f978dd
--- BugID: MATH-1129 Summary: Percentile Computation errs Description: "In the following test, the 75th percentile is _smaller_ than the 25th percentile, leaving me with a negative interquartile range.\n\n{code:title=Bar.java|borderStyle=solid}\n@Test public void negativePercentiles(){\n\n double[] data = new double[]{\n -0.012086732064244697, \n -0.24975668704012527, \n 0.5706168483164684, \n \ -0.322111769955327, \n 0.24166759508327315, \n Double.NaN, \n 0.16698443218942854, \n -0.10427763937565114, \n \ -0.15595963093172435, \n -0.028075857595882995, \n \ -0.24137994506058857, \n 0.47543170476574426, \n \ -0.07495595384947631, \n 0.37445697625436497, \n \ -0.09944199541668033\n };\n DescriptiveStatistics descriptiveStatistics = new DescriptiveStatistics(data);\n\n double threeQuarters = descriptiveStatistics.getPercentile(75);\n double oneQuarter = descriptiveStatistics.getPercentile(25);\n\n \ double IQR = threeQuarters - oneQuarter;\n \n System.out.println(String.format(\"25th percentile %s 75th percentile %s\", oneQuarter, threeQuarters ));\n \n assert IQR >= 0;\n \n }\n{code}" diff --git a/src/main/java/org/apache/commons/math3/stat/descriptive/rank/Percentile.java b/src/main/java/org/apache/commons/math3/stat/descriptive/rank/Percentile.java index db447aa..15631cf 100644 --- a/src/main/java/org/apache/commons/math3/stat/descriptive/rank/Percentile.java +++ b/src/main/java/org/apache/commons/math3/stat/descriptive/rank/Percentile.java @@ -440,12 +440,18 @@ public class Percentile extends AbstractUnivariateStatistic implements Serializa * @param end index after the last element of the slice to sort */ private void insertionSort(final double[] work, final int begin, final int end) { + // Arrays.sort(work, begin, end); // Would also fix MATH-1129 for (int j = begin + 1; j < end; j++) { final double saved = work[j]; int i = j - 1; - while ((i >= begin) && (saved < work[i])) { - work[i + 1] = work[i]; - i--; + while (i >= begin) { + final double wi = work[i]; + if (saved < wi || Double.isNaN(wi)) { + work[i + 1] = wi; + i--; + } else { + break; + } } work[i + 1] = saved; }
bugs-dot-jar/commons-math_extracted_diff/developer-patch_bugs-dot-jar_MATH-1129_d4f978dd.diff
bugs-dot-jar_data_MATH-286_dbdff075
--- BugID: MATH-286 Summary: SimplexSolver not working as expected? Description: |- I guess (but I could be wrong) that SimplexSolver does not always return the optimal solution, nor satisfies all the constraints... Consider this LP: max: 0.8 x0 + 0.2 x1 + 0.7 x2 + 0.3 x3 + 0.6 x4 + 0.4 x5; r1: x0 + x2 + x4 = 23.0; r2: x1 + x3 + x5 = 23.0; r3: x0 >= 10.0; r4: x2 >= 8.0; r5: x4 >= 5.0; LPSolve returns 25.8, with x0 = 10.0, x1 = 0.0, x2 = 8.0, x3 = 0.0, x4 = 5.0, x5 = 23.0; The same LP expressed in Apache commons math is: LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 0.8, 0.2, 0.7, 0.3, 0.6, 0.4 }, 0 ); Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); constraints.add(new LinearConstraint(new double[] { 1, 0, 1, 0, 1, 0 }, Relationship.EQ, 23.0)); constraints.add(new LinearConstraint(new double[] { 0, 1, 0, 1, 0, 1 }, Relationship.EQ, 23.0)); constraints.add(new LinearConstraint(new double[] { 1, 0, 0, 0, 0, 0 }, Relationship.GEQ, 10.0)); constraints.add(new LinearConstraint(new double[] { 0, 0, 1, 0, 0, 0 }, Relationship.GEQ, 8.0)); constraints.add(new LinearConstraint(new double[] { 0, 0, 0, 0, 1, 0 }, Relationship.GEQ, 5.0)); RealPointValuePair solution = new SimplexSolver().optimize(f, constraints, GoalType.MAXIMIZE, true); that returns 22.20, with x0 = 15.0, x1 = 23.0, x2 = 8.0, x3 = 0.0, x4 = 0.0, x5 = 0.0; Is it possible SimplexSolver is buggy that way? The returned value is 22.20 instead of 25.8, and the last constraint (x4 >= 5.0) is not satisfied... Am I using the interface wrongly? diff --git a/src/main/java/org/apache/commons/math/optimization/linear/SimplexTableau.java b/src/main/java/org/apache/commons/math/optimization/linear/SimplexTableau.java index c228ad6..b387767 100644 --- a/src/main/java/org/apache/commons/math/optimization/linear/SimplexTableau.java +++ b/src/main/java/org/apache/commons/math/optimization/linear/SimplexTableau.java @@ -270,8 +270,27 @@ class SimplexTableau implements Serializable { * @return the row that the variable is basic in. null if the column is not basic */ private Integer getBasicRow(final int col) { + return getBasicRow(col, true); + } + + /** + * Checks whether the given column is basic. + * @param col index of the column to check + * @return the row that the variable is basic in. null if the column is not basic + */ + private Integer getBasicRowForSolution(final int col) { + return getBasicRow(col, false); + } + + /** + * Checks whether the given column is basic. + * @param col index of the column to check + * @return the row that the variable is basic in. null if the column is not basic + */ + private Integer getBasicRow(final int col, boolean ignoreObjectiveRows) { Integer row = null; - for (int i = getNumObjectiveFunctions(); i < getHeight(); i++) { + int start = ignoreObjectiveRows ? getNumObjectiveFunctions() : 0; + for (int i = start; i < getHeight(); i++) { if (MathUtils.equals(getEntry(i, col), 1.0, epsilon) && (row == null)) { row = i; } else if (!MathUtils.equals(getEntry(i, col), 0.0, epsilon)) { @@ -318,24 +337,23 @@ class SimplexTableau implements Serializable { * @return current solution */ protected RealPointValuePair getSolution() { - double[] coefficients = new double[getOriginalNumDecisionVariables()]; - Integer basicRow = - getBasicRow(getNumObjectiveFunctions() + getOriginalNumDecisionVariables()); - double mostNegative = basicRow == null ? 0 : getEntry(basicRow, getRhsOffset()); - Set<Integer> basicRows = new HashSet<Integer>(); - for (int i = 0; i < coefficients.length; i++) { - basicRow = getBasicRow(getNumObjectiveFunctions() + i); - if (basicRows.contains(basicRow)) { - // if multiple variables can take a given value - // then we choose the first and set the rest equal to 0 - coefficients[i] = 0; - } else { - basicRows.add(basicRow); - coefficients[i] = - (basicRow == null ? 0 : getEntry(basicRow, getRhsOffset())) - - (restrictToNonNegative ? 0 : mostNegative); - } - } + double[] coefficients = new double[getOriginalNumDecisionVariables()]; + Integer negativeVarBasicRow = getBasicRowForSolution(getNegativeDecisionVariableOffset()); + double mostNegative = negativeVarBasicRow == null ? 0 : getEntry(negativeVarBasicRow, getRhsOffset()); + Set<Integer> basicRows = new HashSet<Integer>(); + for (int i = 0; i < coefficients.length; i++) { + Integer basicRow = getBasicRowForSolution(getNumObjectiveFunctions() + i); + if (basicRows.contains(basicRow)) { + // if multiple variables can take a given value + // then we choose the first and set the rest equal to 0 + coefficients[i] = 0; + } else { + basicRows.add(basicRow); + coefficients[i] = + (basicRow == null ? 0 : getEntry(basicRow, getRhsOffset())) - + (restrictToNonNegative ? 0 : mostNegative); + } + } return new RealPointValuePair(coefficients, f.getValue(coefficients)); } @@ -430,6 +448,15 @@ class SimplexTableau implements Serializable { protected final int getRhsOffset() { return getWidth() - 1; } + + /** + * Returns the offset of the extra decision variable added when there is a + * negative decision variable in the original problem. + * @return the offset of x- + */ + protected final int getNegativeDecisionVariableOffset() { + return getNumObjectiveFunctions() + getOriginalNumDecisionVariables(); + } /** * Get the number of decision variables.
bugs-dot-jar/commons-math_extracted_diff/developer-patch_bugs-dot-jar_MATH-286_dbdff075.diff
bugs-dot-jar_data_MATH-371_bb005b56
--- BugID: MATH-371 Summary: PearsonsCorrelation.getCorrelationPValues() precision limited by machine epsilon Description: "Similar to the issue described in MATH-201, using PearsonsCorrelation.getCorrelationPValues() with many treatments results in p-values that are continuous down to 2.2e-16 but that drop to 0 after that.\n\nIn MATH-201, the problem was described as such:\n> So in essence, the p-value returned by TTestImpl.tTest() is:\n> \n> 1.0 - (cumulativeProbability(t) - cumulativeProbabily(-t))\n> \n> For large-ish t-statistics, cumulativeProbabilty(-t) can get quite small, and cumulativeProbabilty(t) can get very close to 1.0. When \n> cumulativeProbability(-t) is less than the machine epsilon, we get p-values equal to zero because:\n> \n> 1.0 - 1.0 + 0.0 = 0.0\n\nThe solution in MATH-201 was to modify the p-value calculation to this:\n> p = 2.0 * cumulativeProbability(-t)\n\nHere, the problem is similar. From PearsonsCorrelation.getCorrelationPValues():\n p = 2 * (1 - tDistribution.cumulativeProbability(t));\n\nDirectly calculating the p-value using identical code as PearsonsCorrelation.getCorrelationPValues(), but with the following change seems to solve the problem:\n p = 2 * (tDistribution.cumulativeProbability(-t));\n\n\n\n\n" diff --git a/src/main/java/org/apache/commons/math/stat/correlation/PearsonsCorrelation.java b/src/main/java/org/apache/commons/math/stat/correlation/PearsonsCorrelation.java index 83b4c41..dc83314 100644 --- a/src/main/java/org/apache/commons/math/stat/correlation/PearsonsCorrelation.java +++ b/src/main/java/org/apache/commons/math/stat/correlation/PearsonsCorrelation.java @@ -168,7 +168,7 @@ public class PearsonsCorrelation { } else { double r = correlationMatrix.getEntry(i, j); double t = Math.abs(r * Math.sqrt((nObs - 2)/(1 - r * r))); - out[i][j] = 2 * (1 - tDistribution.cumulativeProbability(t)); + out[i][j] = 2 * tDistribution.cumulativeProbability(-t); } } }
bugs-dot-jar/commons-math_extracted_diff/developer-patch_bugs-dot-jar_MATH-371_bb005b56.diff
bugs-dot-jar_data_MATH-1297_56434517
--- BugID: MATH-1297 Summary: multistep integrator start failure triggers NPE Description: |- Multistep ODE integrators like Adams-Bashforth and Adams-Moulton require a starter procedure. If the starter integrator is not configured properly, it will not create the necessary number of initial points and the multistep integrator will not be initialized correctly. This results in NullPointErException when the scaling array is referenced later on. The following test case (with an intentionally wrong starter configuration) shows the problem. {code} @Test public void testStartFailure() { TestProblem1 pb = new TestProblem1(); double minStep = 0.0001 * (pb.getFinalTime() - pb.getInitialTime()); double maxStep = pb.getFinalTime() - pb.getInitialTime(); double scalAbsoluteTolerance = 1.0e-6; double scalRelativeTolerance = 1.0e-7; MultistepIntegrator integ = new AdamsBashforthIntegrator(4, minStep, maxStep, scalAbsoluteTolerance, scalRelativeTolerance); integ.setStarterIntegrator(new DormandPrince853Integrator(0.2 * (pb.getFinalTime() - pb.getInitialTime()), pb.getFinalTime() - pb.getInitialTime(), 0.1, 0.1)); TestProblemHandler handler = new TestProblemHandler(pb, integ); integ.addStepHandler(handler); integ.integrate(pb, pb.getInitialTime(), pb.getInitialState(), pb.getFinalTime(), new double[pb.getDimension()]); } {code} Failure to start the integrator should be detected and an appropriate exception should be triggered. diff --git a/src/main/java/org/apache/commons/math4/exception/util/LocalizedFormats.java b/src/main/java/org/apache/commons/math4/exception/util/LocalizedFormats.java index 1b589f1..dabe9a7 100644 --- a/src/main/java/org/apache/commons/math4/exception/util/LocalizedFormats.java +++ b/src/main/java/org/apache/commons/math4/exception/util/LocalizedFormats.java @@ -162,6 +162,7 @@ public enum LocalizedFormats implements Localizable { LOWER_BOUND_NOT_BELOW_UPPER_BOUND("lower bound ({0}) must be strictly less than upper bound ({1})"), /* keep */ LOWER_ENDPOINT_ABOVE_UPPER_ENDPOINT("lower endpoint ({0}) must be less than or equal to upper endpoint ({1})"), MAP_MODIFIED_WHILE_ITERATING("map has been modified while iterating"), + MULTISTEP_STARTER_STOPPED_EARLY("multistep integrator starter stopped early, maybe too large step size"), EVALUATIONS("evaluations"), /* keep */ MAX_COUNT_EXCEEDED("maximal count ({0}) exceeded"), /* keep */ MAX_ITERATIONS_EXCEEDED("maximal number of iterations ({0}) exceeded"), diff --git a/src/main/java/org/apache/commons/math4/ode/MultistepIntegrator.java b/src/main/java/org/apache/commons/math4/ode/MultistepIntegrator.java index b415dd1..354db49 100644 --- a/src/main/java/org/apache/commons/math4/ode/MultistepIntegrator.java +++ b/src/main/java/org/apache/commons/math4/ode/MultistepIntegrator.java @@ -18,6 +18,7 @@ package org.apache.commons.math4.ode; import org.apache.commons.math4.exception.DimensionMismatchException; +import org.apache.commons.math4.exception.MathIllegalStateException; import org.apache.commons.math4.exception.MaxCountExceededException; import org.apache.commons.math4.exception.NoBracketingException; import org.apache.commons.math4.exception.NumberIsTooSmallException; @@ -248,6 +249,9 @@ public abstract class MultistepIntegrator extends AdaptiveStepsizeIntegrator { }, t0, y0, t, new double[y0.length]); } + // we should not reach this step + throw new MathIllegalStateException(LocalizedFormats.MULTISTEP_STARTER_STOPPED_EARLY); + } catch (InitializationCompletedMarkerException icme) { // NOPMD // this is the expected nominal interruption of the start integrator
bugs-dot-jar/commons-math_extracted_diff/developer-patch_bugs-dot-jar_MATH-1297_56434517.diff
bugs-dot-jar_data_MATH-924_2836a6f9
--- BugID: MATH-924 Summary: new multivariate vector optimizers cannot be used with large number of weights Description: |- When using the Weigth class to pass a large number of weights to multivariate vector optimizers, an nxn full matrix is created (and copied) when a n elements vector is used. This exhausts memory when n is large. This happens for example when using curve fitters (even simple curve fitters like polynomial ones for low degree) with large number of points. I encountered this with curve fitting on 41200 points, which created a matrix with 1.7 billion elements. diff --git a/src/main/java/org/apache/commons/math3/optimization/Weight.java b/src/main/java/org/apache/commons/math3/optimization/Weight.java index 8e7538f..28c1619 100644 --- a/src/main/java/org/apache/commons/math3/optimization/Weight.java +++ b/src/main/java/org/apache/commons/math3/optimization/Weight.java @@ -18,7 +18,7 @@ package org.apache.commons.math3.optimization; import org.apache.commons.math3.linear.RealMatrix; -import org.apache.commons.math3.linear.Array2DRowRealMatrix; +import org.apache.commons.math3.linear.DiagonalMatrix; import org.apache.commons.math3.linear.NonSquareMatrixException; /** @@ -41,11 +41,7 @@ public class Weight implements OptimizationData { * @param weight List of the values of the diagonal. */ public Weight(double[] weight) { - final int dim = weight.length; - weightMatrix = new Array2DRowRealMatrix(dim, dim); - for (int i = 0; i < dim; i++) { - weightMatrix.setEntry(i, i, weight[i]); - } + weightMatrix = new DiagonalMatrix(weight); } /** diff --git a/src/main/java/org/apache/commons/math3/optimization/general/AbstractLeastSquaresOptimizer.java b/src/main/java/org/apache/commons/math3/optimization/general/AbstractLeastSquaresOptimizer.java index b6c97e7..982e559 100644 --- a/src/main/java/org/apache/commons/math3/optimization/general/AbstractLeastSquaresOptimizer.java +++ b/src/main/java/org/apache/commons/math3/optimization/general/AbstractLeastSquaresOptimizer.java @@ -26,6 +26,7 @@ import org.apache.commons.math3.exception.NumberIsTooSmallException; import org.apache.commons.math3.exception.util.LocalizedFormats; import org.apache.commons.math3.linear.ArrayRealVector; import org.apache.commons.math3.linear.RealMatrix; +import org.apache.commons.math3.linear.DiagonalMatrix; import org.apache.commons.math3.linear.DecompositionSolver; import org.apache.commons.math3.linear.MatrixUtils; import org.apache.commons.math3.linear.QRDecomposition; @@ -558,7 +559,16 @@ public abstract class AbstractLeastSquaresOptimizer * @return the square-root of the weight matrix. */ private RealMatrix squareRoot(RealMatrix m) { - final EigenDecomposition dec = new EigenDecomposition(m); - return dec.getSquareRoot(); + if (m instanceof DiagonalMatrix) { + final int dim = m.getRowDimension(); + final RealMatrix sqrtM = new DiagonalMatrix(dim); + for (int i = 0; i < dim; i++) { + sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i))); + } + return sqrtM; + } else { + final EigenDecomposition dec = new EigenDecomposition(m); + return dec.getSquareRoot(); + } } }
bugs-dot-jar/commons-math_extracted_diff/developer-patch_bugs-dot-jar_MATH-924_2836a6f9.diff
bugs-dot-jar_data_MATH-349_4cc9a49d
--- BugID: MATH-349 Summary: Dangerous code in "PoissonDistributionImpl" Description: | In the following excerpt from class "PoissonDistributionImpl": {code:title=PoissonDistributionImpl.java|borderStyle=solid} public PoissonDistributionImpl(double p, NormalDistribution z) { super(); setNormal(z); setMean(p); } {code} (1) Overridable methods are called within the constructor. (2) The reference "z" is stored and modified within the class. I've encountered problem (1) in several classes while working on issue 348. In those cases, in order to remove potential problems, I copied/pasted the body of the "setter" methods inside the constructor but I think that a more elegant solution would be to remove the "setters" altogether (i.e. make the classes immutable). Problem (2) can also create unexpected behaviour. Is it really necessary to pass the "NormalDistribution" object; can't it be always created within the class? diff --git a/src/main/java/org/apache/commons/math/distribution/PoissonDistribution.java b/src/main/java/org/apache/commons/math/distribution/PoissonDistribution.java index 6aca509..d20eb53 100644 --- a/src/main/java/org/apache/commons/math/distribution/PoissonDistribution.java +++ b/src/main/java/org/apache/commons/math/distribution/PoissonDistribution.java @@ -32,7 +32,6 @@ import org.apache.commons.math.MathException; * @version $Revision$ $Date$ */ public interface PoissonDistribution extends IntegerDistribution { - /** * Get the mean for the distribution. * @@ -41,18 +40,6 @@ public interface PoissonDistribution extends IntegerDistribution { double getMean(); /** - * Set the mean for the distribution. - * The parameter value must be positive; otherwise an - * <code>IllegalArgument</code> is thrown. - * - * @param p the mean - * @throws IllegalArgumentException if p &le; 0 - * @deprecated as of v2.1 - */ - @Deprecated - void setMean(double p); - - /** * Calculates the Poisson distribution function using a normal approximation. * * @param x the upper bound, inclusive @@ -60,5 +47,4 @@ public interface PoissonDistribution extends IntegerDistribution { * @throws MathException if an error occurs computing the normal approximation */ double normalApproximateProbability(int x) throws MathException; - } diff --git a/src/main/java/org/apache/commons/math/distribution/PoissonDistributionImpl.java b/src/main/java/org/apache/commons/math/distribution/PoissonDistributionImpl.java index 64f792b..0a81233 100644 --- a/src/main/java/org/apache/commons/math/distribution/PoissonDistributionImpl.java +++ b/src/main/java/org/apache/commons/math/distribution/PoissonDistributionImpl.java @@ -19,7 +19,7 @@ package org.apache.commons.math.distribution; import java.io.Serializable; import org.apache.commons.math.MathException; -import org.apache.commons.math.MathRuntimeException; +import org.apache.commons.math.exception.NotStrictlyPositiveException; import org.apache.commons.math.exception.util.LocalizedFormats; import org.apache.commons.math.special.Gamma; import org.apache.commons.math.util.MathUtils; @@ -77,7 +77,7 @@ public class PoissonDistributionImpl extends AbstractIntegerDistribution * @throws IllegalArgumentException if p &le; 0 */ public PoissonDistributionImpl(double p) { - this(p, new NormalDistributionImpl()); + this(p, DEFAULT_EPSILON, DEFAULT_MAX_ITERATIONS); } /** @@ -90,7 +90,11 @@ public class PoissonDistributionImpl extends AbstractIntegerDistribution * @since 2.1 */ public PoissonDistributionImpl(double p, double epsilon, int maxIterations) { - setMean(p); + if (p <= 0) { + throw new NotStrictlyPositiveException(LocalizedFormats.MEAN, p); + } + mean = p; + normal = new NormalDistributionImpl(p, FastMath.sqrt(p)); this.epsilon = epsilon; this.maxIterations = maxIterations; } @@ -103,8 +107,7 @@ public class PoissonDistributionImpl extends AbstractIntegerDistribution * @since 2.1 */ public PoissonDistributionImpl(double p, double epsilon) { - setMean(p); - this.epsilon = epsilon; + this(p, epsilon, DEFAULT_MAX_ITERATIONS); } /** @@ -115,26 +118,7 @@ public class PoissonDistributionImpl extends AbstractIntegerDistribution * @since 2.1 */ public PoissonDistributionImpl(double p, int maxIterations) { - setMean(p); - this.maxIterations = maxIterations; - } - - - /** - * Create a new Poisson distribution with the given the mean. The mean value - * must be positive; otherwise an <code>IllegalArgument</code> is thrown. - * - * @param p the Poisson mean - * @param z a normal distribution used to compute normal approximations. - * @throws IllegalArgumentException if p &le; 0 - * @since 1.2 - * @deprecated as of 2.1 (to avoid possibly inconsistent state, the - * "NormalDistribution" will be instantiated internally) - */ - @Deprecated - public PoissonDistributionImpl(double p, NormalDistribution z) { - super(); - setNormalAndMeanInternal(z, p); + this(p, DEFAULT_EPSILON, maxIterations); } /** @@ -147,38 +131,6 @@ public class PoissonDistributionImpl extends AbstractIntegerDistribution } /** - * Set the Poisson mean for the distribution. The mean value must be - * positive; otherwise an <code>IllegalArgument</code> is thrown. - * - * @param p the Poisson mean value - * @throws IllegalArgumentException if p &le; 0 - * @deprecated as of 2.1 (class will become immutable in 3.0) - */ - @Deprecated - public void setMean(double p) { - setNormalAndMeanInternal(normal, p); - } - /** - * Set the Poisson mean for the distribution. The mean value must be - * positive; otherwise an <code>IllegalArgument</code> is thrown. - * - * @param z the new distribution - * @param p the Poisson mean value - * @throws IllegalArgumentException if p &le; 0 - */ - private void setNormalAndMeanInternal(NormalDistribution z, - double p) { - if (p <= 0) { - throw MathRuntimeException.createIllegalArgumentException( - LocalizedFormats.NOT_POSITIVE_POISSON_MEAN, p); - } - mean = p; - normal = z; - normal.setMean(p); - normal.setStandardDeviation(FastMath.sqrt(p)); - } - - /** * The probability mass function P(X = x) for a Poisson distribution. * * @param x the value at which the probability density function is @@ -286,18 +238,4 @@ public class PoissonDistributionImpl extends AbstractIntegerDistribution protected int getDomainUpperBound(double p) { return Integer.MAX_VALUE; } - - /** - * Modify the normal distribution used to compute normal approximations. The - * caller is responsible for insuring the normal distribution has the proper - * parameter settings. - * - * @param value the new distribution - * @since 1.2 - * @deprecated as of 2.1 (class will become immutable in 3.0) - */ - @Deprecated - public void setNormal(NormalDistribution value) { - setNormalAndMeanInternal(value, mean); - } }
bugs-dot-jar/commons-math_extracted_diff/developer-patch_bugs-dot-jar_MATH-349_4cc9a49d.diff
bugs-dot-jar_data_MATH-657_32b0f733
--- BugID: MATH-657 Summary: Division by zero Description: 'In class {{Complex}}, division by zero always returns NaN. I think that it should return NaN only when the numerator is also {{ZERO}}, otherwise the result should be {{INF}}. See [here|http://en.wikipedia.org/wiki/Riemann_sphere#Arithmetic_operations]. ' diff --git a/src/main/java/org/apache/commons/math/complex/Complex.java b/src/main/java/org/apache/commons/math/complex/Complex.java index ac31e4b..137765c 100644 --- a/src/main/java/org/apache/commons/math/complex/Complex.java +++ b/src/main/java/org/apache/commons/math/complex/Complex.java @@ -78,6 +78,8 @@ public class Complex implements FieldElement<Complex>, Serializable { private final transient boolean isNaN; /** Record whether this complex number is infinite. */ private final transient boolean isInfinite; + /** Record whether this complex number is zero. */ + private final transient boolean isZero; /** * Create a complex number given only the real part. @@ -101,6 +103,7 @@ public class Complex implements FieldElement<Complex>, Serializable { isNaN = Double.isNaN(real) || Double.isNaN(imaginary); isInfinite = !isNaN && (Double.isInfinite(real) || Double.isInfinite(imaginary)); + isZero = real == 0 && imaginary == 0; } /** @@ -222,7 +225,10 @@ public class Complex implements FieldElement<Complex>, Serializable { * <li>If either {@code this} or {@code divisor} has a {@code NaN} value * in either part, {@link #NaN} is returned. * </li> - * <li>If {@code divisor} equals {@link #ZERO}, {@link #NaN} is returned. + * <li>If {@code this} and {@code divisor} are both {@link #ZERO}, + * {@link #NaN} is returned. + * </li> + * <li>If {@code divisor} equals {@link #ZERO}, {@link #INF} is returned. * </li> * <li>If {@code this} and {@code divisor} are both infinite, * {@link #NaN} is returned. @@ -249,16 +255,17 @@ public class Complex implements FieldElement<Complex>, Serializable { return NaN; } - final double c = divisor.getReal(); - final double d = divisor.getImaginary(); - if (c == 0.0 && d == 0.0) { - return NaN; + if (divisor.isZero) { + return isZero ? NaN : INF; } if (divisor.isInfinite() && !isInfinite()) { return ZERO; } + final double c = divisor.getReal(); + final double d = divisor.getImaginary(); + if (FastMath.abs(c) < FastMath.abs(d)) { double q = c / d; double denominator = c * q + d; @@ -285,7 +292,7 @@ public class Complex implements FieldElement<Complex>, Serializable { return NaN; } if (divisor == 0d) { - return NaN; + return isZero ? NaN : INF; } if (Double.isInfinite(divisor)) { return !isInfinite() ? ZERO : NaN;
bugs-dot-jar/commons-math_extracted_diff/developer-patch_bugs-dot-jar_MATH-657_32b0f733.diff
bugs-dot-jar_data_MATH-1135_a7363a2a
--- BugID: MATH-1135 Summary: 'Bug in MonotoneChain: a collinear point landing on the existing boundary should be dropped (patch)' Description: "The is a bug on the code in MonotoneChain.java that attempts to handle the case of a point on the line formed by the previous last points and the last point of the chain being constructed. When `includeCollinearPoints` is false, the point should be dropped entirely. In common-math 3,3, the point is added, which in some cases can cause a `ConvergenceException` to be thrown.\n\nIn the patch below, the data points are from a case that showed up in testing before we went to production.\n\n{code:java}\nIndex: src/main/java/org/apache/commons/math3/geometry/euclidean/twod/hull/MonotoneChain.java\n===================================================================\n--- src/main/java/org/apache/commons/math3/geometry/euclidean/twod/hull/MonotoneChain.java\t(revision 1609491)\n+++ src/main/java/org/apache/commons/math3/geometry/euclidean/twod/hull/MonotoneChain.java\t(working copy)\n@@ -160,8 +160,8 @@\n } else {\n if (distanceToCurrent > distanceToLast) {\n hull.remove(size - 1);\n+ hull.add(point);\n \ }\n- hull.add(point);\n }\n \ return;\n } else if (offset > 0) {\nIndex: src/test/java/org/apache/commons/math3/geometry/euclidean/twod/hull/ConvexHullGenerator2DAbstractTest.java\n===================================================================\n--- src/test/java/org/apache/commons/math3/geometry/euclidean/twod/hull/ConvexHullGenerator2DAbstractTest.java\t(revision 1609491)\n+++ src/test/java/org/apache/commons/math3/geometry/euclidean/twod/hull/ConvexHullGenerator2DAbstractTest.java\t(working copy)\n@@ -204,6 +204,24 @@\n }\n \n @Test\n+ public void testCollinnearPointOnExistingBoundary() {\n+ final Collection<Vector2D> points = new ArrayList<Vector2D>();\n+ points.add(new Vector2D(7.3152, 34.7472));\n+ points.add(new Vector2D(6.400799999999997, 34.747199999999985));\n+ points.add(new Vector2D(5.486399999999997, 34.7472));\n+ \ points.add(new Vector2D(4.876799999999999, 34.7472));\n+ points.add(new Vector2D(4.876799999999999, 34.1376));\n+ points.add(new Vector2D(4.876799999999999, 30.48));\n+ points.add(new Vector2D(6.0959999999999965, 30.48));\n+ points.add(new Vector2D(6.0959999999999965, 34.1376));\n+ points.add(new Vector2D(7.315199999999996, 34.1376));\n+ points.add(new Vector2D(7.3152, 30.48));\n+\n+ final ConvexHull2D hull = generator.generate(points);\n+ checkConvexHull(points, hull);\n+ }\n+\n+ @Test\n public void testIssue1123() {\n \n List<Vector2D> points = new ArrayList<Vector2D>();\n{code}" diff --git a/src/main/java/org/apache/commons/math3/geometry/euclidean/twod/hull/MonotoneChain.java b/src/main/java/org/apache/commons/math3/geometry/euclidean/twod/hull/MonotoneChain.java index 2ade7a6..50fd6b7 100644 --- a/src/main/java/org/apache/commons/math3/geometry/euclidean/twod/hull/MonotoneChain.java +++ b/src/main/java/org/apache/commons/math3/geometry/euclidean/twod/hull/MonotoneChain.java @@ -160,8 +160,8 @@ public class MonotoneChain extends AbstractConvexHullGenerator2D { } else { if (distanceToCurrent > distanceToLast) { hull.remove(size - 1); + hull.add(point); } - hull.add(point); } return; } else if (offset > 0) {
bugs-dot-jar/commons-math_extracted_diff/developer-patch_bugs-dot-jar_MATH-1135_a7363a2a.diff
bugs-dot-jar_data_MATH-434_133cbc2d
--- BugID: MATH-434 Summary: SimplexSolver returns unfeasible solution Description: "The SimplexSolver is returning an unfeasible solution:\n\nimport java.util.ArrayList;\nimport java.text.DecimalFormat;\nimport org.apache.commons.math.linear.ArrayRealVector;\nimport org.apache.commons.math.optimization.GoalType;\nimport org.apache.commons.math.optimization.OptimizationException;\nimport org.apache.commons.math.optimization.linear.*;\n\npublic class SimplexSolverBug {\n \n public static void main(String[] args) throws OptimizationException {\n \n LinearObjectiveFunction c = new LinearObjectiveFunction(new double[]{0.0d, 1.0d, 1.0d, 0.0d, 0.0d, 0.0d, 0.0d}, 0.0d);\n \n ArrayList<LinearConstraint> cnsts = new ArrayList<LinearConstraint>(5);\n LinearConstraint cnst;\n cnst = new LinearConstraint(new double[] {1.0d, -0.1d, 0.0d, 0.0d, 0.0d, 0.0d, 0.0d}, Relationship.EQ, -0.1d);\n cnsts.add(cnst);\n cnst = new LinearConstraint(new double[] {1.0d, 0.0d, 0.0d, 0.0d, 0.0d, 0.0d, 0.0d}, Relationship.GEQ, -1e-18d);\n \ cnsts.add(cnst);\n cnst = new LinearConstraint(new double[] {0.0d, 1.0d, 0.0d, 0.0d, 0.0d, 0.0d, 0.0d}, Relationship.GEQ, 0.0d);\n cnsts.add(cnst);\n \ cnst = new LinearConstraint(new double[] {0.0d, 0.0d, 0.0d, 1.0d, 0.0d, -0.0128588d, 1e-5d}, Relationship.EQ, 0.0d);\n cnsts.add(cnst);\n cnst = new LinearConstraint(new double[] {0.0d, 0.0d, 0.0d, 0.0d, 1.0d, 1e-5d, -0.0128586d}, Relationship.EQ, 1e-10d);\n cnsts.add(cnst);\n cnst = new LinearConstraint(new double[] {0.0d, 0.0d, 1.0d, -1.0d, 0.0d, 0.0d, 0.0d}, Relationship.GEQ, 0.0d);\n \ cnsts.add(cnst);\n cnst = new LinearConstraint(new double[] {0.0d, 0.0d, 1.0d, 1.0d, 0.0d, 0.0d, 0.0d}, Relationship.GEQ, 0.0d);\n cnsts.add(cnst);\n \ cnst = new LinearConstraint(new double[] {0.0d, 0.0d, 1.0d, 0.0d, -1.0d, 0.0d, 0.0d}, Relationship.GEQ, 0.0d);\n cnsts.add(cnst);\n cnst = new LinearConstraint(new double[] {0.0d, 0.0d, 1.0d, 0.0d, 1.0d, 0.0d, 0.0d}, Relationship.GEQ, 0.0d);\n cnsts.add(cnst);\n \n DecimalFormat df = new java.text.DecimalFormat(\"0.#####E0\");\n \n System.out.println(\"Constraints:\");\n \ for(LinearConstraint con : cnsts) {\n for (int i = 0; i < con.getCoefficients().getDimension(); ++i)\n System.out.print(df.format(con.getCoefficients().getData()[i]) + \" \");\n System.out.println(con.getRelationship() + \" \" + con.getValue());\n \ }\n \n SimplexSolver simplex = new SimplexSolver(1e-7);\n \ double[] sol = simplex.optimize(c, cnsts, GoalType.MINIMIZE, false).getPointRef();\n \ System.out.println(\"Solution:\\n\" + new ArrayRealVector(sol));\n System.out.println(\"Second constraint is violated!\");\n }\n}\n\n\nIt's an odd problem, but something I ran across. I tracked the problem to the getPivotRow routine in SimplexSolver. \ It was choosing a pivot that resulted in a negative right-hand-side. I recommend a fix by replacing\n ...\n if (MathUtils.equals(ratio, minRatio, epsilon)) {\n ...\nwith\n ...\n if (MathUtils.equals(ratio, minRatio, Math.abs(epsilon/entry))) {\n ...\n\nI believe this would be more appropriate (and at least resolves this particular problem).\n\nAlso, you may want to consider making a change in getPivotColumn to replace\n ...\n \ if (MathUtils.compareTo(tableau.getEntry(0, i), minValue, epsilon) < 0) {\n ...\nwith\n ...\n if (tableau.getEntry(0, i) < minValue) \n ...\nbecause I don't see the point of biasing earlier columns when multiple entries are within epsilon of each other. Why not pick the absolute smallest. I don't know that any problem can result from doing it the other way, but the latter may be a safer bet.\n\nVERY IMPORTANT: I discovered another bug that occurs when not restricting to non-negatives. In SimplexTableu::getSolution(), \n ... \n if (basicRows.contains(basicRow)) \n // if multiple variables can take a given value\n // then we choose the first and set the rest equal to 0\n coefficients[i] = 0;\n ...\nshould be\n ... \n if (basicRows.contains(basicRow)) {\n // if multiple variables can take a given value\n // then we choose the first and set the rest equal to 0\n coefficients[i] = (restrictToNonNegative ? 0 : -mostNegative);\n ...\nIf necessary, I can give an example of where this bug causes a problem, but it should be fairly obvious why this was wrong.\n" diff --git a/src/main/java/org/apache/commons/math/optimization/linear/SimplexSolver.java b/src/main/java/org/apache/commons/math/optimization/linear/SimplexSolver.java index 5c25548..b9afc0a 100644 --- a/src/main/java/org/apache/commons/math/optimization/linear/SimplexSolver.java +++ b/src/main/java/org/apache/commons/math/optimization/linear/SimplexSolver.java @@ -22,6 +22,7 @@ import java.util.List; import org.apache.commons.math.optimization.OptimizationException; import org.apache.commons.math.optimization.RealPointValuePair; +import org.apache.commons.math.util.FastMath; import org.apache.commons.math.util.MathUtils; @@ -31,26 +32,34 @@ import org.apache.commons.math.util.MathUtils; * @since 2.0 */ public class SimplexSolver extends AbstractLinearOptimizer { - - /** Default amount of error to accept in floating point comparisons. */ + + /** Default amount of error to accept for algorithm convergence. */ private static final double DEFAULT_EPSILON = 1.0e-6; - - /** Amount of error to accept in floating point comparisons. */ + + /** Amount of error to accept for algorithm convergence. */ protected final double epsilon; + /** Default amount of error to accept in floating point comparisons (as ulps). */ + private static final int DEFAULT_ULPS = 10; + + /** Amount of error to accept in floating point comparisons (as ulps). */ + protected final int maxUlps; + /** * Build a simplex solver with default settings. */ public SimplexSolver() { - this(DEFAULT_EPSILON); + this(DEFAULT_EPSILON, DEFAULT_ULPS); } /** * Build a simplex solver with a specified accepted amount of error - * @param epsilon the amount of error to accept in floating point comparisons + * @param epsilon the amount of error to accept for algorithm convergence + * @param maxUlps amount of error to accept in floating point comparisons */ - public SimplexSolver(final double epsilon) { + public SimplexSolver(final double epsilon, final int maxUlps) { this.epsilon = epsilon; + this.maxUlps = maxUlps; } /** @@ -62,8 +71,9 @@ public class SimplexSolver extends AbstractLinearOptimizer { double minValue = 0; Integer minPos = null; for (int i = tableau.getNumObjectiveFunctions(); i < tableau.getWidth() - 1; i++) { - if (MathUtils.compareTo(tableau.getEntry(0, i), minValue, epsilon) < 0) { - minValue = tableau.getEntry(0, i); + final double entry = tableau.getEntry(0, i); + if (MathUtils.compareTo(entry, minValue, getEpsilon(entry)) < 0) { + minValue = entry; minPos = i; } } @@ -83,11 +93,13 @@ public class SimplexSolver extends AbstractLinearOptimizer { for (int i = tableau.getNumObjectiveFunctions(); i < tableau.getHeight(); i++) { final double rhs = tableau.getEntry(i, tableau.getWidth() - 1); final double entry = tableau.getEntry(i, col); - if (MathUtils.compareTo(entry, 0, epsilon) > 0) { + + if (MathUtils.compareTo(entry, 0d, getEpsilon(entry)) > 0) { final double ratio = rhs / entry; - if (MathUtils.equals(ratio, minRatio, epsilon)) { + final int cmp = MathUtils.compareTo(ratio, minRatio, getEpsilon(ratio)); + if (cmp == 0) { minRatioPositions.add(i); - } else if (ratio < minRatio) { + } else if (cmp < 0) { minRatio = ratio; minRatioPositions = new ArrayList<Integer>(); minRatioPositions.add(i); @@ -103,7 +115,8 @@ public class SimplexSolver extends AbstractLinearOptimizer { for (Integer row : minRatioPositions) { for (int i = 0; i < tableau.getNumArtificialVariables(); i++) { int column = i + tableau.getArtificialVariableOffset(); - if (MathUtils.equals(tableau.getEntry(row, column), 1, epsilon) && + final double entry = tableau.getEntry(row, column); + if (MathUtils.equals(entry, 1d, getEpsilon(entry)) && row.equals(tableau.getBasicRow(column))) { return row; } @@ -162,7 +175,7 @@ public class SimplexSolver extends AbstractLinearOptimizer { } // if W is not zero then we have no feasible solution - if (!MathUtils.equals(tableau.getEntry(0, tableau.getRhsOffset()), 0, epsilon)) { + if (!MathUtils.equals(tableau.getEntry(0, tableau.getRhsOffset()), 0d, epsilon)) { throw new NoFeasibleSolutionException(); } } @@ -171,7 +184,8 @@ public class SimplexSolver extends AbstractLinearOptimizer { @Override public RealPointValuePair doOptimize() throws OptimizationException { final SimplexTableau tableau = - new SimplexTableau(function, linearConstraints, goal, nonNegative, epsilon); + new SimplexTableau(function, linearConstraints, goal, nonNegative, + epsilon, maxUlps); solvePhase1(tableau); tableau.dropPhase1Objective(); @@ -182,4 +196,12 @@ public class SimplexSolver extends AbstractLinearOptimizer { return tableau.getSolution(); } + /** + * Get an epsilon that is adjusted to the magnitude of the given value. + * @param value the value for which to get the epsilon + * @return magnitude-adjusted epsilon using {@link FastMath.ulp} + */ + private double getEpsilon(double value) { + return FastMath.ulp(value) * (double) maxUlps; + } } diff --git a/src/main/java/org/apache/commons/math/optimization/linear/SimplexTableau.java b/src/main/java/org/apache/commons/math/optimization/linear/SimplexTableau.java index 647d6be..0d1d911 100644 --- a/src/main/java/org/apache/commons/math/optimization/linear/SimplexTableau.java +++ b/src/main/java/org/apache/commons/math/optimization/linear/SimplexTableau.java @@ -33,6 +33,7 @@ import org.apache.commons.math.linear.RealMatrix; import org.apache.commons.math.linear.RealVector; import org.apache.commons.math.optimization.GoalType; import org.apache.commons.math.optimization.RealPointValuePair; +import org.apache.commons.math.util.FastMath; import org.apache.commons.math.util.MathUtils; /** @@ -65,6 +66,9 @@ class SimplexTableau implements Serializable { /** Column label for negative vars. */ private static final String NEGATIVE_VAR_COLUMN_LABEL = "x-"; + /** Default amount of error to accept in floating point comparisons (as ulps). */ + private static final int DEFAULT_ULPS = 10; + /** Serializable version identifier. */ private static final long serialVersionUID = -1369660067587938365L; @@ -92,9 +96,12 @@ class SimplexTableau implements Serializable { /** Number of artificial variables. */ private int numArtificialVariables; - /** Amount of error to accept in floating point comparisons. */ + /** Amount of error to accept when checking for optimality. */ private final double epsilon; + /** Amount of error to accept in floating point comparisons. */ + private final int maxUlps; + /** * Build a tableau for a linear problem. * @param f linear objective function @@ -102,16 +109,35 @@ class SimplexTableau implements Serializable { * @param goalType type of optimization goal: either {@link GoalType#MAXIMIZE} * or {@link GoalType#MINIMIZE} * @param restrictToNonNegative whether to restrict the variables to non-negative values - * @param epsilon amount of error to accept in floating point comparisons + * @param epsilon amount of error to accept when checking for optimality */ SimplexTableau(final LinearObjectiveFunction f, final Collection<LinearConstraint> constraints, final GoalType goalType, final boolean restrictToNonNegative, final double epsilon) { + this(f, constraints, goalType, restrictToNonNegative, epsilon, DEFAULT_ULPS); + } + + /** + * Build a tableau for a linear problem. + * @param f linear objective function + * @param constraints linear constraints + * @param goalType type of optimization goal: either {@link GoalType#MAXIMIZE} + * or {@link GoalType#MINIMIZE} + * @param restrictToNonNegative whether to restrict the variables to non-negative values + * @param epsilon amount of error to accept when checking for optimality + * @param maxUlps amount of error to accept in floating point comparisons + */ + SimplexTableau(final LinearObjectiveFunction f, + final Collection<LinearConstraint> constraints, + final GoalType goalType, final boolean restrictToNonNegative, + final double epsilon, + final int maxUlps) { this.f = f; this.constraints = normalizeConstraints(constraints); this.restrictToNonNegative = restrictToNonNegative; this.epsilon = epsilon; + this.maxUlps = maxUlps; this.numDecisionVariables = f.getCoefficients().getDimension() + (restrictToNonNegative ? 0 : 1); this.numSlackVariables = getConstraintTypeCounts(Relationship.LEQ) + @@ -172,7 +198,7 @@ class SimplexTableau implements Serializable { if (!restrictToNonNegative) { matrix.setEntry(zIndex, getSlackVariableOffset() - 1, - getInvertedCoeffiecientSum(objectiveCoefficients)); + getInvertedCoefficientSum(objectiveCoefficients)); } // initialize the constraint rows @@ -188,7 +214,7 @@ class SimplexTableau implements Serializable { // x- if (!restrictToNonNegative) { matrix.setEntry(row, getSlackVariableOffset() - 1, - getInvertedCoeffiecientSum(constraint.getCoefficients())); + getInvertedCoefficientSum(constraint.getCoefficients())); } // RHS @@ -269,7 +295,7 @@ class SimplexTableau implements Serializable { * @param coefficients coefficients to sum * @return the -1 times the sum of all coefficients in the given array. */ - protected static double getInvertedCoeffiecientSum(final RealVector coefficients) { + protected static double getInvertedCoefficientSum(final RealVector coefficients) { double sum = 0; for (double coefficient : coefficients.getData()) { sum -= coefficient; @@ -285,9 +311,10 @@ class SimplexTableau implements Serializable { protected Integer getBasicRow(final int col) { Integer row = null; for (int i = 0; i < getHeight(); i++) { - if (MathUtils.equals(getEntry(i, col), 1.0, epsilon) && (row == null)) { + final double entry = getEntry(i, col); + if (MathUtils.equals(entry, 1d, getEpsilon(entry)) && (row == null)) { row = i; - } else if (!MathUtils.equals(getEntry(i, col), 0.0, epsilon)) { + } else if (!MathUtils.equals(entry, 0d, getEpsilon(entry))) { return null; } } @@ -308,9 +335,10 @@ class SimplexTableau implements Serializable { // positive cost non-artificial variables for (int i = getNumObjectiveFunctions(); i < getArtificialVariableOffset(); i++) { - if (MathUtils.compareTo(tableau.getEntry(0, i), 0, epsilon) > 0) { - columnsToDrop.add(i); - } + final double entry = tableau.getEntry(0, i); + if (MathUtils.compareTo(entry, 0d, getEpsilon(entry)) > 0) { + columnsToDrop.add(i); + } } // non-basic artificial variables @@ -353,7 +381,8 @@ class SimplexTableau implements Serializable { */ boolean isOptimal() { for (int i = getNumObjectiveFunctions(); i < getWidth() - 1; i++) { - if (MathUtils.compareTo(tableau.getEntry(0, i), 0, epsilon) < 0) { + final double entry = tableau.getEntry(0, i); + if (MathUtils.compareTo(entry, 0d, epsilon) < 0) { return false; } } @@ -382,7 +411,7 @@ class SimplexTableau implements Serializable { if (basicRows.contains(basicRow)) { // if multiple variables can take a given value // then we choose the first and set the rest equal to 0 - coefficients[i] = 0; + coefficients[i] = 0 - (restrictToNonNegative ? 0 : mostNegative); } else { basicRows.add(basicRow); coefficients[i] = @@ -545,6 +574,7 @@ class SimplexTableau implements Serializable { (numSlackVariables == rhs.numSlackVariables) && (numArtificialVariables == rhs.numArtificialVariables) && (epsilon == rhs.epsilon) && + (maxUlps == rhs.maxUlps) && f.equals(rhs.f) && constraints.equals(rhs.constraints) && tableau.equals(rhs.tableau); @@ -560,6 +590,7 @@ class SimplexTableau implements Serializable { numSlackVariables ^ numArtificialVariables ^ Double.valueOf(epsilon).hashCode() ^ + maxUlps ^ f.hashCode() ^ constraints.hashCode() ^ tableau.hashCode(); @@ -585,5 +616,13 @@ class SimplexTableau implements Serializable { ois.defaultReadObject(); MatrixUtils.deserializeRealMatrix(this, "tableau", ois); } - + + /** + * Get an epsilon that is adjusted to the magnitude of the given value. + * @param value the value for which to get the epsilon + * @return magnitude-adjusted epsilon using {@link FastMath.ulp} + */ + private double getEpsilon(double value) { + return FastMath.ulp(value) * (double) maxUlps; + } }
bugs-dot-jar/commons-math_extracted_diff/developer-patch_bugs-dot-jar_MATH-434_133cbc2d.diff
bugs-dot-jar_data_MATH-705_645d642b
--- BugID: MATH-705 Summary: DormandPrince853 integrator leads to revisiting of state events Description: |- See the attached ReappearingEventTest.java. It has two unit tests, which use either the DormandPrince853 or the GraggBulirschStoer integrator, on the same ODE problem. It is a problem starting at time 6.0, with 7 variables, and 1 state event. The state event was previously detected at time 6.0, which is why I start there now. I provide and end time of 10.0. Since I start at the state event, I expect to integrate all the way to the end (10.0). For the GraggBulirschStoer this is what happens (see attached ReappearingEventTest.out). For the DormandPrince853Integerator, it detects a state event and stops integration at 6.000000000000002. I think the problem becomes clear by looking at the output in ReappearingEventTest.out, in particular these lines: {noformat} computeDerivatives: t=6.0 y=[2.0 , 2.0 , 2.0 , 4.0 , 2.0 , 7.0 , 15.0 ] (...) g : t=6.0 y=[1.9999999999999996 , 1.9999999999999996 , 1.9999999999999996 , 4.0 , 1.9999999999999996 , 7.0 , 14.999999999999998 ] (...) final result : t=6.000000000000002 y=[2.0000000000000013 , 2.0000000000000013 , 2.0000000000000013 , 4.000000000000002 , 2.0000000000000013 , 7.000000000000002 , 15.0 ] {noformat} The initial value of the last variable in y, the one that the state event refers to, is 15.0. However, the first time it is given to the g function, the value is 14.999999999999998. This value is less than 15, and more importantly, it is a value from the past (as all functions are increasing), *before* the state event. This makes that the state event re-appears immediately, and integration stops at 6.000000000000002 because of the detected state event. I find it puzzling that for the DormandPrince853Integerator the y array that is given to the first evaluation of the g function, has different values than the y array that is the input to the problem. For GraggBulirschStoer is can be seen that the y arrays have identical values. diff --git a/src/main/java/org/apache/commons/math/ode/nonstiff/ClassicalRungeKuttaStepInterpolator.java b/src/main/java/org/apache/commons/math/ode/nonstiff/ClassicalRungeKuttaStepInterpolator.java index 42796c7..baf236a 100644 --- a/src/main/java/org/apache/commons/math/ode/nonstiff/ClassicalRungeKuttaStepInterpolator.java +++ b/src/main/java/org/apache/commons/math/ode/nonstiff/ClassicalRungeKuttaStepInterpolator.java @@ -48,7 +48,7 @@ class ClassicalRungeKuttaStepInterpolator extends RungeKuttaStepInterpolator { /** Serializable version identifier. */ - private static final long serialVersionUID = 20110928L; + private static final long serialVersionUID = 20111120L; /** Simple constructor. * This constructor builds an instance that is not usable yet, the diff --git a/src/main/java/org/apache/commons/math/ode/nonstiff/DormandPrince54StepInterpolator.java b/src/main/java/org/apache/commons/math/ode/nonstiff/DormandPrince54StepInterpolator.java index af32c4c..1dac8ab 100644 --- a/src/main/java/org/apache/commons/math/ode/nonstiff/DormandPrince54StepInterpolator.java +++ b/src/main/java/org/apache/commons/math/ode/nonstiff/DormandPrince54StepInterpolator.java @@ -72,7 +72,7 @@ class DormandPrince54StepInterpolator private static final double D6 = 69997945.0 / 29380423.0; /** Serializable version identifier. */ - private static final long serialVersionUID = 20110928L; + private static final long serialVersionUID = 20111120L; /** First vector for interpolation. */ private double[] v1; diff --git a/src/main/java/org/apache/commons/math/ode/nonstiff/DormandPrince853StepInterpolator.java b/src/main/java/org/apache/commons/math/ode/nonstiff/DormandPrince853StepInterpolator.java index 91442bb..64dd7d7 100644 --- a/src/main/java/org/apache/commons/math/ode/nonstiff/DormandPrince853StepInterpolator.java +++ b/src/main/java/org/apache/commons/math/ode/nonstiff/DormandPrince853StepInterpolator.java @@ -39,7 +39,7 @@ class DormandPrince853StepInterpolator extends RungeKuttaStepInterpolator { /** Serializable version identifier. */ - private static final long serialVersionUID = 20110928L; + private static final long serialVersionUID = 20111120L; /** Propagation weights, element 1. */ private static final double B_01 = 104257.0 / 1920240.0; @@ -368,18 +368,34 @@ class DormandPrince853StepInterpolator final double dot5 = theta2 * (3 + theta * (-12 + theta * (15 - 6 * theta))); final double dot6 = theta2 * theta * (4 + theta * (-15 + theta * (18 - 7 * theta))); - for (int i = 0; i < interpolatedState.length; ++i) { - interpolatedState[i] = currentState[i] - - oneMinusThetaH * (v[0][i] - - theta * (v[1][i] + - theta * (v[2][i] + - eta * (v[3][i] + - theta * (v[4][i] + - eta * (v[5][i] + - theta * (v[6][i]))))))); - interpolatedDerivatives[i] = v[0][i] + dot1 * v[1][i] + dot2 * v[2][i] + - dot3 * v[3][i] + dot4 * v[4][i] + - dot5 * v[5][i] + dot6 * v[6][i]; + if ((previousState != null) && (theta <= 0.5)) { + for (int i = 0; i < interpolatedState.length; ++i) { + interpolatedState[i] = previousState[i] + + theta * h * (v[0][i] + + eta * (v[1][i] + + theta * (v[2][i] + + eta * (v[3][i] + + theta * (v[4][i] + + eta * (v[5][i] + + theta * (v[6][i]))))))); + interpolatedDerivatives[i] = v[0][i] + dot1 * v[1][i] + dot2 * v[2][i] + + dot3 * v[3][i] + dot4 * v[4][i] + + dot5 * v[5][i] + dot6 * v[6][i]; + } + } else { + for (int i = 0; i < interpolatedState.length; ++i) { + interpolatedState[i] = currentState[i] - + oneMinusThetaH * (v[0][i] - + theta * (v[1][i] + + theta * (v[2][i] + + eta * (v[3][i] + + theta * (v[4][i] + + eta * (v[5][i] + + theta * (v[6][i]))))))); + interpolatedDerivatives[i] = v[0][i] + dot1 * v[1][i] + dot2 * v[2][i] + + dot3 * v[3][i] + dot4 * v[4][i] + + dot5 * v[5][i] + dot6 * v[6][i]; + } } } diff --git a/src/main/java/org/apache/commons/math/ode/nonstiff/EmbeddedRungeKuttaIntegrator.java b/src/main/java/org/apache/commons/math/ode/nonstiff/EmbeddedRungeKuttaIntegrator.java index 87fd716..34d2c00 100644 --- a/src/main/java/org/apache/commons/math/ode/nonstiff/EmbeddedRungeKuttaIntegrator.java +++ b/src/main/java/org/apache/commons/math/ode/nonstiff/EmbeddedRungeKuttaIntegrator.java @@ -202,7 +202,7 @@ public abstract class EmbeddedRungeKuttaIntegrator final double[] y = y0.clone(); final int stages = c.length + 1; final double[][] yDotK = new double[stages][y.length]; - final double[] yTmp = new double[y.length]; + final double[] yTmp = y0.clone(); final double[] yDotTmp = new double[y.length]; // set up an interpolator sharing the integrator arrays @@ -294,6 +294,7 @@ public abstract class EmbeddedRungeKuttaIntegrator System.arraycopy(yTmp, 0, y, 0, y0.length); System.arraycopy(yDotK[stages - 1], 0, yDotTmp, 0, y0.length); stepStart = acceptStep(interpolator, y, yDotTmp, t); + System.arraycopy(y, 0, yTmp, 0, y.length); if (!isLastStep) { diff --git a/src/main/java/org/apache/commons/math/ode/nonstiff/EulerStepInterpolator.java b/src/main/java/org/apache/commons/math/ode/nonstiff/EulerStepInterpolator.java index 99a604f..d2807a4 100644 --- a/src/main/java/org/apache/commons/math/ode/nonstiff/EulerStepInterpolator.java +++ b/src/main/java/org/apache/commons/math/ode/nonstiff/EulerStepInterpolator.java @@ -42,7 +42,7 @@ class EulerStepInterpolator extends RungeKuttaStepInterpolator { /** Serializable version identifier. */ - private static final long serialVersionUID = 20110928L; + private static final long serialVersionUID = 20111120L; /** Simple constructor. * This constructor builds an instance that is not usable yet, the diff --git a/src/main/java/org/apache/commons/math/ode/nonstiff/GillStepInterpolator.java b/src/main/java/org/apache/commons/math/ode/nonstiff/GillStepInterpolator.java index e956b20..5377755 100644 --- a/src/main/java/org/apache/commons/math/ode/nonstiff/GillStepInterpolator.java +++ b/src/main/java/org/apache/commons/math/ode/nonstiff/GillStepInterpolator.java @@ -54,7 +54,7 @@ class GillStepInterpolator private static final double TWO_PLUS_SQRT_2 = 2 + FastMath.sqrt(2.0); /** Serializable version identifier. */ - private static final long serialVersionUID = 20110928L; + private static final long serialVersionUID = 20111120L; /** Simple constructor. * This constructor builds an instance that is not usable yet, the diff --git a/src/main/java/org/apache/commons/math/ode/nonstiff/HighamHall54StepInterpolator.java b/src/main/java/org/apache/commons/math/ode/nonstiff/HighamHall54StepInterpolator.java index ba112d4..b928b53 100644 --- a/src/main/java/org/apache/commons/math/ode/nonstiff/HighamHall54StepInterpolator.java +++ b/src/main/java/org/apache/commons/math/ode/nonstiff/HighamHall54StepInterpolator.java @@ -33,7 +33,7 @@ class HighamHall54StepInterpolator extends RungeKuttaStepInterpolator { /** Serializable version identifier */ - private static final long serialVersionUID = 20110928L; + private static final long serialVersionUID = 20111120L; /** Simple constructor. * This constructor builds an instance that is not usable yet, the diff --git a/src/main/java/org/apache/commons/math/ode/nonstiff/MidpointStepInterpolator.java b/src/main/java/org/apache/commons/math/ode/nonstiff/MidpointStepInterpolator.java index 1c76483..25f77c5 100644 --- a/src/main/java/org/apache/commons/math/ode/nonstiff/MidpointStepInterpolator.java +++ b/src/main/java/org/apache/commons/math/ode/nonstiff/MidpointStepInterpolator.java @@ -44,7 +44,7 @@ class MidpointStepInterpolator extends RungeKuttaStepInterpolator { /** Serializable version identifier */ - private static final long serialVersionUID = 20110928L; + private static final long serialVersionUID = 20111120L; /** Simple constructor. * This constructor builds an instance that is not usable yet, the diff --git a/src/main/java/org/apache/commons/math/ode/nonstiff/RungeKuttaIntegrator.java b/src/main/java/org/apache/commons/math/ode/nonstiff/RungeKuttaIntegrator.java index fb82d0c..c51620c 100644 --- a/src/main/java/org/apache/commons/math/ode/nonstiff/RungeKuttaIntegrator.java +++ b/src/main/java/org/apache/commons/math/ode/nonstiff/RungeKuttaIntegrator.java @@ -107,7 +107,7 @@ public abstract class RungeKuttaIntegrator extends AbstractIntegrator { for (int i = 0; i < stages; ++i) { yDotK [i] = new double[y0.length]; } - final double[] yTmp = new double[y0.length]; + final double[] yTmp = y0.clone(); final double[] yDotTmp = new double[y0.length]; // set up an interpolator sharing the integrator arrays diff --git a/src/main/java/org/apache/commons/math/ode/nonstiff/RungeKuttaStepInterpolator.java b/src/main/java/org/apache/commons/math/ode/nonstiff/RungeKuttaStepInterpolator.java index 987dfb1..55146c3 100644 --- a/src/main/java/org/apache/commons/math/ode/nonstiff/RungeKuttaStepInterpolator.java +++ b/src/main/java/org/apache/commons/math/ode/nonstiff/RungeKuttaStepInterpolator.java @@ -38,6 +38,9 @@ import org.apache.commons.math.ode.sampling.AbstractStepInterpolator; abstract class RungeKuttaStepInterpolator extends AbstractStepInterpolator { + /** Previous state. */ + protected double[] previousState; + /** Slopes at the intermediate points */ protected double[][] yDotK; @@ -55,9 +58,9 @@ abstract class RungeKuttaStepInterpolator * uninitialized model and latter initializing the copy. */ protected RungeKuttaStepInterpolator() { - super(); - yDotK = null; - integrator = null; + previousState = null; + yDotK = null; + integrator = null; } /** Copy constructor. @@ -82,16 +85,16 @@ abstract class RungeKuttaStepInterpolator super(interpolator); if (interpolator.currentState != null) { - final int dimension = currentState.length; + + previousState = interpolator.previousState.clone(); yDotK = new double[interpolator.yDotK.length][]; for (int k = 0; k < interpolator.yDotK.length; ++k) { - yDotK[k] = new double[dimension]; - System.arraycopy(interpolator.yDotK[k], 0, - yDotK[k], 0, dimension); + yDotK[k] = interpolator.yDotK[k].clone(); } } else { + previousState = null; yDotK = null; } @@ -129,12 +132,20 @@ abstract class RungeKuttaStepInterpolator final EquationsMapper primaryMapper, final EquationsMapper[] secondaryMappers) { reinitialize(y, forward, primaryMapper, secondaryMappers); + this.previousState = null; this.yDotK = yDotArray; this.integrator = rkIntegrator; } /** {@inheritDoc} */ @Override + public void shift() { + previousState = currentState.clone(); + super.shift(); + } + + /** {@inheritDoc} */ + @Override public void writeExternal(final ObjectOutput out) throws IOException { @@ -143,6 +154,10 @@ abstract class RungeKuttaStepInterpolator // save the local attributes final int n = (currentState == null) ? -1 : currentState.length; + for (int i = 0; i < n; ++i) { + out.writeDouble(previousState[i]); + } + final int kMax = (yDotK == null) ? -1 : yDotK.length; out.writeInt(kMax); for (int k = 0; k < kMax; ++k) { @@ -165,6 +180,15 @@ abstract class RungeKuttaStepInterpolator // read the local attributes final int n = (currentState == null) ? -1 : currentState.length; + if (n < 0) { + previousState = null; + } else { + previousState = new double[n]; + for (int i = 0; i < n; ++i) { + previousState[i] = in.readDouble(); + } + } + final int kMax = in.readInt(); yDotK = (kMax < 0) ? null : new double[kMax][]; for (int k = 0; k < kMax; ++k) { diff --git a/src/main/java/org/apache/commons/math/ode/nonstiff/ThreeEighthesStepInterpolator.java b/src/main/java/org/apache/commons/math/ode/nonstiff/ThreeEighthesStepInterpolator.java index 731ec44..fdc9d75 100644 --- a/src/main/java/org/apache/commons/math/ode/nonstiff/ThreeEighthesStepInterpolator.java +++ b/src/main/java/org/apache/commons/math/ode/nonstiff/ThreeEighthesStepInterpolator.java @@ -49,7 +49,7 @@ class ThreeEighthesStepInterpolator extends RungeKuttaStepInterpolator { /** Serializable version identifier */ - private static final long serialVersionUID = 20110928L; + private static final long serialVersionUID = 20111120L; /** Simple constructor. * This constructor builds an instance that is not usable yet, the
bugs-dot-jar/commons-math_extracted_diff/developer-patch_bugs-dot-jar_MATH-705_645d642b.diff
bugs-dot-jar_data_MATH-657_97b440fc
--- BugID: MATH-657 Summary: Division by zero Description: 'In class {{Complex}}, division by zero always returns NaN. I think that it should return NaN only when the numerator is also {{ZERO}}, otherwise the result should be {{INF}}. See [here|http://en.wikipedia.org/wiki/Riemann_sphere#Arithmetic_operations]. ' diff --git a/src/main/java/org/apache/commons/math/complex/Complex.java b/src/main/java/org/apache/commons/math/complex/Complex.java index 137765c..dd0b00a 100644 --- a/src/main/java/org/apache/commons/math/complex/Complex.java +++ b/src/main/java/org/apache/commons/math/complex/Complex.java @@ -256,7 +256,8 @@ public class Complex implements FieldElement<Complex>, Serializable { } if (divisor.isZero) { - return isZero ? NaN : INF; + // return isZero ? NaN : INF; // See MATH-657 + return NaN; } if (divisor.isInfinite() && !isInfinite()) { @@ -292,7 +293,8 @@ public class Complex implements FieldElement<Complex>, Serializable { return NaN; } if (divisor == 0d) { - return isZero ? NaN : INF; + // return isZero ? NaN : INF; // See MATH-657 + return NaN; } if (Double.isInfinite(divisor)) { return !isInfinite() ? ZERO : NaN;
bugs-dot-jar/commons-math_extracted_diff/developer-patch_bugs-dot-jar_MATH-657_97b440fc.diff
bugs-dot-jar_data_MATH-344_a0b4b4b7
--- BugID: MATH-344 Summary: Brent solver returns the wrong value if either bracket endpoint is root Description: The solve(final UnivariateRealFunction f, final double min, final double max, final double initial) function returns yMin or yMax if min or max are deemed to be roots, respectively, instead of min or max. diff --git a/src/main/java/org/apache/commons/math/analysis/solvers/BrentSolver.java b/src/main/java/org/apache/commons/math/analysis/solvers/BrentSolver.java index e0cb427..7fc090e 100644 --- a/src/main/java/org/apache/commons/math/analysis/solvers/BrentSolver.java +++ b/src/main/java/org/apache/commons/math/analysis/solvers/BrentSolver.java @@ -112,7 +112,7 @@ public class BrentSolver extends UnivariateRealSolverImpl { // return the first endpoint if it is good enough double yMin = f.value(min); if (Math.abs(yMin) <= functionValueAccuracy) { - setResult(yMin, 0); + setResult(min, 0); return result; } @@ -124,7 +124,7 @@ public class BrentSolver extends UnivariateRealSolverImpl { // return the second endpoint if it is good enough double yMax = f.value(max); if (Math.abs(yMax) <= functionValueAccuracy) { - setResult(yMax, 0); + setResult(max, 0); return result; }
bugs-dot-jar/commons-math_extracted_diff/developer-patch_bugs-dot-jar_MATH-344_a0b4b4b7.diff
bugs-dot-jar_data_MATH-1123_a197ba85
--- BugID: MATH-1123 Summary: NPE in BSPTree#fitToCell() Description: "Hello, \nI faced a NPE using BSPTree#fitToCell() from the SVN trunk. I fixed the problem using a small patch I will attach to the ticket.\n" diff --git a/src/main/java/org/apache/commons/math3/geometry/partitioning/BSPTree.java b/src/main/java/org/apache/commons/math3/geometry/partitioning/BSPTree.java index c81832b..5aec175 100644 --- a/src/main/java/org/apache/commons/math3/geometry/partitioning/BSPTree.java +++ b/src/main/java/org/apache/commons/math3/geometry/partitioning/BSPTree.java @@ -294,7 +294,7 @@ public class BSPTree<S extends Space> { */ private SubHyperplane<S> fitToCell(final SubHyperplane<S> sub) { SubHyperplane<S> s = sub; - for (BSPTree<S> tree = this; tree.parent != null; tree = tree.parent) { + for (BSPTree<S> tree = this; tree.parent != null && s != null; tree = tree.parent) { if (tree == tree.parent.plus) { s = s.split(tree.parent.cut.getHyperplane()).getPlus(); } else {
bugs-dot-jar/commons-math_extracted_diff/developer-patch_bugs-dot-jar_MATH-1123_a197ba85.diff
bugs-dot-jar_data_MATH-546_b6bf8f41
--- BugID: MATH-546 Summary: Truncation issue in KMeansPlusPlusClusterer Description: |- The for loop inside KMeansPlusPlusClusterer.chooseInitialClusters defines a variable int sum = 0; This variable should have type double, rather than int. Using an int causes the method to truncate the distances between points to (square roots of) integers. It's especially bad when the distances between points are typically less than 1. As an aside, in version 2.2, this bug manifested itself by making the clusterer return empty clusters. I wonder if the EmptyClusterStrategy would still be necessary if this bug were fixed. diff --git a/src/main/java/org/apache/commons/math/stat/clustering/KMeansPlusPlusClusterer.java b/src/main/java/org/apache/commons/math/stat/clustering/KMeansPlusPlusClusterer.java index b73ac9d..e09bbc3 100644 --- a/src/main/java/org/apache/commons/math/stat/clustering/KMeansPlusPlusClusterer.java +++ b/src/main/java/org/apache/commons/math/stat/clustering/KMeansPlusPlusClusterer.java @@ -172,7 +172,7 @@ public class KMeansPlusPlusClusterer<T extends Clusterable<T>> { while (resultSet.size() < k) { // For each data point x, compute D(x), the distance between x and // the nearest center that has already been chosen. - int sum = 0; + double sum = 0; for (int i = 0; i < pointSet.size(); i++) { final T p = pointSet.get(i); final Cluster<T> nearest = getNearestCluster(resultSet, p);
bugs-dot-jar/commons-math_extracted_diff/developer-patch_bugs-dot-jar_MATH-546_b6bf8f41.diff
bugs-dot-jar_data_MATH-326_ce185345
--- BugID: MATH-326 Summary: getLInfNorm() uses wrong formula in both ArrayRealVector and OpenMapRealVector (in different ways) Description: "the L_infinity norm of a finite dimensional vector is just the max of the absolute value of its entries.\n\nThe current implementation in ArrayRealVector has a typo:\n\n{code}\n public double getLInfNorm() {\n double max = 0;\n \ for (double a : data) {\n max += Math.max(max, Math.abs(a));\n \ }\n return max;\n }\n{code}\n\nthe += should just be an =.\n\nThere is sadly a unit test assuring us that this is the correct behavior (effectively a regression-only test, not a test for correctness).\n\nWorse, the implementation in OpenMapRealVector is not even positive semi-definite:\n\n{code} \n public double getLInfNorm() {\n double max = 0;\n Iterator iter = entries.iterator();\n \ while (iter.hasNext()) {\n iter.advance();\n max += iter.value();\n }\n return max;\n }\n{code}\n\nI would suggest that this method be moved up to the AbstractRealVector superclass and implemented using the sparseIterator():\n\n{code}\n public double getLInfNorm() {\n double norm = 0;\n Iterator<Entry> it = sparseIterator();\n Entry e;\n while(it.hasNext() && (e = it.next()) != null) {\n norm = Math.max(norm, Math.abs(e.getValue()));\n \ }\n return norm;\n }\n{code}\n\nUnit tests with negative valued vectors would be helpful to check for this kind of thing in the future." diff --git a/src/main/java/org/apache/commons/math/linear/AbstractRealVector.java b/src/main/java/org/apache/commons/math/linear/AbstractRealVector.java index cf103c0..ace4b8d 100644 --- a/src/main/java/org/apache/commons/math/linear/AbstractRealVector.java +++ b/src/main/java/org/apache/commons/math/linear/AbstractRealVector.java @@ -206,6 +206,40 @@ public abstract class AbstractRealVector implements RealVector { } /** {@inheritDoc} */ + public double getNorm() { + double sum = 0; + Iterator<Entry> it = sparseIterator(); + Entry e; + while (it.hasNext() && (e = it.next()) != null) { + final double value = e.getValue(); + sum += value * value; + } + return Math.sqrt(sum); + } + + /** {@inheritDoc} */ + public double getL1Norm() { + double norm = 0; + Iterator<Entry> it = sparseIterator(); + Entry e; + while (it.hasNext() && (e = it.next()) != null) { + norm += Math.abs(e.getValue()); + } + return norm; + } + + /** {@inheritDoc} */ + public double getLInfNorm() { + double norm = 0; + Iterator<Entry> it = sparseIterator(); + Entry e; + while (it.hasNext() && (e = it.next()) != null) { + norm = Math.max(norm, Math.abs(e.getValue())); + } + return norm; + } + + /** {@inheritDoc} */ public double getDistance(double[] v) throws IllegalArgumentException { return getDistance(new ArrayRealVector(v,false)); } diff --git a/src/main/java/org/apache/commons/math/linear/ArrayRealVector.java b/src/main/java/org/apache/commons/math/linear/ArrayRealVector.java index 45c0919..22d0a28 100644 --- a/src/main/java/org/apache/commons/math/linear/ArrayRealVector.java +++ b/src/main/java/org/apache/commons/math/linear/ArrayRealVector.java @@ -694,6 +694,7 @@ public class ArrayRealVector extends AbstractRealVector implements Serializable } /** {@inheritDoc} */ + @Override public double getNorm() { double sum = 0; for (double a : data) { @@ -703,6 +704,7 @@ public class ArrayRealVector extends AbstractRealVector implements Serializable } /** {@inheritDoc} */ + @Override public double getL1Norm() { double sum = 0; for (double a : data) { @@ -712,10 +714,11 @@ public class ArrayRealVector extends AbstractRealVector implements Serializable } /** {@inheritDoc} */ + @Override public double getLInfNorm() { double max = 0; for (double a : data) { - max += Math.max(max, Math.abs(a)); + max = Math.max(max, Math.abs(a)); } return max; } diff --git a/src/main/java/org/apache/commons/math/linear/OpenMapRealVector.java b/src/main/java/org/apache/commons/math/linear/OpenMapRealVector.java index febea7a..eb5be1b 100644 --- a/src/main/java/org/apache/commons/math/linear/OpenMapRealVector.java +++ b/src/main/java/org/apache/commons/math/linear/OpenMapRealVector.java @@ -495,17 +495,6 @@ public class OpenMapRealVector extends AbstractRealVector implements SparseRealV return max; } - /** {@inheritDoc} */ - public double getL1Norm() { - double res = 0; - Iterator iter = entries.iterator(); - while (iter.hasNext()) { - iter.advance(); - res += Math.abs(iter.value()); - } - return res; - } - /** * Optimized method to compute LInfDistance. * @param v The vector to compute from @@ -557,28 +546,6 @@ public class OpenMapRealVector extends AbstractRealVector implements SparseRealV } /** {@inheritDoc} */ - public double getLInfNorm() { - double max = 0; - Iterator iter = entries.iterator(); - while (iter.hasNext()) { - iter.advance(); - max += iter.value(); - } - return max; - } - - /** {@inheritDoc} */ - public double getNorm() { - double res = 0; - Iterator iter = entries.iterator(); - while (iter.hasNext()) { - iter.advance(); - res += iter.value() * iter.value(); - } - return Math.sqrt(res); - } - - /** {@inheritDoc} */ public boolean isInfinite() { boolean infiniteFound = false; Iterator iter = entries.iterator();
bugs-dot-jar/commons-math_extracted_diff/developer-patch_bugs-dot-jar_MATH-326_ce185345.diff
bugs-dot-jar_data_MATH-691_118f0cc0
--- BugID: MATH-691 Summary: Statistics.setVarianceImpl makes getStandardDeviation produce NaN Description: |- Invoking SummaryStatistics.setVarianceImpl(new Variance(true/false) makes getStandardDeviation produce NaN. The code to reproduce it: {code:java} int[] scores = {1, 2, 3, 4}; SummaryStatistics stats = new SummaryStatistics(); stats.setVarianceImpl(new Variance(false)); //use "population variance" for(int i : scores) { stats.addValue(i); } double sd = stats.getStandardDeviation(); System.out.println(sd); {code} A workaround suggested by Mikkel is: {code:java} double sd = FastMath.sqrt(stats.getSecondMoment() / stats.getN()); {code} diff --git a/src/main/java/org/apache/commons/math/stat/descriptive/SummaryStatistics.java b/src/main/java/org/apache/commons/math/stat/descriptive/SummaryStatistics.java index 1203d51..da987cd 100644 --- a/src/main/java/org/apache/commons/math/stat/descriptive/SummaryStatistics.java +++ b/src/main/java/org/apache/commons/math/stat/descriptive/SummaryStatistics.java @@ -155,13 +155,13 @@ public class SummaryStatistics implements StatisticalSummary, Serializable { secondMoment.increment(value); // If mean, variance or geomean have been overridden, // need to increment these - if (!(meanImpl instanceof Mean)) { + if (meanImpl != mean) { meanImpl.increment(value); } - if (!(varianceImpl instanceof Variance)) { + if (varianceImpl != variance) { varianceImpl.increment(value); } - if (!(geoMeanImpl instanceof GeometricMean)) { + if (geoMeanImpl != geoMean) { geoMeanImpl.increment(value); } n++;
bugs-dot-jar/commons-math_extracted_diff/developer-patch_bugs-dot-jar_MATH-691_118f0cc0.diff
bugs-dot-jar_data_MATH-855_350f726c
--- BugID: MATH-855 Summary: '"BrentOptimizer" not always reporting the best point' Description: '{{BrentOptimizer}} (package "o.a.c.m.optimization.univariate") does not check that the point it is going to return is indeed the best one it has encountered. Indeed, the last evaluated point might be slightly worse than the one before last.' diff --git a/src/main/java/org/apache/commons/math3/optimization/univariate/BrentOptimizer.java b/src/main/java/org/apache/commons/math3/optimization/univariate/BrentOptimizer.java index ee2227c..cff5bfd 100644 --- a/src/main/java/org/apache/commons/math3/optimization/univariate/BrentOptimizer.java +++ b/src/main/java/org/apache/commons/math3/optimization/univariate/BrentOptimizer.java @@ -80,12 +80,13 @@ public class BrentOptimizer extends BaseAbstractUnivariateOptimizer { if (abs <= 0) { throw new NotStrictlyPositiveException(abs); } + relativeThreshold = rel; absoluteThreshold = abs; } /** - * The arguments are used implement the original stopping criterion + * The arguments are used for implementing the original stopping criterion * of Brent's algorithm. * {@code abs} and {@code rel} define a tolerance * {@code tol = rel |x| + abs}. {@code rel} should be no smaller than @@ -226,7 +227,7 @@ public class BrentOptimizer extends BaseAbstractUnivariateOptimizer { if (checker != null) { if (checker.converged(iter, previous, current)) { - return current; + return best(current, previous, isMinim); } } @@ -263,9 +264,36 @@ public class BrentOptimizer extends BaseAbstractUnivariateOptimizer { } } } else { // Default termination (Brent's criterion). - return current; + return best(current, previous, isMinim); } ++iter; } } + + /** + * Selects the best of two points. + * + * @param a Point and value. + * @param b Point and value. + * @param isMinim {@code true} if the selected point must be the one with + * the lowest value. + * @return the best point, or {@code null} if {@code a} and {@code b} are + * both {@code null}. + */ + private UnivariatePointValuePair best(UnivariatePointValuePair a, + UnivariatePointValuePair b, + boolean isMinim) { + if (a == null) { + return b; + } + if (b == null) { + return a; + } + + if (isMinim) { + return a.getValue() < b.getValue() ? a : b; + } else { + return a.getValue() > b.getValue() ? a : b; + } + } }
bugs-dot-jar/commons-math_extracted_diff/developer-patch_bugs-dot-jar_MATH-855_350f726c.diff
bugs-dot-jar_data_MATH-414_5fe9b36c
--- BugID: MATH-414 Summary: ConvergenceException in NormalDistributionImpl.cumulativeProbability() Description: "I get a ConvergenceException in NormalDistributionImpl.cumulativeProbability() for very large/small parameters including Infinity, -Infinity.\nFor instance in the following code:\n\n\t@Test\n\tpublic void testCumulative() {\n\t\tfinal NormalDistribution nd = new NormalDistributionImpl();\n\t\tfor (int i = 0; i < 500; i++) {\n\t\t\tfinal double val = Math.exp(i);\n\t\t\ttry {\n\t\t\t\tSystem.out.println(\"val = \" + val + \" cumulative = \" + nd.cumulativeProbability(val));\n\t\t\t} catch (MathException e) {\n\t\t\t\te.printStackTrace();\n\t\t\t\tfail();\n\t\t\t}\n\t\t}\n\t}\n\nIn version 2.0, I get no exception. \n\nMy suggestion is to change in the implementation of cumulativeProbability(double) to catch all ConvergenceException (and return for very large and very small values), not just MaxIterationsExceededException.\n" diff --git a/src/main/java/org/apache/commons/math/distribution/NormalDistributionImpl.java b/src/main/java/org/apache/commons/math/distribution/NormalDistributionImpl.java index 456555b..0d7ce7d 100644 --- a/src/main/java/org/apache/commons/math/distribution/NormalDistributionImpl.java +++ b/src/main/java/org/apache/commons/math/distribution/NormalDistributionImpl.java @@ -114,26 +114,20 @@ public class NormalDistributionImpl extends AbstractContinuousDistribution /** * For this distribution, {@code X}, this method returns {@code P(X < x)}. + * If {@code x}is more than 40 standard deviations from the mean, 0 or 1 is returned, + * as in these cases the actual value is within {@code Double.MIN_VALUE} of 0 or 1. * * @param x Value at which the CDF is evaluated. * @return CDF evaluated at {@code x}. - * @throws MathException if the algorithm fails to converge; unless - * {@code x} is more than 20 standard deviations from the mean, in which - * case the convergence exception is caught and 0 or 1 is returned. + * @throws MathException if the algorithm fails to converge */ public double cumulativeProbability(double x) throws MathException { - try { - return 0.5 * (1.0 + Erf.erf((x - mean) / - (standardDeviation * FastMath.sqrt(2.0)))); - } catch (MaxIterationsExceededException ex) { - if (x < (mean - 20 * standardDeviation)) { // JDK 1.5 blows at 38 - return 0; - } else if (x > (mean + 20 * standardDeviation)) { - return 1; - } else { - throw ex; - } + final double dev = x - mean; + if (FastMath.abs(dev) > 40 * standardDeviation) { + return dev < 0 ? 0.0d : 1.0d; } + return 0.5 * (1.0 + Erf.erf((dev) / + (standardDeviation * FastMath.sqrt(2.0)))); } /**
bugs-dot-jar/commons-math_extracted_diff/developer-patch_bugs-dot-jar_MATH-414_5fe9b36c.diff
bugs-dot-jar_data_MATH-929_cedf0d27
--- BugID: MATH-929 Summary: MultivariateNormalDistribution.density(double[]) returns wrong value when the dimension is odd Description: |- To reproduce: {code} Assert.assertEquals(0.398942280401433, new MultivariateNormalDistribution(new double[]{0}, new double[][]{{1}}).density(new double[]{0}), 1e-15); {code} diff --git a/src/main/java/org/apache/commons/math3/distribution/MultivariateNormalDistribution.java b/src/main/java/org/apache/commons/math3/distribution/MultivariateNormalDistribution.java index 1570681..fd18c28 100644 --- a/src/main/java/org/apache/commons/math3/distribution/MultivariateNormalDistribution.java +++ b/src/main/java/org/apache/commons/math3/distribution/MultivariateNormalDistribution.java @@ -180,7 +180,7 @@ public class MultivariateNormalDistribution throw new DimensionMismatchException(vals.length, dim); } - return FastMath.pow(2 * FastMath.PI, -dim / 2) * + return FastMath.pow(2 * FastMath.PI, -0.5 * dim) * FastMath.pow(covarianceMatrixDeterminant, -0.5) * getExponentTerm(vals); }
bugs-dot-jar/commons-math_extracted_diff/developer-patch_bugs-dot-jar_MATH-929_cedf0d27.diff
bugs-dot-jar_data_MATH-780_dd6cefb0
--- BugID: MATH-780 Summary: BSPTree class and recovery of a Euclidean 3D BRep Description: | New to the work here. Thanks for your efforts on this code. I create a BSPTree from a BoundaryRep (Brep) my test Brep is a cube as represented by a float array containing 8 3D points in(x,y,z) order and an array of indices (12 triplets for the 12 faces of the cube). I construct a BSPMesh() as shown in the code below. I can construct the PolyhedronsSet() but have problems extracting the faces from the BSPTree to reconstruct the BRep. The attached code (BSPMesh2.java) shows that a small change to 1 of the vertex positions causes/corrects the problem. Any ideas? diff --git a/src/main/java/org/apache/commons/math3/geometry/euclidean/twod/PolygonsSet.java b/src/main/java/org/apache/commons/math3/geometry/euclidean/twod/PolygonsSet.java index 6ba72be..add24ac 100644 --- a/src/main/java/org/apache/commons/math3/geometry/euclidean/twod/PolygonsSet.java +++ b/src/main/java/org/apache/commons/math3/geometry/euclidean/twod/PolygonsSet.java @@ -132,7 +132,9 @@ public class PolygonsSet extends AbstractRegion<Euclidean2D, Euclidean1D> { final Vector2D[][] v = getVertices(); if (v.length == 0) { - if ((Boolean) getTree(false).getAttribute()) { + final BSPTree<Euclidean2D> tree = getTree(false); + if (tree.getCut() == null && (Boolean) tree.getAttribute()) { + // the instance covers the whole space setSize(Double.POSITIVE_INFINITY); setBarycenter(Vector2D.NaN); } else {
bugs-dot-jar/commons-math_extracted_diff/developer-patch_bugs-dot-jar_MATH-780_dd6cefb0.diff
bugs-dot-jar_data_MATH-855_ac597cc1
--- BugID: MATH-855 Summary: '"BrentOptimizer" not always reporting the best point' Description: '{{BrentOptimizer}} (package "o.a.c.m.optimization.univariate") does not check that the point it is going to return is indeed the best one it has encountered. Indeed, the last evaluated point might be slightly worse than the one before last.' diff --git a/src/main/java/org/apache/commons/math3/optimization/univariate/BrentOptimizer.java b/src/main/java/org/apache/commons/math3/optimization/univariate/BrentOptimizer.java index cff5bfd..25f2f50 100644 --- a/src/main/java/org/apache/commons/math3/optimization/univariate/BrentOptimizer.java +++ b/src/main/java/org/apache/commons/math3/optimization/univariate/BrentOptimizer.java @@ -24,13 +24,19 @@ import org.apache.commons.math3.optimization.ConvergenceChecker; import org.apache.commons.math3.optimization.GoalType; /** - * Implements Richard Brent's algorithm (from his book "Algorithms for + * For a function defined on some interval {@code (lo, hi)}, this class + * finds an approximation {@code x} to the point at which the function + * attains its minimum. + * It implements Richard Brent's algorithm (from his book "Algorithms for * Minimization without Derivatives", p. 79) for finding minima of real - * univariate functions. This implementation is an adaptation partly - * based on the Python code from SciPy (module "optimize.py" v0.5). - * If the function is defined on some interval {@code (lo, hi)}, then - * this method finds an approximation {@code x} to the point at which - * the function attains its minimum. + * univariate functions. + * <br/> + * This code is an adaptation, partly based on the Python code from SciPy + * (module "optimize.py" v0.5); the original algorithm is also modified + * <ul> + * <li>to use an initial guess provided by the user,</li> + * <li>to ensure that the best point encountered is the one returned.</li> + * </ul> * * @version $Id$ * @since 2.0 @@ -141,6 +147,8 @@ public class BrentOptimizer extends BaseAbstractUnivariateOptimizer { UnivariatePointValuePair previous = null; UnivariatePointValuePair current = new UnivariatePointValuePair(x, isMinim ? fx : -fx); + // Best point encountered so far (which is the initial guess). + UnivariatePointValuePair best = current; int iter = 0; while (true) { @@ -224,10 +232,15 @@ public class BrentOptimizer extends BaseAbstractUnivariateOptimizer { // User-defined convergence checker. previous = current; current = new UnivariatePointValuePair(u, isMinim ? fu : -fu); + best = best(best, + best(current, + previous, + isMinim), + isMinim); if (checker != null) { if (checker.converged(iter, previous, current)) { - return best(current, previous, isMinim); + return best; } } @@ -264,7 +277,11 @@ public class BrentOptimizer extends BaseAbstractUnivariateOptimizer { } } } else { // Default termination (Brent's criterion). - return best(current, previous, isMinim); + return best(best, + best(current, + previous, + isMinim), + isMinim); } ++iter; } @@ -278,7 +295,8 @@ public class BrentOptimizer extends BaseAbstractUnivariateOptimizer { * @param isMinim {@code true} if the selected point must be the one with * the lowest value. * @return the best point, or {@code null} if {@code a} and {@code b} are - * both {@code null}. + * both {@code null}. When {@code a} and {@code b} have the same function + * value, {@code a} is returned. */ private UnivariatePointValuePair best(UnivariatePointValuePair a, UnivariatePointValuePair b, @@ -291,9 +309,9 @@ public class BrentOptimizer extends BaseAbstractUnivariateOptimizer { } if (isMinim) { - return a.getValue() < b.getValue() ? a : b; + return a.getValue() <= b.getValue() ? a : b; } else { - return a.getValue() > b.getValue() ? a : b; + return a.getValue() >= b.getValue() ? a : b; } } }
bugs-dot-jar/commons-math_extracted_diff/developer-patch_bugs-dot-jar_MATH-855_ac597cc1.diff
bugs-dot-jar_data_MATH-828_a49e443c
--- BugID: MATH-828 Summary: Not expected UnboundedSolutionException Description: "SimplexSolver throws UnboundedSolutionException when trying to solve minimization linear programming problem. The number of exception thrown depends on the number of variables.\n\nIn order to see that behavior of SimplexSolver first try to run JUnit test setting a final variable ENTITIES_COUNT = 2 and that will give almost good result and then set it to 15 and you'll get a massive of unbounded exceptions.\nFirst iteration is runned with predefined set of input data with which the Solver gives back an appropriate result.\n\nThe problem itself is well tested by it's authors (mathematicians who I believe know what they developed) using Matlab 10 with no unbounded solutions on the same rules of creatnig random variables values.\n\nWhat is strange to me is the dependence of the number of UnboundedSolutionException exceptions on the number of variables in the problem.\n\nThe problem is formulated as\nmin(1*t + 0*L) (for every r-th subject)\ns.t.\n-q(r) + QL >= 0\nx(r)t - XL >= 0\nL >= 0\nwhere \nr = 1..R, \nL = {l(1), l(2), ..., l(R)} (vector of R rows and 1 column),\nQ - coefficients matrix MxR\nX - coefficients matrix NxR " diff --git a/src/main/java/org/apache/commons/math3/optimization/linear/SimplexSolver.java b/src/main/java/org/apache/commons/math3/optimization/linear/SimplexSolver.java index c2fa14d..dec310b 100644 --- a/src/main/java/org/apache/commons/math3/optimization/linear/SimplexSolver.java +++ b/src/main/java/org/apache/commons/math3/optimization/linear/SimplexSolver.java @@ -116,12 +116,14 @@ public class SimplexSolver extends AbstractLinearOptimizer { // there's a degeneracy as indicated by a tie in the minimum ratio test // 1. check if there's an artificial variable that can be forced out of the basis - for (Integer row : minRatioPositions) { - for (int i = 0; i < tableau.getNumArtificialVariables(); i++) { - int column = i + tableau.getArtificialVariableOffset(); - final double entry = tableau.getEntry(row, column); - if (Precision.equals(entry, 1d, maxUlps) && row.equals(tableau.getBasicRow(column))) { - return row; + if (tableau.getNumArtificialVariables() > 0) { + for (Integer row : minRatioPositions) { + for (int i = 0; i < tableau.getNumArtificialVariables(); i++) { + int column = i + tableau.getArtificialVariableOffset(); + final double entry = tableau.getEntry(row, column); + if (Precision.equals(entry, 1d, maxUlps) && row.equals(tableau.getBasicRow(column))) { + return row; + } } } } @@ -131,20 +133,26 @@ public class SimplexSolver extends AbstractLinearOptimizer { // // see http://www.stanford.edu/class/msande310/blandrule.pdf // see http://en.wikipedia.org/wiki/Bland%27s_rule (not equivalent to the above paper) - Integer minRow = null; - int minIndex = tableau.getWidth(); - for (Integer row : minRatioPositions) { - for (int i = tableau.getNumObjectiveFunctions(); i < tableau.getWidth() - 1 && minRow != row; i++) { - if (row == tableau.getBasicRow(i)) { - if (i < minIndex) { - minIndex = i; - minRow = row; + // + // Additional heuristic: if we did not get a solution after half of maxIterations + // revert to the simple case of just returning the top-most row + // This heuristic is based on empirical data gathered while investigating MATH-828. + if (getIterations() < getMaxIterations() / 2) { + Integer minRow = null; + int minIndex = tableau.getWidth(); + for (Integer row : minRatioPositions) { + int i = tableau.getNumObjectiveFunctions(); + for (; i < tableau.getWidth() - 1 && minRow != row; i++) { + if (row == tableau.getBasicRow(i)) { + if (i < minIndex) { + minIndex = i; + minRow = row; + } } } } + return minRow; } - - return minRow; } return minRatioPositions.get(0); }
bugs-dot-jar/commons-math_extracted_diff/developer-patch_bugs-dot-jar_MATH-828_a49e443c.diff
bugs-dot-jar_data_MATH-519_26a61077
--- BugID: MATH-519 Summary: GaussianFitter Unexpectedly Throws NotStrictlyPositiveException Description: "Running the following:\n\n \tdouble[] observations = \n \t{ \n \ \t\t\t1.1143831578403364E-29, \n \t\t\t 4.95281403484594E-28, \n \t\t\t 1.1171347211930288E-26, \n \t\t\t 1.7044813962636277E-25, \n \t\t\t 1.9784716574832164E-24, \n \t\t\t 1.8630236407866774E-23, \n \t\t\t 1.4820532905097742E-22, \n \t\t\t 1.0241963854632831E-21, \n \t\t\t 6.275077366673128E-21, \n \t\t\t 3.461808994532493E-20, \n \t\t\t 1.7407124684715706E-19, \n \t\t\t 8.056687953553974E-19, \n \t\t\t 3.460193945992071E-18, \n \t\t\t 1.3883326374011525E-17, \n \t\t\t 5.233894983671116E-17, \n \t\t\t 1.8630791465263745E-16, \n \t\t\t 6.288759227922111E-16, \n \t\t\t 2.0204433920597856E-15, \n \t\t\t 6.198768938576155E-15, \n \t\t\t 1.821419346860626E-14, \n \t\t\t 5.139176445538471E-14, \n \t\t\t 1.3956427429045787E-13, \n \t\t\t 3.655705706448139E-13, \n \t\t\t 9.253753324779779E-13, \n \t\t\t 2.267636001476696E-12, \n \t\t\t 5.3880460095836855E-12, \n \t\t\t 1.2431632654852931E-11 \n \t};\n \ \n \tGaussianFitter g = \n \t\tnew GaussianFitter(new LevenbergMarquardtOptimizer());\n \ \t\n \tfor (int index = 0; index < 27; index++)\n \t{\n \t\tg.addObservedPoint(index, observations[index]);\n \t}\n \tg.fit();\n\nResults in:\n\norg.apache.commons.math.exception.NotStrictlyPositiveException: -1.277 is smaller than, or equal to, the minimum (0)\n\tat org.apache.commons.math.analysis.function.Gaussian$Parametric.validateParameters(Gaussian.java:184)\n\tat org.apache.commons.math.analysis.function.Gaussian$Parametric.value(Gaussian.java:129)\n\n\nI'm guessing the initial guess for sigma is off. " diff --git a/src/main/java/org/apache/commons/math/optimization/fitting/GaussianFitter.java b/src/main/java/org/apache/commons/math/optimization/fitting/GaussianFitter.java index 725b5ca..e1b54f4 100644 --- a/src/main/java/org/apache/commons/math/optimization/fitting/GaussianFitter.java +++ b/src/main/java/org/apache/commons/math/optimization/fitting/GaussianFitter.java @@ -21,10 +21,12 @@ import java.util.Arrays; import java.util.Comparator; import org.apache.commons.math.analysis.function.Gaussian; +import org.apache.commons.math.analysis.ParametricUnivariateRealFunction; import org.apache.commons.math.exception.NullArgumentException; import org.apache.commons.math.exception.NumberIsTooSmallException; import org.apache.commons.math.exception.OutOfRangeException; import org.apache.commons.math.exception.ZeroException; +import org.apache.commons.math.exception.NotStrictlyPositiveException; import org.apache.commons.math.exception.util.LocalizedFormats; import org.apache.commons.math.optimization.DifferentiableMultivariateVectorialOptimizer; import org.apache.commons.math.optimization.fitting.CurveFitter; @@ -57,29 +59,66 @@ import org.apache.commons.math.optimization.fitting.WeightedObservedPoint; * @version $Revision$ $Date$ */ public class GaussianFitter extends CurveFitter { - /** * Constructs an instance using the specified optimizer. * - * @param optimizer optimizer to use for the fitting + * @param optimizer Optimizer to use for the fitting. */ public GaussianFitter(DifferentiableMultivariateVectorialOptimizer optimizer) { - super(optimizer);; + super(optimizer); } + /** + * Fits a Gaussian function to the observed points. + * + * @param initialGuess First guess values in the following order: + * <ul> + * <li>Norm</li> + * <li>Mean</li> + * <li>Sigma</li> + * </ul> + * @return the parameters of the Gaussian function that best fits the + * observed points (in the same order as above). + */ + public double[] fit(double[] initialGuess) { + final ParametricUnivariateRealFunction f = new ParametricUnivariateRealFunction() { + private final ParametricUnivariateRealFunction g = new Gaussian.Parametric(); + + public double value(double x, double[] p) { + double v = Double.POSITIVE_INFINITY; + try { + v = g.value(x, p); + } catch (NotStrictlyPositiveException e) { + // Do nothing. + } + return v; + } + + public double[] gradient(double x, double[] p) { + double[] v = { Double.POSITIVE_INFINITY, + Double.POSITIVE_INFINITY, + Double.POSITIVE_INFINITY }; + try { + v = g.gradient(x, p); + } catch (NotStrictlyPositiveException e) { + // Do nothing. + } + return v; + } + }; + + return fit(f, initialGuess); + } /** - * Fits Gaussian function to the observed points. - * It will call the base class - * {@link CurveFitter#fit( - * org.apache.commons.math.analysis.ParametricUnivariateRealFunction, - * double[]) fit} method. + * Fits a Gaussian function to the observed points. * - * @return the Gaussian function that best fits the observed points. + * @return the parameters of the Gaussian function that best fits the + * observed points (in the same order as above). */ public double[] fit() { - return fit(new Gaussian.Parametric(), - (new ParameterGuesser(getObservations())).guess()); + final double[] guess = (new ParameterGuesser(getObservations())).guess(); + return fit(guess); } /** @@ -90,7 +129,6 @@ public class GaussianFitter extends CurveFitter { public static class ParameterGuesser { /** Observed points. */ private final WeightedObservedPoint[] observations; - /** Resulting guessed parameters. */ private double[] parameters; @@ -112,7 +150,7 @@ public class GaussianFitter extends CurveFitter { /** * Guesses the parameters based on the observed points. * - * @return guessed parameters array <code>{norm, mean, sigma}</code> + * @return the guessed parameters: norm, mean and sigma. */ public double[] guess() { if (parameters == null) { @@ -124,15 +162,13 @@ public class GaussianFitter extends CurveFitter { /** * Guesses the parameters based on the specified observed points. * - * @param points observed points upon which should base guess - * - * @return guessed parameters array <code>{norm, mean, sigma}</code> + * @param points Observed points upon which should base guess. + * @return the guessed parameters: norm, mean and sigma. */ private double[] basicGuess(WeightedObservedPoint[] points) { Arrays.sort(points, createWeightedObservedPointComparator()); double[] params = new double[3]; - int maxYIdx = findMaxY(points); params[0] = points[maxYIdx].getY(); params[1] = points[maxYIdx].getX(); @@ -154,9 +190,8 @@ public class GaussianFitter extends CurveFitter { /** * Finds index of point in specified points with the largest Y. * - * @param points points to search - * - * @return index in specified points array + * @param points Points to search. + * @return the index in specified points array. */ private int findMaxY(WeightedObservedPoint[] points) { int maxYIdx = 0; @@ -169,20 +204,18 @@ public class GaussianFitter extends CurveFitter { } /** - * Interpolates using the specified points to determine X at the specified - * Y. - * - * @param points points to use for interpolation - * @param startIdx index within points from which to start search for - * interpolation bounds points - * @param idxStep index step for search for interpolation bounds points - * @param y Y value for which X should be determined + * Interpolates using the specified points to determine X at the + * specified Y. * - * @return value of X at the specified Y - * - * @throws IllegalArgumentException if idxStep is 0 - * @throws OutOfRangeException if specified <code>y</code> is not within the - * range of the specified <code>points</code> + * @param points Points to use for interpolation. + * @param startIdx Index within points from which to start search for + * interpolation bounds points. + * @param idxStep Index step for search for interpolation bounds points. + * @param y Y value for which X should be determined. + * @return the value of X at the specified Y. + * @throws ZeroException if {@code idxStep} is 0. + * @throws OutOfRangeException if specified {@code y} is not within the + * range of the specified {@code points}. */ private double interpolateXAtY(WeightedObservedPoint[] points, int startIdx, int idxStep, double y) @@ -208,18 +241,16 @@ public class GaussianFitter extends CurveFitter { * Gets the two bounding interpolation points from the specified points * suitable for determining X at the specified Y. * - * @param points points to use for interpolation - * @param startIdx index within points from which to start search for - * interpolation bounds points - * @param idxStep index step for search for interpolation bounds points - * @param y Y value for which X should be determined - * - * @return array containing two points suitable for determining X at the - * specified Y - * - * @throws IllegalArgumentException if idxStep is 0 - * @throws OutOfRangeException if specified <code>y</code> is not within the - * range of the specified <code>points</code> + * @param points Points to use for interpolation. + * @param startIdx Index within points from which to start search for + * interpolation bounds points. + * @param idxStep Index step for search for interpolation bounds points. + * @param y Y value for which X should be determined. + * @return the array containing two points suitable for determining X at + * the specified Y. + * @throws ZeroException if {@code idxStep} is 0. + * @throws OutOfRangeException if specified {@code y} is not within the + * range of the specified {@code points}. */ private WeightedObservedPoint[] getInterpolationPointsForY(WeightedObservedPoint[] points, int startIdx, int idxStep, double y) @@ -244,19 +275,17 @@ public class GaussianFitter extends CurveFitter { maxY = Math.max(maxY, point.getY()); } throw new OutOfRangeException(y, minY, maxY); - } /** * Determines whether a value is between two other values. * - * @param value value to determine whether is between <code>boundary1</code> - * and <code>boundary2</code> - * @param boundary1 one end of the range - * @param boundary2 other end of the range - * - * @return true if <code>value</code> is between <code>boundary1</code> and - * <code>boundary2</code> (inclusive); false otherwise + * @param value Value to determine whether is between {@code boundary1} + * and {@code boundary2}. + * @param boundary1 One end of the range. + * @param boundary2 Other end of the range. + * @return {@code true} if {@code value} is between {@code boundary1} and + * {@code boundary2} (inclusive), {@code false} otherwise. */ private boolean isBetween(double value, double boundary1, double boundary2) { return (value >= boundary1 && value <= boundary2) || @@ -264,10 +293,10 @@ public class GaussianFitter extends CurveFitter { } /** - * Factory method creating <code>Comparator</code> for comparing - * <code>WeightedObservedPoint</code> instances. + * Factory method creating {@code Comparator} for comparing + * {@code WeightedObservedPoint} instances. * - * @return new <code>Comparator</code> instance + * @return the new {@code Comparator} instance. */ private Comparator<WeightedObservedPoint> createWeightedObservedPointComparator() { return new Comparator<WeightedObservedPoint>() {
bugs-dot-jar/commons-math_extracted_diff/developer-patch_bugs-dot-jar_MATH-519_26a61077.diff
bugs-dot-jar_data_MATH-867_bfbb156d
--- BugID: MATH-867 Summary: 'CMAESOptimizer with bounds fits finely near lower bound and coarsely near upper bound. ' Description: When fitting with bounds, the CMAESOptimizer fits finely near the lower bound and coarsely near the upper bound. This is because it internally maps the fitted parameter range into the interval [0,1]. The unit of least precision (ulp) between floating point numbers is much smaller near zero than near one. Thus, fits have much better resolution near the lower bound (which is mapped to zero) than the upper bound (which is mapped to one). I will attach a example program to demonstrate. diff --git a/src/main/java/org/apache/commons/math3/optimization/direct/CMAESOptimizer.java b/src/main/java/org/apache/commons/math3/optimization/direct/CMAESOptimizer.java index 866c8fd..388d1df 100644 --- a/src/main/java/org/apache/commons/math3/optimization/direct/CMAESOptimizer.java +++ b/src/main/java/org/apache/commons/math3/optimization/direct/CMAESOptimizer.java @@ -123,13 +123,11 @@ public class CMAESOptimizer private boolean isActiveCMA; /** * Determines how often a new random offspring is generated in case it is - * not feasible / beyond the defined limits, default is 0. Only relevant if - * boundaries != null. + * not feasible / beyond the defined limits, default is 0. */ private int checkFeasableCount; /** - * Lower and upper boundaries of the objective variables. boundaries == null - * means no boundaries. + * Lower and upper boundaries of the objective variables. */ private double[][] boundaries; /** @@ -357,7 +355,7 @@ public class CMAESOptimizer // -------------------- Initialization -------------------------------- isMinimize = getGoalType().equals(GoalType.MINIMIZE); final FitnessFunction fitfun = new FitnessFunction(); - final double[] guess = fitfun.encode(getStartPoint()); + final double[] guess = getStartPoint(); // number of objective variables/problem dimension dimension = guess.length; initializeCMA(guess); @@ -422,7 +420,7 @@ public class CMAESOptimizer bestValue = bestFitness; lastResult = optimum; optimum = new PointValuePair( - fitfun.repairAndDecode(bestArx.getColumn(0)), + fitfun.repair(bestArx.getColumn(0)), isMinimize ? bestFitness : -bestFitness); if (getConvergenceChecker() != null && lastResult != null) { if (getConvergenceChecker().converged(iterations, optimum, lastResult)) { @@ -506,55 +504,10 @@ public class CMAESOptimizer final double[] lB = getLowerBound(); final double[] uB = getUpperBound(); - // Checks whether there is at least one finite bound value. - boolean hasFiniteBounds = false; - for (int i = 0; i < lB.length; i++) { - if (!Double.isInfinite(lB[i]) || - !Double.isInfinite(uB[i])) { - hasFiniteBounds = true; - break; - } - } - // Checks whether there is at least one infinite bound value. - boolean hasInfiniteBounds = false; - if (hasFiniteBounds) { - for (int i = 0; i < lB.length; i++) { - if (Double.isInfinite(lB[i]) || - Double.isInfinite(uB[i])) { - hasInfiniteBounds = true; - break; - } - } - - if (hasInfiniteBounds) { - // If there is at least one finite bound, none can be infinite, - // because mixed cases are not supported by the current code. - throw new MathUnsupportedOperationException(); - } else { - // Convert API to internal handling of boundaries. - boundaries = new double[2][]; - boundaries[0] = lB; - boundaries[1] = uB; - - // Abort early if the normalization will overflow (cf. "encode" method). - for (int i = 0; i < lB.length; i++) { - if (Double.isInfinite(boundaries[1][i] - boundaries[0][i])) { - final double max = Double.MAX_VALUE + boundaries[0][i]; - final NumberIsTooLargeException e - = new NumberIsTooLargeException(boundaries[1][i], - max, - true); - e.getContext().addMessage(LocalizedFormats.OVERFLOW); - e.getContext().addMessage(LocalizedFormats.INDEX, i); - - throw e; - } - } - } - } else { - // Convert API to internal handling of boundaries. - boundaries = null; - } + // Convert API to internal handling of boundaries. + boundaries = new double[2][]; + boundaries[0] = lB; + boundaries[1] = uB; if (inputSigma != null) { if (inputSigma.length != init.length) { @@ -564,10 +517,8 @@ public class CMAESOptimizer if (inputSigma[i] < 0) { throw new NotPositiveException(inputSigma[i]); } - if (boundaries != null) { - if (inputSigma[i] > boundaries[1][i] - boundaries[0][i]) { - throw new OutOfRangeException(inputSigma[i], 0, boundaries[1][i] - boundaries[0][i]); - } + if (inputSigma[i] > boundaries[1][i] - boundaries[0][i]) { + throw new OutOfRangeException(inputSigma[i], 0, boundaries[1][i] - boundaries[0][i]); } } } @@ -585,8 +536,7 @@ public class CMAESOptimizer // initialize sigma double[][] sigmaArray = new double[guess.length][1]; for (int i = 0; i < guess.length; i++) { - final double range = (boundaries == null) ? 1.0 : boundaries[1][i] - boundaries[0][i]; - sigmaArray[i][0] = ((inputSigma == null) ? 0.3 : inputSigma[i]) / range; + sigmaArray[i][0] = inputSigma == null ? 0.3 : inputSigma[i]; } RealMatrix insigma = new Array2DRowRealMatrix(sigmaArray, false); sigma = max(insigma); // overall standard deviation @@ -919,61 +869,19 @@ public class CMAESOptimizer } /** - * @param x Original objective variables. - * @return the normalized objective variables. - */ - public double[] encode(final double[] x) { - if (boundaries == null) { - return x; - } - double[] res = new double[x.length]; - for (int i = 0; i < x.length; i++) { - double diff = boundaries[1][i] - boundaries[0][i]; - res[i] = x[i] / diff; - } - return res; - } - - /** - * @param x Normalized objective variables. - * @return the original objective variables, possibly repaired. - */ - public double[] repairAndDecode(final double[] x) { - return boundaries != null && isRepairMode ? - decode(repair(x)) : - decode(x); - } - - /** - * @param x Normalized objective variables. - * @return the original objective variables. - */ - public double[] decode(final double[] x) { - if (boundaries == null) { - return x; - } - double[] res = new double[x.length]; - for (int i = 0; i < x.length; i++) { - double diff = boundaries[1][i] - boundaries[0][i]; - res[i] = diff * x[i]; - } - return res; - } - - /** * @param point Normalized objective variables. * @return the objective value + penalty for violated bounds. */ public double value(final double[] point) { double value; - if (boundaries != null && isRepairMode) { + if (isRepairMode) { double[] repaired = repair(point); value = CMAESOptimizer.this - .computeObjectiveValue(decode(repaired)) + + .computeObjectiveValue(repaired) + penalty(point, repaired); } else { value = CMAESOptimizer.this - .computeObjectiveValue(decode(point)); + .computeObjectiveValue(point); } return isMinimize ? value : -value; } @@ -983,18 +891,11 @@ public class CMAESOptimizer * @return {@code true} if in bounds. */ public boolean isFeasible(final double[] x) { - if (boundaries == null) { - return true; - } - - final double[] bLoEnc = encode(boundaries[0]); - final double[] bHiEnc = encode(boundaries[1]); - for (int i = 0; i < x.length; i++) { - if (x[i] < bLoEnc[i]) { + if (x[i] < boundaries[0][i]) { return false; } - if (x[i] > bHiEnc[i]) { + if (x[i] > boundaries[1][i]) { return false; } } @@ -1013,12 +914,12 @@ public class CMAESOptimizer * @return the repaired objective variables - all in bounds. */ private double[] repair(final double[] x) { - double[] repaired = new double[x.length]; + final double[] repaired = new double[x.length]; for (int i = 0; i < x.length; i++) { - if (x[i] < 0) { - repaired[i] = 0; - } else if (x[i] > 1.0) { - repaired[i] = 1.0; + if (x[i] < boundaries[0][i]) { + repaired[i] = boundaries[0][i]; + } else if (x[i] > boundaries[1][i]) { + repaired[i] = boundaries[1][i]; } else { repaired[i] = x[i]; }
bugs-dot-jar/commons-math_extracted_diff/developer-patch_bugs-dot-jar_MATH-867_bfbb156d.diff
bugs-dot-jar_data_MATH-395_962315ba
--- BugID: MATH-395 Summary: Bugs in "BrentOptimizer" Description: | I apologize for having provided a buggy implementation of Brent's optimization algorithm (class "BrentOptimizer" in package "optimization.univariate"). The unit tests didn't show that there was something wrong, although (from the "changes.xml" file) I discovered that, at the time, Luc had noticed something weird in the implementation's behaviour. Comparing with an implementation in Python, I could figure out the fixes. I'll modify "BrentOptimizer" and add a test. I also propose to change the name of the unit test class from "BrentMinimizerTest" to "BrentOptimizerTest". diff --git a/src/main/java/org/apache/commons/math/ConvergingAlgorithmImpl.java b/src/main/java/org/apache/commons/math/ConvergingAlgorithmImpl.java index 883578b..0c4eabe 100644 --- a/src/main/java/org/apache/commons/math/ConvergingAlgorithmImpl.java +++ b/src/main/java/org/apache/commons/math/ConvergingAlgorithmImpl.java @@ -139,14 +139,14 @@ public abstract class ConvergingAlgorithmImpl implements ConvergingAlgorithm { /** * Increment the iterations counter by 1. * - * @throws OptimizationException if the maximal number + * @throws MaxIterationsExceededException if the maximal number * of iterations is exceeded. * @since 2.2 */ protected void incrementIterationsCounter() - throws ConvergenceException { + throws MaxIterationsExceededException { if (++iterationCount > maximalIterationCount) { - throw new ConvergenceException(new MaxIterationsExceededException(maximalIterationCount)); + throw new MaxIterationsExceededException(maximalIterationCount); } } } diff --git a/src/main/java/org/apache/commons/math/optimization/univariate/AbstractUnivariateRealOptimizer.java b/src/main/java/org/apache/commons/math/optimization/univariate/AbstractUnivariateRealOptimizer.java index d312243..c6eeb53 100644 --- a/src/main/java/org/apache/commons/math/optimization/univariate/AbstractUnivariateRealOptimizer.java +++ b/src/main/java/org/apache/commons/math/optimization/univariate/AbstractUnivariateRealOptimizer.java @@ -260,5 +260,6 @@ public abstract class AbstractUnivariateRealOptimizer * * @return the optimum. */ - protected abstract double doOptimize(); + protected abstract double doOptimize() + throws MaxIterationsExceededException, FunctionEvaluationException; } diff --git a/src/main/java/org/apache/commons/math/optimization/univariate/BrentOptimizer.java b/src/main/java/org/apache/commons/math/optimization/univariate/BrentOptimizer.java index 62f2fcb..46c4afa 100644 --- a/src/main/java/org/apache/commons/math/optimization/univariate/BrentOptimizer.java +++ b/src/main/java/org/apache/commons/math/optimization/univariate/BrentOptimizer.java @@ -41,39 +41,37 @@ public class BrentOptimizer extends AbstractUnivariateRealOptimizer { * Construct a solver. */ public BrentOptimizer() { - super(100, 1E-10); + setMaxEvaluations(1000); + setMaximalIterationCount(100); + setAbsoluteAccuracy(1e-11); + setRelativeAccuracy(1e-9); } - /** {@inheritDoc} */ - public double optimize(final UnivariateRealFunction f, final GoalType goalType, - final double min, final double max, final double startValue) + /** + * Perform the optimization. + * + * @return the optimum. + */ + protected double doOptimize() throws MaxIterationsExceededException, FunctionEvaluationException { - clearResult(); - return localMin(f, goalType, min, startValue, max, + return localMin(getGoalType() == GoalType.MINIMIZE, + getMin(), getStartValue(), getMax(), getRelativeAccuracy(), getAbsoluteAccuracy()); } - /** {@inheritDoc} */ - public double optimize(final UnivariateRealFunction f, final GoalType goalType, - final double min, final double max) - throws MaxIterationsExceededException, FunctionEvaluationException { - return optimize(f, goalType, min, max, min + GOLDEN_SECTION * (max - min)); - } - /** - * Find the minimum of the function {@code f} within the interval {@code (a, b)}. + * Find the minimum of the function within the interval {@code (lo, hi)}. * - * If the function {@code f} is defined on the interval {@code (a, b)}, then - * this method finds an approximation {@code x} to the point at which {@code f} - * attains its minimum.<br/> - * {@code t} and {@code eps} define a tolerance {@code tol = eps |x| + t} and - * {@code f} is never evaluated at two points closer together than {@code tol}. - * {@code eps} should be no smaller than <em>2 macheps</em> and preferable not - * much less than <em>sqrt(macheps)</em>, where <em>macheps</em> is the relative - * machine precision. {@code t} should be positive. - * @param f the function to solve. - * @param goalType type of optimization goal: either {@link GoalType#MAXIMIZE} - * or {@link GoalType#MINIMIZE}. + * If the function is defined on the interval {@code (lo, hi)}, then + * this method finds an approximation {@code x} to the point at which + * the function attains its minimum.<br/> + * {@code t} and {@code eps} define a tolerance {@code tol = eps |x| + t} + * and the function is never evaluated at two points closer together than + * {@code tol}. {@code eps} should be no smaller than <em>2 macheps</em> and + * preferable not much less than <em>sqrt(macheps)</em>, where + * <em>macheps</em> is the relative machine precision. {@code t} should be + * positive. + * @param isMinim {@code true} when minimizing the function. * @param lo Lower bound of the interval. * @param mid Point inside the interval {@code [lo, hi]}. * @param hi Higher bound of the interval. @@ -85,8 +83,7 @@ public class BrentOptimizer extends AbstractUnivariateRealOptimizer { * @throws FunctionEvaluationException if an error occurs evaluating * the function. */ - private double localMin(UnivariateRealFunction f, - GoalType goalType, + private double localMin(boolean isMinim, double lo, double mid, double hi, double eps, double t) throws MaxIterationsExceededException, FunctionEvaluationException { @@ -108,16 +105,16 @@ public class BrentOptimizer extends AbstractUnivariateRealOptimizer { double x = mid; double v = x; double w = x; + double d = 0; double e = 0; - double fx = computeObjectiveValue(f, x); - if (goalType == GoalType.MAXIMIZE) { + double fx = computeObjectiveValue(x); + if (!isMinim) { fx = -fx; } double fv = fx; double fw = fx; - int count = 0; - while (count < maximalIterationCount) { + while (true) { double m = 0.5 * (a + b); final double tol1 = eps * Math.abs(x) + t; final double tol2 = 2 * tol1; @@ -127,7 +124,6 @@ public class BrentOptimizer extends AbstractUnivariateRealOptimizer { double p = 0; double q = 0; double r = 0; - double d = 0; double u = 0; if (Math.abs(e) > tol1) { // Fit parabola. @@ -191,8 +187,8 @@ public class BrentOptimizer extends AbstractUnivariateRealOptimizer { u = x + d; } - double fu = computeObjectiveValue(f, u); - if (goalType == GoalType.MAXIMIZE) { + double fu = computeObjectiveValue(u); + if (!isMinim) { fu = -fu; } @@ -229,16 +225,10 @@ public class BrentOptimizer extends AbstractUnivariateRealOptimizer { } } } else { // termination - setResult(x, (goalType == GoalType.MAXIMIZE) ? -fx : fx, count); + setFunctionValue(isMinim ? fx : -fx); return x; } - ++count; + incrementIterationsCounter(); } - throw new MaxIterationsExceededException(maximalIterationCount); - } - - /** Temporary workaround. */ - protected double doOptimize() { - throw new UnsupportedOperationException(); } }
bugs-dot-jar/commons-math_extracted_diff/developer-patch_bugs-dot-jar_MATH-395_962315ba.diff
bugs-dot-jar_data_MATH-727_69273dca
--- BugID: MATH-727 Summary: too large first step with embedded Runge-Kutta integrators (Dormand-Prince 8(5,3) ...) Description: |- Adaptive step size integrators compute the first step size by themselves if it is not provided. For embedded Runge-Kutta type, this step size is not checked against the integration range, so if the integration range is extremely short, this step size may evaluate the function out of the range (and in fact it tries afterward to go back, and fails to stop). Gragg-Bulirsch-Stoer integrators do not have this problem, the step size is checked and truncated if needed. diff --git a/src/main/java/org/apache/commons/math3/ode/nonstiff/RungeKuttaIntegrator.java b/src/main/java/org/apache/commons/math3/ode/nonstiff/RungeKuttaIntegrator.java index 68bd8b0..5f7d5d8 100644 --- a/src/main/java/org/apache/commons/math3/ode/nonstiff/RungeKuttaIntegrator.java +++ b/src/main/java/org/apache/commons/math3/ode/nonstiff/RungeKuttaIntegrator.java @@ -119,7 +119,19 @@ public abstract class RungeKuttaIntegrator extends AbstractIntegrator { // set up integration control objects stepStart = equations.getTime(); - stepSize = forward ? step : -step; + if (forward) { + if (stepStart + step >= t) { + stepSize = t - stepStart; + } else { + stepSize = step; + } + } else { + if (stepStart - step <= t) { + stepSize = t - stepStart; + } else { + stepSize = -step; + } + } initIntegration(equations.getTime(), y0, t); // main integration loop
bugs-dot-jar/commons-math_extracted_diff/developer-patch_bugs-dot-jar_MATH-727_69273dca.diff
bugs-dot-jar_data_MATH-343_f6dd42b4
--- BugID: MATH-343 Summary: Brent solver doesn't throw IllegalArgumentException when initial guess has the wrong sign Description: Javadoc for "public double solve(final UnivariateRealFunction f, final double min, final double max, final double initial)" claims that "if the values of the function at the three points have the same sign" an IllegalArgumentException is thrown. This case isn't even checked. diff --git a/src/main/java/org/apache/commons/math/analysis/solvers/BrentSolver.java b/src/main/java/org/apache/commons/math/analysis/solvers/BrentSolver.java index 4e95ed5..e0cb427 100644 --- a/src/main/java/org/apache/commons/math/analysis/solvers/BrentSolver.java +++ b/src/main/java/org/apache/commons/math/analysis/solvers/BrentSolver.java @@ -32,6 +32,11 @@ import org.apache.commons.math.analysis.UnivariateRealFunction; */ public class BrentSolver extends UnivariateRealSolverImpl { + /** Error message for non-bracketing interval. */ + private static final String NON_BRACKETING_MESSAGE = + "function values at endpoints do not have different signs. " + + "Endpoints: [{0}, {1}], Values: [{2}, {3}]"; + /** Serializable version identifier */ private static final long serialVersionUID = 7694577816772532779L; @@ -128,6 +133,11 @@ public class BrentSolver extends UnivariateRealSolverImpl { return solve(f, initial, yInitial, max, yMax, initial, yInitial); } + if (yMin * yMax > 0) { + throw MathRuntimeException.createIllegalArgumentException( + NON_BRACKETING_MESSAGE, min, max, yMin, yMax); + } + // full Brent algorithm starting with provided initial guess return solve(f, min, yMin, max, yMax, initial, yInitial); @@ -176,9 +186,7 @@ public class BrentSolver extends UnivariateRealSolverImpl { } else { // neither value is close to zero and min and max do not bracket root. throw MathRuntimeException.createIllegalArgumentException( - "function values at endpoints do not have different signs. " + - "Endpoints: [{0}, {1}], Values: [{2}, {3}]", - min, max, yMin, yMax); + NON_BRACKETING_MESSAGE, min, max, yMin, yMax); } } else if (sign < 0){ // solve using only the first endpoint as initial guess
bugs-dot-jar/commons-math_extracted_diff/developer-patch_bugs-dot-jar_MATH-343_f6dd42b4.diff
bugs-dot-jar_data_MATH-1068_b12610d3
--- BugID: MATH-1068 Summary: KendallsCorrelation suffers from integer overflow for large arrays. Description: |- For large array size (say, over 5,000), numPairs > 10 million. in line 258, (numPairs - tiedXPairs) * (numPairs - tiedYPairs) possibly > 100 billion, which will cause an integer overflow, resulting in a negative number, which will result in the end result in a NaN since the square-root of that number is calculated. This can easily be solved by changing line 163 to final long numPairs = ((long)n) * (n - 1) / 2; // to avoid overflow diff --git a/src/main/java/org/apache/commons/math3/stat/correlation/KendallsCorrelation.java b/src/main/java/org/apache/commons/math3/stat/correlation/KendallsCorrelation.java index 1e4495c..81fb39f 100644 --- a/src/main/java/org/apache/commons/math3/stat/correlation/KendallsCorrelation.java +++ b/src/main/java/org/apache/commons/math3/stat/correlation/KendallsCorrelation.java @@ -160,7 +160,7 @@ public class KendallsCorrelation { } final int n = xArray.length; - final int numPairs = n * (n - 1) / 2; + final long numPairs = n * (n - 1l) / 2l; @SuppressWarnings("unchecked") Pair<Double, Double>[] pairs = new Pair[n]; @@ -254,7 +254,8 @@ public class KendallsCorrelation { } tiedYPairs += consecutiveYTies * (consecutiveYTies - 1) / 2; - int concordantMinusDiscordant = numPairs - tiedXPairs - tiedYPairs + tiedXYPairs - 2 * swaps; - return concordantMinusDiscordant / FastMath.sqrt((numPairs - tiedXPairs) * (numPairs - tiedYPairs)); + final long concordantMinusDiscordant = numPairs - tiedXPairs - tiedYPairs + tiedXYPairs - 2 * swaps; + final double nonTiedPairsMultiplied = (numPairs - tiedXPairs) * (double) (numPairs - tiedYPairs); + return concordantMinusDiscordant / FastMath.sqrt(nonTiedPairsMultiplied); } }
bugs-dot-jar/commons-math_extracted_diff/developer-patch_bugs-dot-jar_MATH-1068_b12610d3.diff
bugs-dot-jar_data_MATH-1283_9e0c5ad4
--- BugID: MATH-1283 Summary: Gamma function computation Description: |- In the gamma method, when handling the case "absX > 20", the computation of gammaAbs should replace "x" (see code below with x in bold) by "absX". For large negative values of x, the function returns with the wrong sign. final double gammaAbs = SQRT_TWO_PI / *x* * FastMath.pow(y, absX + 0.5) * FastMath.exp(-y) * lanczos(absX); diff --git a/src/main/java/org/apache/commons/math4/special/Gamma.java b/src/main/java/org/apache/commons/math4/special/Gamma.java index aa0e90c..f390f7c 100644 --- a/src/main/java/org/apache/commons/math4/special/Gamma.java +++ b/src/main/java/org/apache/commons/math4/special/Gamma.java @@ -695,7 +695,7 @@ public class Gamma { } } else { final double y = absX + LANCZOS_G + 0.5; - final double gammaAbs = SQRT_TWO_PI / x * + final double gammaAbs = SQRT_TWO_PI / absX * FastMath.pow(y, absX + 0.5) * FastMath.exp(-y) * lanczos(absX); if (x > 0.0) {
bugs-dot-jar/commons-math_extracted_diff/developer-patch_bugs-dot-jar_MATH-1283_9e0c5ad4.diff
bugs-dot-jar_data_MATH-1204_a56d4998
--- BugID: MATH-1204 Summary: 'bracket function gives up too early ' Description: 'In UnivariateSolverUtils.bracket(...) the search ends prematurely if a = lowerBound, which ignores some roots in the interval. ' diff --git a/src/main/java/org/apache/commons/math4/analysis/solvers/UnivariateSolverUtils.java b/src/main/java/org/apache/commons/math4/analysis/solvers/UnivariateSolverUtils.java index 2521c9b..49742d8 100644 --- a/src/main/java/org/apache/commons/math4/analysis/solvers/UnivariateSolverUtils.java +++ b/src/main/java/org/apache/commons/math4/analysis/solvers/UnivariateSolverUtils.java @@ -314,7 +314,7 @@ public class UnivariateSolverUtils { double delta = 0; for (int numIterations = 0; - (numIterations < maximumIterations) && (a > lowerBound || b > upperBound); + (numIterations < maximumIterations) && (a > lowerBound || b < upperBound); ++numIterations) { final double previousA = a;
bugs-dot-jar/commons-math_extracted_diff/developer-patch_bugs-dot-jar_MATH-1204_a56d4998.diff
bugs-dot-jar_data_MATH-1277_fb007815
--- BugID: MATH-1277 Summary: Incorrect Kendall Tau calc due to data type mistmatch Description: "The Kendall Tau calculation returns a number from -1.0 to 1.0\n\ndue to a mixing of ints and longs, a mistake occurs on large size columns (arrays) passed to the function. an array size of > 50350 triggers the condition in my case - although it may be data dependent\n\nthe ver 3.5 library returns 2.6 as a result (outside of the defined range of Kendall Tau)\n\nwith the cast to long below - the result reutns to its expected value\n\n\ncommons.math3.stat.correlation.KendallsCorrelation.correlation\n\n\nhere's the sample code I used:\nI added the cast to long of swaps in the \n\n\t\t\tint swaps = 1077126315;\n\t\t\t final long numPairs = sum(50350 - 1);\n\t\t\t long tiedXPairs = 0;\n\t\t long tiedXYPairs = 0;\n\t\t long tiedYPairs = 0;\n\t\t \n\t\t final long concordantMinusDiscordant = numPairs - tiedXPairs - tiedYPairs + tiedXYPairs - 2 * (long) swaps;\n\t final double nonTiedPairsMultiplied = 1.6e18;\n\t double myTest = concordantMinusDiscordant / FastMath.sqrt(nonTiedPairsMultiplied);\n" diff --git a/src/main/java/org/apache/commons/math4/stat/correlation/KendallsCorrelation.java b/src/main/java/org/apache/commons/math4/stat/correlation/KendallsCorrelation.java index 77b7d22..125083e 100644 --- a/src/main/java/org/apache/commons/math4/stat/correlation/KendallsCorrelation.java +++ b/src/main/java/org/apache/commons/math4/stat/correlation/KendallsCorrelation.java @@ -201,7 +201,7 @@ public class KendallsCorrelation { tiedXPairs += sum(consecutiveXTies - 1); tiedXYPairs += sum(consecutiveXYTies - 1); - int swaps = 0; + long swaps = 0; @SuppressWarnings("unchecked") Pair<Double, Double>[] pairsDestination = new Pair[n]; for (int segmentSize = 1; segmentSize < n; segmentSize <<= 1) {
bugs-dot-jar/commons-math_extracted_diff/developer-patch_bugs-dot-jar_MATH-1277_fb007815.diff
bugs-dot-jar_data_MATH-1093_7cfbc0da
--- BugID: MATH-1093 Summary: arcs set split covers full circle instead of being empty Description: |- When splitting an arcs set using an arc very close to one of the boundaries (but not at the boundary), the algorithm confuses cases for which end - start = 2pi from cases for which end - start = epsilon. The following test case shows such a failure: {code} @Test public void testSplitWithinEpsilon() { double epsilon = 1.0e-10; double a = 6.25; double b = a - 0.5 * epsilon; ArcsSet set = new ArcsSet(a - 1, a, epsilon); Arc arc = new Arc(b, b + FastMath.PI, epsilon); ArcsSet.Split split = set.split(arc); Assert.assertEquals(set.getSize(), split.getPlus().getSize(), epsilon); Assert.assertNull(split.getMinus()); } {code} The last assertion (split.getMinus() being null) fails, as with current code split.getMinus() covers the full circle from 0 to 2pi. diff --git a/src/main/java/org/apache/commons/math3/geometry/spherical/oned/ArcsSet.java b/src/main/java/org/apache/commons/math3/geometry/spherical/oned/ArcsSet.java index 06a8bb2..08ec3ad 100644 --- a/src/main/java/org/apache/commons/math3/geometry/spherical/oned/ArcsSet.java +++ b/src/main/java/org/apache/commons/math3/geometry/spherical/oned/ArcsSet.java @@ -717,10 +717,10 @@ public class ArcsSet extends AbstractRegion<Sphere1D, Sphere1D> implements Itera final double syncedStart = MathUtils.normalizeAngle(a[0], reference) - arc.getInf(); final double arcOffset = a[0] - syncedStart; final double syncedEnd = a[1] - arcOffset; - if (syncedStart < arcLength || syncedEnd > MathUtils.TWO_PI) { + if (syncedStart <= arcLength - getTolerance() || syncedEnd >= MathUtils.TWO_PI + getTolerance()) { inMinus = true; } - if (syncedEnd > arcLength) { + if (syncedEnd >= arcLength + getTolerance()) { inPlus = true; } } @@ -749,10 +749,8 @@ public class ArcsSet extends AbstractRegion<Sphere1D, Sphere1D> implements Itera */ public Split split(final Arc arc) { - final BSPTree<Sphere1D> minus = new BSPTree<Sphere1D>(); - minus.setAttribute(Boolean.FALSE); - final BSPTree<Sphere1D> plus = new BSPTree<Sphere1D>(); - plus.setAttribute(Boolean.FALSE); + final List<Double> minus = new ArrayList<Double>(); + final List<Double> plus = new ArrayList<Double>(); final double reference = FastMath.PI + arc.getInf(); final double arcLength = arc.getSup() - arc.getInf(); @@ -763,51 +761,51 @@ public class ArcsSet extends AbstractRegion<Sphere1D, Sphere1D> implements Itera final double syncedEnd = a[1] - arcOffset; if (syncedStart < arcLength) { // the start point a[0] is in the minus part of the arc - addArcLimit(minus, a[0], true); + minus.add(a[0]); if (syncedEnd > arcLength) { // the end point a[1] is past the end of the arc // so we leave the minus part and enter the plus part final double minusToPlus = arcLength + arcOffset; - addArcLimit(minus, minusToPlus, false); - addArcLimit(plus, minusToPlus, true); + minus.add(minusToPlus); + plus.add(minusToPlus); if (syncedEnd > MathUtils.TWO_PI) { // in fact the end point a[1] goes far enough that we // leave the plus part of the arc and enter the minus part again final double plusToMinus = MathUtils.TWO_PI + arcOffset; - addArcLimit(plus, plusToMinus, false); - addArcLimit(minus, plusToMinus, true); - addArcLimit(minus, a[1], false); + plus.add(plusToMinus); + minus.add(plusToMinus); + minus.add(a[1]); } else { // the end point a[1] is in the plus part of the arc - addArcLimit(plus, a[1], false); + plus.add(a[1]); } } else { // the end point a[1] is in the minus part of the arc - addArcLimit(minus, a[1], false); + minus.add(a[1]); } } else { // the start point a[0] is in the plus part of the arc - addArcLimit(plus, a[0], true); + plus.add(a[0]); if (syncedEnd > MathUtils.TWO_PI) { // the end point a[1] wraps around to the start of the arc // so we leave the plus part and enter the minus part final double plusToMinus = MathUtils.TWO_PI + arcOffset; - addArcLimit(plus, plusToMinus, false); - addArcLimit(minus, plusToMinus, true); + plus.add(plusToMinus); + minus.add(plusToMinus); if (syncedEnd > MathUtils.TWO_PI + arcLength) { // in fact the end point a[1] goes far enough that we // leave the minus part of the arc and enter the plus part again final double minusToPlus = MathUtils.TWO_PI + arcLength + arcOffset; - addArcLimit(minus, minusToPlus, false); - addArcLimit(plus, minusToPlus, true); - addArcLimit(plus, a[1], false); + minus.add(minusToPlus); + plus.add(minusToPlus); + plus.add(a[1]); } else { // the end point a[1] is in the minus part of the arc - addArcLimit(minus, a[1], false); + minus.add(a[1]); } } else { // the end point a[1] is in the plus part of the arc - addArcLimit(plus, a[1], false); + plus.add(a[1]); } } } @@ -822,30 +820,85 @@ public class ArcsSet extends AbstractRegion<Sphere1D, Sphere1D> implements Itera * @param isStart if true, the limit is the start of an arc */ private void addArcLimit(final BSPTree<Sphere1D> tree, final double alpha, final boolean isStart) { + final LimitAngle limit = new LimitAngle(new S1Point(alpha), !isStart, getTolerance()); final BSPTree<Sphere1D> node = tree.getCell(limit.getLocation(), getTolerance()); if (node.getCut() != null) { - // we find again an already added limit, - // this means we have done a full turn around the circle - leafBefore(node).setAttribute(Boolean.valueOf(!isStart)); - } else { - // it's a new node - node.insertCut(limit); - node.setAttribute(null); - node.getPlus().setAttribute(Boolean.FALSE); - node.getMinus().setAttribute(Boolean.TRUE); + // this should never happen + throw new MathInternalError(); } + + node.insertCut(limit); + node.setAttribute(null); + node.getPlus().setAttribute(Boolean.FALSE); + node.getMinus().setAttribute(Boolean.TRUE); + } /** Create a split part. - * @param tree BSP tree containing the limit angles of the split part + * <p> + * As per construction, the list of limit angles is known to have + * an even number of entries, with start angles at even indices and + * end angles at odd indices. + * </p> + * @param limits limit angles of the split part * @return split part (may be null) */ - private ArcsSet createSplitPart(final BSPTree<Sphere1D> tree) { - if (tree.getCut() == null && !(Boolean) tree.getAttribute()) { + private ArcsSet createSplitPart(final List<Double> limits) { + if (limits.isEmpty()) { return null; } else { + + // collapse close limit angles + for (int i = 0; i < limits.size(); ++i) { + final int j = (i + 1) % limits.size(); + final double lA = limits.get(i); + final double lB = MathUtils.normalizeAngle(limits.get(j), lA); + if (FastMath.abs(lB - lA) <= getTolerance()) { + // the two limits are too close to each other, we remove both of them + if (j > 0) { + // regular case, the two entries are consecutive ones + limits.remove(j); + limits.remove(i); + i = i - 1; + } else { + // special case, i the the last entry and j is the first entry + // we have wrapped around list end + final double lEnd = limits.remove(limits.size() - 1); + final double lStart = limits.remove(0); + if (limits.isEmpty()) { + // the ends were the only limits, is it a full circle or an empty circle? + if (lEnd - lStart > FastMath.PI) { + // it was full circle + return new ArcsSet(new BSPTree<Sphere1D>(Boolean.TRUE), getTolerance()); + } else { + // it was an empty circle + return null; + } + } else { + // we have removed the first interval start, so our list + // currently starts with an interval end, which is wrong + // we need to move this interval end to the end of the list + limits.add(limits.remove(0) + MathUtils.TWO_PI); + } + } + } + } + + // build the tree by adding all angular sectors + BSPTree<Sphere1D> tree = new BSPTree<Sphere1D>(Boolean.FALSE); + for (int i = 0; i < limits.size() - 1; i += 2) { + addArcLimit(tree, limits.get(i), true); + addArcLimit(tree, limits.get(i + 1), false); + } + + if (tree.getCut() == null) { + // we did not insert anything + return null; + } + return new ArcsSet(tree, getTolerance()); + } }
bugs-dot-jar/commons-math_extracted_diff/developer-patch_bugs-dot-jar_MATH-1093_7cfbc0da.diff