src_fm_fc_ms_ff
stringlengths
43
86.8k
target
stringlengths
20
276k
UserHostPageFilter implements Filter { String securityContextJson(final User user) { final String userJson = ServerMarshalling.toJSON(user); return "{\"" + SecurityConstants.DICTIONARY_USER + "\": " + userJson + "}"; } @Override void init(FilterConfig filterConfig); @Override void destroy(); @Override void doFilter(ServletRequest request, ServletResponse response, FilterChain chain); }
@Test public void testSecurityContextJsonWhenAGroupHasAnApostrophe() throws Exception { final UserImpl user = new UserImpl("Mary", roles("admin"), groups("girls'", "programmer", "admin")); final String json = filter.securityContextJson(user); assertTrue(isValid(json)); } @Test public void testSecurityContextJsonWhenAGroupHasAQuote() throws Exception { final UserImpl user = new UserImpl("Mary", roles("admin"), groups("girls\"", "programmer", "admin")); final String json = filter.securityContextJson(user); assertTrue(isValid(json)); }
JBossVfsDir implements Vfs.Dir { @Override public Iterable<Vfs.File> getFiles() { return new Iterable<Vfs.File>() { @Override public Iterator<Vfs.File> iterator() { final List<VirtualFile> toVisit = new ArrayList<VirtualFile>(virtualFile.getChildren()); return new AbstractIterator<Vfs.File>() { @Override protected Vfs.File computeNext() { while (!toVisit.isEmpty()) { final VirtualFile nextFile = toVisit.remove(toVisit.size() - 1); if (nextFile.isDirectory()) { toVisit.addAll(nextFile.getChildren()); continue; } return new Vfs.File() { @Override public String getName() { return nextFile.getName(); } @Override public String getRelativePath() { return nextFile.getPathName(); } @Override public String getFullPath() { return nextFile.getPathName(); } @Override public InputStream openInputStream() throws IOException { return nextFile.openStream(); } }; } return endOfData(); } }; } }; } JBossVfsDir(URL url); @Override String getPath(); @Override Iterable<Vfs.File> getFiles(); @Override void close(); }
@Test public void testEmptyVfsDirListing() throws Exception { JBossVfsDir jbvd = new JBossVfsDir(getJBossVfsMountPoint().asDirectoryURL()); int count = 0; for (org.jboss.errai.reflections.vfs.Vfs.File reflectionsFile : jbvd.getFiles()) { System.out.println("Visiting virtual file " + reflectionsFile.getRelativePath()); count++; } Assert.assertEquals("Didn't find the expected number of VFS entries", 0, count); } @Test public void testShallowVfsDirListing() throws Exception { new File(mountedDir, "foo").createNewFile(); new File(mountedDir, "bar").createNewFile(); new File(mountedDir, "baz").createNewFile(); JBossVfsDir jbvd = new JBossVfsDir(getJBossVfsMountPoint().asDirectoryURL()); int count = 0; for (org.jboss.errai.reflections.vfs.Vfs.File reflectionsFile : jbvd.getFiles()) { System.out.println("Visiting virtual file " + reflectionsFile.getRelativePath()); count++; } Assert.assertEquals("Didn't find the expected number of VFS entries", 3, count); } @Test public void testNestedEmptyVfsDirListing() throws Exception { new File(mountedDir, "deeply/nested/directories").mkdirs(); JBossVfsDir jbvd = new JBossVfsDir(getJBossVfsMountPoint().asDirectoryURL()); int count = 0; for (org.jboss.errai.reflections.vfs.Vfs.File reflectionsFile : jbvd.getFiles()) { System.out.println("Visiting virtual file " + reflectionsFile.getRelativePath()); count++; } Assert.assertEquals("All dirs were empty, but got non-zero count", 0, count); } @Test public void testVfsFullPath() throws Exception { new File(mountedDir, "foo").createNewFile(); JBossVfsDir jbvd = new JBossVfsDir(getJBossVfsMountPoint().asDirectoryURL()); String path = jbvd.getFiles().iterator().next().getFullPath(); Assert.assertTrue("Wrong path:" + path, path.matches("/([A-Za-z]:/)?mnt/foo")); } @Test public void testVfsRelativePath() throws Exception { new File(mountedDir, "foo").createNewFile(); JBossVfsDir jbvd = new JBossVfsDir(getJBossVfsMountPoint().asDirectoryURL()); String path = jbvd.getFiles().iterator().next().getRelativePath(); Assert.assertTrue("Wrong path:" + path, path.matches("/([A-Za-z]:/)?mnt/foo")); } @Test public void testVfsFileName() throws Exception { new File(mountedDir, "foo").createNewFile(); JBossVfsDir jbvd = new JBossVfsDir(getJBossVfsMountPoint().asDirectoryURL()); assertEquals("foo", jbvd.getFiles().iterator().next().getName()); }
EventDispatcher implements MessageCallback { static String getConversationalSessionId(Class<? extends Object> eventType) { final QueueSession queueSession = RpcContext.getQueueSession(); if (eventType.isAnnotationPresent(Conversational.class) && queueSession != null && queueSession.getSessionId() != null) { return queueSession.getSessionId(); } return null; } EventDispatcher(final BeanManager beanManager, final EventRoutingTable eventRoutingTable, final MessageBus messageBus, final Set<String> observedEvents, final Map<String, Annotation> eventQualifiers); @Override @SuppressWarnings("unchecked") void callback(final Message message); boolean isRoutable(final LocalContext localContext, final Message message); void sendEventToClients(Object event, EventMetadata emd); }
@Test public void conversationalEventWithContext() { RpcContext.set(new MockMessage()); final String convSessionId = EventDispatcher.getConversationalSessionId(MyConversationalEvent.class); assertEquals("bearista", convSessionId); } @Test public void conversationalEventWithoutContext() { final String convSessionId = EventDispatcher.getConversationalSessionId(MyConversationalEvent.class); assertNull(convSessionId); } @Test public void nonConversationalEventWithContext() { RpcContext.set(new MockMessage()); final String convSessionId = EventDispatcher.getConversationalSessionId(MyNonConversationalEvent.class); assertNull(convSessionId); } @Test public void nonConversationalEventWithoutContext() { final String convSessionId = EventDispatcher.getConversationalSessionId(MyNonConversationalEvent.class); assertNull(convSessionId); }
Elemental2TagMapping { static Collection<String> getTags(final Class<?> elemental2ElementClass) { if (elemental2ElementClass == null || Element.class.equals(elemental2ElementClass)) { return Collections.emptyList(); } final Collection<String> tags = TAG_NAMES_BY_DOM_INTERFACE.get(elemental2ElementClass); if (tags.isEmpty()) { return getTags(elemental2ElementClass.getSuperclass()); } return tags; } }
@Test public void testGetTags() { assertEquals("null should return no tag", emptyList(), getTags(null)); assertEquals("Object.class should not have any mapped tag name", emptyList(), getTags(Object.class)); assertEquals("String.class should not have any mapped tag name", emptyList(), getTags(String.class)); assertEquals("HTMLDivElement should have a tag mapped to it", singletonList("div"), getTags(HTMLDivElement.class)); assertEquals("HTMLDivElement subclass should have a tag mapped to it", singletonList("div"), getTags(CustomElement.class)); assertEquals("HTMLDivElement subclass should have a tag mapped to it", singletonList("div"), getTags(CustomElement.Child.class)); }
TemplatedCodeDecorator extends IOCDecoratorExtension<Templated> { @Override public void generateDecorator(final Decorable decorable, final FactoryController controller) { final MetaClass declaringClass = decorable.getDecorableDeclaringType(); final Templated anno = (Templated) decorable.getAnnotation(); final Class<?> templateProvider = anno.provider(); final boolean customProvider = templateProvider != Templated.DEFAULT_PROVIDER.class; final Optional<String> styleSheetPath = getTemplateStyleSheetPath(declaringClass); final boolean explicitStyleSheetPresent = styleSheetPath.filter(path -> Thread.currentThread().getContextClassLoader().getResource(path) != null).isPresent(); if (declaringClass.isAssignableTo(Composite.class)) { logger.warn("The @Templated class, {}, extends Composite. This will not be supported in future versions.", declaringClass.getFullyQualifiedName()); } if (styleSheetPath.isPresent() && !explicitStyleSheetPresent) { throw new GenerationException("@Templated class [" + declaringClass.getFullyQualifiedName() + "] declared a stylesheet [" + styleSheetPath + "] that could not be found."); } final List<Statement> initStmts = new ArrayList<>(); generateTemplatedInitialization(decorable, controller, initStmts, customProvider); if (customProvider) { final Statement init = Stmt.invokeStatic(TemplateUtil.class, "provideTemplate", templateProvider, getTemplateUrl(declaringClass), Stmt.newObject(TemplateRenderingCallback.class) .extend() .publicOverridesMethod("renderTemplate", Parameter.of(String.class, "template", true)) .appendAll(initStmts) .finish() .finish()); controller.addInitializationStatements(Collections.singletonList(init)); } else { controller.addInitializationStatements(initStmts); } controller.addDestructionStatements(generateTemplateDestruction(decorable)); controller.addInitializationStatementsToEnd(Collections.<Statement>singletonList(invokeStatic(StyleBindingsRegistry.class, "get") .invoke("updateStyles", Refs.get("instance")))); } TemplatedCodeDecorator(final Class<Templated> decoratesWith); @Override void generateDecorator(final Decorable decorable, final FactoryController controller); static Optional<String> getTemplateStyleSheetPath(final MetaClass type); static String getTemplateFileName(final MetaClass type); static String getTemplateUrl(final MetaClass type); static String getTemplateFragmentName(final MetaClass type); }
@Test public void nativeQuickHandlerWithNoEventTypeThrowsGenerationException() throws Exception { final MetaMethod handlerMethod = mock(MetaMethod.class); final MetaParameter eventParam = mock(MetaParameter.class); when(templatedClass.getMethodsAnnotatedWith(EventHandler.class)) .thenReturn(singletonList(handlerMethod)); when(handlerMethod.getAnnotation(EventHandler.class)).thenReturn(defaultHandlerAnno); when(handlerMethod.getParameters()).thenReturn(new MetaParameter[] { eventParam }); when(eventParam.getType()).thenReturn(elemental2EventClass); try { decorator.generateDecorator(decorable, controller); fail("No error was observed."); } catch (final GenerationException observed) { try { assertTrue("Error must mention @ForEvent", ofNullable(observed.getMessage()).filter(m -> m.contains("@ForEvent")).isPresent()); assertTrue("Error must mention @BrowserEvent", ofNullable(observed.getMessage()).filter(m -> m.contains("@BrowserEvent")).isPresent()); } catch (final AssertionError ae) { ae.initCause(observed); throw ae; } } catch (final AssertionError ae) { throw ae; } catch (final Throwable t) { throw new AssertionError("Unexpected error: " + t.getMessage(), t); } }
TranslationServiceGenerator extends AbstractAsyncGenerator { public static String getLocaleFromBundlePath(final String bundlePath) { final Matcher matcher = LOCALE_IN_FILENAME_PATTERN.matcher(bundlePath); if (matcher != null && matcher.matches()) { final StringBuilder locale = new StringBuilder(); final String lang = matcher.group(2); if (lang != null) locale.append(lang); final String region = matcher.group(3); if (region != null) locale.append("_").append(region.substring(1)); return locale.toString(); } else { return null; } } @Override String generate(final TreeLogger logger, final GeneratorContext context, final String typeName); @Override String generate(final TreeLogger logger, final GeneratorContext context); static String getLocaleFromBundlePath(final String bundlePath); }
@Test public void testGetLocaleFromBundleFilename() { Assert.assertEquals(null, TranslationServiceGenerator.getLocaleFromBundlePath("myBundle.json")); Assert.assertEquals(null, TranslationServiceGenerator.getLocaleFromBundlePath("myBundle_en_US.other")); Assert.assertEquals("en_US", TranslationServiceGenerator.getLocaleFromBundlePath("myBundle_en_US.json")); Assert.assertEquals("en_GB", TranslationServiceGenerator.getLocaleFromBundlePath("myBundle_en_GB.json")); Assert.assertEquals("en", TranslationServiceGenerator.getLocaleFromBundlePath("myBundle_en.json")); Assert.assertEquals("fr_CA", TranslationServiceGenerator.getLocaleFromBundlePath("Some-Other-Bundle_fr_CA.json")); Assert.assertEquals("fr_FR", TranslationServiceGenerator.getLocaleFromBundlePath("Some-Other-Bundle_fr_FR.json")); Assert.assertEquals("fr", TranslationServiceGenerator.getLocaleFromBundlePath("Some-Other-Bundle_fr.json")); Assert.assertEquals("en_US", TranslationServiceGenerator .getLocaleFromBundlePath("org/example/ui/client/local/myBundle_en_US.json")); Assert.assertEquals("en_GB", TranslationServiceGenerator .getLocaleFromBundlePath("org/example/ui/client/local/myBundle_en_GB.json")); Assert.assertEquals("en", TranslationServiceGenerator .getLocaleFromBundlePath("org/example/ui/client/local/myBundle_en.json")); }
TranslationServiceGenerator extends AbstractAsyncGenerator { @SuppressWarnings({ "rawtypes", "unchecked" }) protected static Set<String> recordBundleKeys(final Map<String, Set<String>> discoveredI18nMap, final String locale, final String bundlePath) { InputStream is = null; final Set<String> duplicates = new HashSet<>(); try { final Set<String> keys = discoveredI18nMap.computeIfAbsent(locale, l -> new HashSet<>()); is = TranslationServiceGenerator.class.getClassLoader().getResourceAsStream(bundlePath); if (isJsonBundle(bundlePath)) { final JsonFactory jsonFactory = new JsonFactory(); final JsonParser jp = jsonFactory.createJsonParser(is); JsonToken token = jp.nextToken(); while (token != null) { token = jp.nextToken(); if (token == JsonToken.FIELD_NAME) { final String name = jp.getCurrentName(); if (keys.contains(name)) { duplicates.add(name); } keys.add(name); } } } else { final Properties properties = new Properties(); properties.load(is); final Set<String> propertFileKeys = (Set) properties.keySet(); propertFileKeys .stream() .filter(key -> keys.contains(key)) .collect(Collectors.toCollection(() -> duplicates)); keys.addAll(propertFileKeys); } } catch (final Exception e) { throw new RuntimeException(e); } finally { IOUtils.closeQuietly(is); } return duplicates; } @Override String generate(final TreeLogger logger, final GeneratorContext context, final String typeName); @Override String generate(final TreeLogger logger, final GeneratorContext context); static String getLocaleFromBundlePath(final String bundlePath); }
@Test public void testRecordBundleKeys() { String jsonResourcePath = "org/jboss/errai/ui/test/i18n/client/I18nTemplateTest.json"; Map<String, Set<String>> result = new HashMap<String, Set<String>>(); TranslationServiceGenerator.recordBundleKeys(result, null, jsonResourcePath); Assert.assertEquals(1, result.keySet().size()); Set<String> defaultKeys = result.get(null); Assert.assertEquals(11, defaultKeys.size()); jsonResourcePath = "org/jboss/errai/ui/test/i18n/client/I18nTemplateTest_fr_FR.json"; TranslationServiceGenerator.recordBundleKeys(result, "fr_FR", jsonResourcePath); Assert.assertEquals(2, result.keySet().size()); defaultKeys = result.get(null); Assert.assertEquals(11, defaultKeys.size()); Set<String> fr_FR_Keys = result.get("fr_FR"); Assert.assertEquals(10, fr_FR_Keys.size()); jsonResourcePath = "org/jboss/errai/ui/test/i18n/client/I18nTemplateTest_da.json"; TranslationServiceGenerator.recordBundleKeys(result, "da", jsonResourcePath); Assert.assertEquals(3, result.keySet().size()); defaultKeys = result.get(null); Assert.assertEquals(11, defaultKeys.size()); fr_FR_Keys = result.get("fr_FR"); Assert.assertEquals(10, fr_FR_Keys.size()); Set<String> da_Keys = result.get("da"); Assert.assertEquals(9, da_Keys.size()); }
MetricGetter { @SafeVarargs public static final TagValue[][] getTagCombinations(Class<? extends TagValue>... tagValueClazzes) { int combinations = 1; for (Class<? extends TagValue> clazz : tagValueClazzes) { combinations *= clazz.getEnumConstants().length; } TagValue[][] result = new TagValue[combinations][]; List<List<TagValue>> tagLists = getTagCombinations(Arrays.asList(tagValueClazzes)); for (int i = 0; i < tagLists.size(); i++) { List<TagValue> tagList = tagLists.get(i); result[i] = tagList.toArray(new TagValue[tagList.size()]); } return result; } MetricGetter(Class<?> clazz, String methodName); CounterMetric getInvocations(InvocationResult result, InvocationFallback fallbackUsed); CounterMetric getRetryCalls(RetryRetried retried, RetryResult result); CounterMetric getRetryRetries(); CounterMetric getTimeoutCalls(TimeoutTimedOut timedOut); Optional<Histogram> getTimeoutExecutionDuration(); CounterMetric getCircuitBreakerCalls(CircuitBreakerResult cbResult); CounterMetric getCircuitBreakerOpened(); GaugeMetric getCircuitBreakerState(CircuitBreakerState cbState); CounterMetric getBulkheadCalls(BulkheadResult bulkheadResult); GaugeMetric getBulkheadExecutionsRunning(); GaugeMetric getBulkheadExecutionsWaiting(); Optional<Histogram> getBulkheadRunningDuration(); Optional<Histogram> getBulkheadWaitingDuration(); void baselineMetrics(); @SafeVarargs static final TagValue[][] getTagCombinations(Class<? extends TagValue>... tagValueClazzes); }
@Test public void testTagComboZero() { TagValue[][] expected = {{}}; assertEquals(MetricGetter.getTagCombinations(), expected); } @Test public void testTagComboOne() { TagValue[][] expected = {{TimeoutTimedOut.TRUE}, {TimeoutTimedOut.FALSE}}; assertEquals(MetricGetter.getTagCombinations(TimeoutTimedOut.class), expected); } @Test public void testTagComboTwo() { TagValue[][] expected = {{TimeoutTimedOut.TRUE, InvocationResult.VALUE_RETURNED}, {TimeoutTimedOut.TRUE, InvocationResult.EXCEPTION_THROWN}, {TimeoutTimedOut.FALSE, InvocationResult.VALUE_RETURNED}, {TimeoutTimedOut.FALSE, InvocationResult.EXCEPTION_THROWN}}; assertEquals(MetricGetter.getTagCombinations(TimeoutTimedOut.class, InvocationResult.class), expected); }
Sleeper { public void sleepWhileConditionMet(BooleanSupplier condition, Time duration) throws InterruptedException { long timeoutMs = duration.valueAsMillis(); long sleepingPeriodMs = getSleepingPeriodMs(timeoutMs); long timeWaited = 0; while (condition.getAsBoolean() && timeWaited < timeoutMs) { sleepMs(sleepingPeriodMs); timeWaited += sleepingPeriodMs; } } void sleep(Time duration); void sleepWhileConditionMet(BooleanSupplier condition, Time duration); }
@Test public void sleepWhileConditionMet_conditionDoesNotChangeBeforeTime_sleepsAllottedTime() throws Exception { final long SLEEP_TIME_MS = 100; Sleeper sleeper = new Sleeper(); long start = System.nanoTime(); sleeper.sleepWhileConditionMet(Suppliers.of(true), Time.milliseconds(SLEEP_TIME_MS)); long passed = (long) ((System.nanoTime() - start) * 1e-6); long difference = Math.abs(passed - SLEEP_TIME_MS); assertThat(difference, lessThanOrEqualTo(SLEEP_TIME_MS / 5)); }
RequirementsControl { public Optional<Action> getActionOnRequirement(Requirement requirement) { return Optional.ofNullable(mActionsOnRequirement.get(requirement)); } RequirementsControl(Logger logger, Map<Requirement, Action> actionsOnRequirement, Map<Subsystem, Action> defaultActionsOnSubsystems); RequirementsControl(Logger logger); void updateRequirementsNoCurrentAction(Action action); void updateRequirementsWithNewRunningAction(Action action); Optional<Action> getActionOnRequirement(Requirement requirement); void setDefaultActionOnSubsystem(Subsystem subsystem, Action action); Map<Subsystem, Action> getDefaultActionsToStart(); }
@Test public void getActionOnSubsystem_subsystemHasNoAction_returnsEmpty() throws Exception { Subsystem subsystem = mock(Subsystem.class); Optional<Action> optionalAction = mRequirementsControl.getActionOnRequirement(subsystem); assertFalse(optionalAction.isPresent()); } @Test public void getActionOnSubsystem_forSubsystemWithAction_returnsAction() throws Exception { Subsystem subsystem = mock(Subsystem.class); Action action = mock(Action.class); mActionsOnSubsystems.put(subsystem, action); Optional<Action> optionalAction = mRequirementsControl.getActionOnRequirement(subsystem); assertThat(optionalAction.get(), equalTo(action)); }
RequirementsControl { public void setDefaultActionOnSubsystem(Subsystem subsystem, Action action) { if (!action.getConfiguration().getRequirements().contains(subsystem)) { action.configure() .requires(subsystem) .save(); } mDefaultActionsOnSubsystems.put(subsystem, action); } RequirementsControl(Logger logger, Map<Requirement, Action> actionsOnRequirement, Map<Subsystem, Action> defaultActionsOnSubsystems); RequirementsControl(Logger logger); void updateRequirementsNoCurrentAction(Action action); void updateRequirementsWithNewRunningAction(Action action); Optional<Action> getActionOnRequirement(Requirement requirement); void setDefaultActionOnSubsystem(Subsystem subsystem, Action action); Map<Subsystem, Action> getDefaultActionsToStart(); }
@Test public void setDefaultActionOnSubsystem_defaultAlreadyExists_replacesAction() throws Exception { Subsystem subsystem = mock(Subsystem.class); Action action = mock(Action.class); mDefaultActionsOnSubsystems.put(subsystem, action); Action newAction = ActionsMock.actionMocker() .mockWithRequirements(Collections.singleton(subsystem)) .build(); mRequirementsControl.setDefaultActionOnSubsystem(subsystem, newAction); MatcherAssert.assertThat(mDefaultActionsOnSubsystems, IsMapContaining.hasEntry(subsystem, newAction)); } @Test public void setDefaultActionOnSubsystem_defaultNotExists_putAction() throws Exception { Subsystem subsystem = mock(Subsystem.class); Action newAction = ActionsMock.actionMocker() .mockWithRequirements(Collections.singleton(subsystem)) .build(); mRequirementsControl.setDefaultActionOnSubsystem(subsystem, newAction); MatcherAssert.assertThat(mDefaultActionsOnSubsystems, IsMapContaining.hasEntry(subsystem, newAction)); } @Test public void setDefaultActionOnSubsystem_subsystemNotInRequirements_subsystemAdded() throws Exception { Subsystem subsystem = mock(Subsystem.class); Action newAction = ActionsMock.actionMocker().build(); mRequirementsControl.setDefaultActionOnSubsystem(subsystem, newAction); MatcherAssert.assertThat(newAction.getConfiguration().getRequirements(), IsIterableContaining.hasItem(subsystem)); }
RequirementsControl { public Map<Subsystem, Action> getDefaultActionsToStart() { Map<Subsystem, Action> actionsToStart = new HashMap<>(); for (Map.Entry<Subsystem, Action> entry : mDefaultActionsOnSubsystems.entrySet()) { if (mActionsOnRequirement.containsKey(entry.getKey())) { continue; } actionsToStart.put(entry.getKey(), entry.getValue()); } return actionsToStart; } RequirementsControl(Logger logger, Map<Requirement, Action> actionsOnRequirement, Map<Subsystem, Action> defaultActionsOnSubsystems); RequirementsControl(Logger logger); void updateRequirementsNoCurrentAction(Action action); void updateRequirementsWithNewRunningAction(Action action); Optional<Action> getActionOnRequirement(Requirement requirement); void setDefaultActionOnSubsystem(Subsystem subsystem, Action action); Map<Subsystem, Action> getDefaultActionsToStart(); }
@Test public void getDefaultActionsToStart_noActionsAreRunning_returnsAll() throws Exception { Map<Subsystem, Action> defaultActions = new HashMap<>(); defaultActions.put(mock(Subsystem.class), mock(Action.class)); defaultActions.put(mock(Subsystem.class), mock(Action.class)); mDefaultActionsOnSubsystems.putAll(defaultActions); Map<Subsystem, Action> defaultActionsToStart = mRequirementsControl.getDefaultActionsToStart(); MatcherAssert.assertThat(defaultActionsToStart, IsMapWithSize.aMapWithSize(defaultActions.size())); defaultActions.forEach((s, a) -> MatcherAssert.assertThat(defaultActionsToStart, IsMapContaining.hasEntry(s, a))); } @Test public void getDefaultActionsToStart_someActionsRunning_returnsTheOnesNotRunning() throws Exception { Map<Subsystem, Action> notRunning = new HashMap<>(); notRunning.put(mock(Subsystem.class), mock(Action.class)); notRunning.put(mock(Subsystem.class), mock(Action.class)); Map<Subsystem, Action> running = new HashMap<>(); running.put(mock(Subsystem.class), mock(Action.class)); running.put(mock(Subsystem.class), mock(Action.class)); mDefaultActionsOnSubsystems.putAll(notRunning); mDefaultActionsOnSubsystems.putAll(running); mActionsOnSubsystems.putAll(running); Map<Subsystem, Action> defaultActionsToStart = mRequirementsControl.getDefaultActionsToStart(); MatcherAssert.assertThat(defaultActionsToStart, IsMapWithSize.aMapWithSize(notRunning.size())); notRunning.forEach((s, a) -> MatcherAssert.assertThat(defaultActionsToStart, IsMapContaining.hasEntry(s, a))); }
ActionControl { public void startAction(Action action) { if (mRunningActions.containsKey(action)) { throw new IllegalStateException("action already running"); } if (mNextRunActions.contains(action)) { throw new IllegalStateException("action already scheduled to run"); } mNextRunActions.add(action); } ActionControl(Clock clock, RequirementsControl requirementsControl, Map<Action, ActionContext> runningActions, Collection<Action> nextRunActions); ActionControl(Clock clock, RequirementsControl requirementsControl); Set<Map.Entry<Action, ActionContext>> getRunningActionContexts(); void startAction(Action action); void cancelAction(Action action); boolean isActionRunning(Action action); void startNewActions(); void updateActionsForNextRun(Iterable<Action> actionsToRemove); void cancelActionsIf(Predicate<? super Action> predicate); void cancelAllActions(); }
@Test public void startAction_actionNotRunning_addsToRunning() throws Exception { Action action = mock(Action.class); mActionControl.startAction(action); assertThat(mNextRunActions, IsIterableContaining.hasItem(action)); } @Test public void startAction_actionRunning_throwsIllegalStateException() throws Exception { assertThrows(IllegalStateException.class, ()-> { Action action = mock(Action.class); mRunningActions.put(action, mock(ActionContext.class)); mActionControl.startAction(action); }); } @Test public void startAction_actionRunForNext_throwsIllegalStateException() throws Exception { assertThrows(IllegalStateException.class, ()-> { Action action = mock(Action.class); mNextRunActions.add(action); mActionControl.startAction(action); }); }
ActionControl { public void cancelAction(Action action) { ActionContext context = mRunningActions.get(action); if (context != null) { context.cancelAction(); } else { throw new IllegalStateException("action is not running"); } } ActionControl(Clock clock, RequirementsControl requirementsControl, Map<Action, ActionContext> runningActions, Collection<Action> nextRunActions); ActionControl(Clock clock, RequirementsControl requirementsControl); Set<Map.Entry<Action, ActionContext>> getRunningActionContexts(); void startAction(Action action); void cancelAction(Action action); boolean isActionRunning(Action action); void startNewActions(); void updateActionsForNextRun(Iterable<Action> actionsToRemove); void cancelActionsIf(Predicate<? super Action> predicate); void cancelAllActions(); }
@Test public void cancelAction_actionRunning_cancels() throws Exception { Action action = mock(Action.class); ActionContext context = mock(ActionContext.class); mRunningActions.put(action, context); mActionControl.cancelAction(action); verify(context, times(1)).cancelAction(); } @Test public void cancelAction_actionNotRunning_throwsIllegalStateException() throws Exception { assertThrows(IllegalStateException.class, ()-> { Action action = mock(Action.class); mActionControl.cancelAction(action); }); }
Time implements Comparable<Time> { public boolean before(Time other) { return lessThan(other); } Time(long value, TimeUnit unit); static Time of(long value, TimeUnit unit); static Time milliseconds(long valueMs); static Time seconds(long valueSeconds); static Time seconds(double valueSeconds); static Time minutes(long valueMinutes); static Time minutes(double valueMinutes); long value(); TimeUnit unit(); Time toUnit(TimeUnit newTimeUnit); long valueAsMillis(); double valueAsSeconds(); boolean isValid(); Time add(Time other); Time sub(Time other); boolean before(Time other); boolean lessThan(Time other); boolean lessThanOrEquals(Time other); boolean after(Time other); boolean largerThan(Time other); boolean largerThanOrEquals(Time other); boolean equals(Time other); @Override int compareTo(Time other); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); static Time earliest(Time... times); static Time latest(Time... times); static final long INVALID_VALUE; static final Time INVALID; }
@Test public void before_thisIsNotValidOtherIsNotValid_returnsFalse() throws Exception { final Time THIS = Time.INVALID; final Time OTHER = Time.INVALID; assertFalse(THIS.before(OTHER)); }
ActionControl { public boolean isActionRunning(Action action) { return mRunningActions.containsKey(action); } ActionControl(Clock clock, RequirementsControl requirementsControl, Map<Action, ActionContext> runningActions, Collection<Action> nextRunActions); ActionControl(Clock clock, RequirementsControl requirementsControl); Set<Map.Entry<Action, ActionContext>> getRunningActionContexts(); void startAction(Action action); void cancelAction(Action action); boolean isActionRunning(Action action); void startNewActions(); void updateActionsForNextRun(Iterable<Action> actionsToRemove); void cancelActionsIf(Predicate<? super Action> predicate); void cancelAllActions(); }
@Test public void isRunning_actionNotRunning_returnsFalse() throws Exception { Action action = mock(Action.class); Assertions.assertFalse(mActionControl.isActionRunning(action)); } @Test public void isRunning_actionRunning_returnsTrue() throws Exception { Action action = mock(Action.class); mRunningActions.put(action, mock(ActionContext.class)); Assertions.assertTrue(mActionControl.isActionRunning(action)); }
ActionControl { public void updateActionsForNextRun(Iterable<Action> actionsToRemove) { actionsToRemove.forEach(this::internalRemove); } ActionControl(Clock clock, RequirementsControl requirementsControl, Map<Action, ActionContext> runningActions, Collection<Action> nextRunActions); ActionControl(Clock clock, RequirementsControl requirementsControl); Set<Map.Entry<Action, ActionContext>> getRunningActionContexts(); void startAction(Action action); void cancelAction(Action action); boolean isActionRunning(Action action); void startNewActions(); void updateActionsForNextRun(Iterable<Action> actionsToRemove); void cancelActionsIf(Predicate<? super Action> predicate); void cancelAllActions(); }
@Test public void updateActionsForNextRun_withActionsToRemove_runMarkedFinished() throws Exception { Map<Action, ActionContext> actions = new HashMap<>(); actions.put(mock(Action.class), mock(ActionContext.class)); actions.put(mock(Action.class), mock(ActionContext.class)); mRunningActions.putAll(actions); mActionControl.updateActionsForNextRun(actions.keySet()); actions.values().forEach((ctx)-> verify(ctx, times(1)).runFinished()); } @Test public void updateActionsForNextRun_withActionsToRemove_requirementsMarkedNoAction() throws Exception { Map<Action, ActionContext> actions = new HashMap<>(); actions.put(mock(Action.class), mock(ActionContext.class)); actions.put(mock(Action.class), mock(ActionContext.class)); mRunningActions.putAll(actions); mActionControl.updateActionsForNextRun(actions.keySet()); ArgumentCaptor<Action> captor = ArgumentCaptor.forClass(Action.class); verify(mRequirementsControl, times(actions.size())).updateRequirementsNoCurrentAction(captor.capture()); MatcherAssert.assertThat(captor.getAllValues(), IsIterableContainingInAnyOrder.containsInAnyOrder(actions.keySet().toArray())); }
ActionControl { public void startNewActions() { mNextRunActions.forEach(this::internalAdd); mNextRunActions.clear(); } ActionControl(Clock clock, RequirementsControl requirementsControl, Map<Action, ActionContext> runningActions, Collection<Action> nextRunActions); ActionControl(Clock clock, RequirementsControl requirementsControl); Set<Map.Entry<Action, ActionContext>> getRunningActionContexts(); void startAction(Action action); void cancelAction(Action action); boolean isActionRunning(Action action); void startNewActions(); void updateActionsForNextRun(Iterable<Action> actionsToRemove); void cancelActionsIf(Predicate<? super Action> predicate); void cancelAllActions(); }
@Test public void startNewActions_withActionsToStart_startsActions() throws Exception { Collection<Action> actions = Arrays.asList( ActionsMock.actionMocker().build(), ActionsMock.actionMocker().build() ); mNextRunActions.addAll(actions); mActionControl.startNewActions(); MatcherAssert.assertThat(mRunningActions.keySet(), IsIterableContainingInAnyOrder.containsInAnyOrder(actions.toArray())); } @Test public void startNewActions_withActionsToStart_updatesRequirements() throws Exception { Collection<Action> actions = Arrays.asList( ActionsMock.actionMocker().build(), ActionsMock.actionMocker().build() ); mNextRunActions.addAll(actions); mActionControl.startNewActions(); ArgumentCaptor<Action> captor = ArgumentCaptor.forClass(Action.class); verify(mRequirementsControl, times(actions.size())).updateRequirementsWithNewRunningAction(captor.capture()); MatcherAssert.assertThat(captor.getAllValues(), IsIterableContainingInAnyOrder.containsInAnyOrder(actions.toArray())); }
ActionControl { public void cancelAllActions() { mNextRunActions.clear(); mRunningActions.forEach(this::onInternalRemove); mRunningActions.clear(); } ActionControl(Clock clock, RequirementsControl requirementsControl, Map<Action, ActionContext> runningActions, Collection<Action> nextRunActions); ActionControl(Clock clock, RequirementsControl requirementsControl); Set<Map.Entry<Action, ActionContext>> getRunningActionContexts(); void startAction(Action action); void cancelAction(Action action); boolean isActionRunning(Action action); void startNewActions(); void updateActionsForNextRun(Iterable<Action> actionsToRemove); void cancelActionsIf(Predicate<? super Action> predicate); void cancelAllActions(); }
@Test public void stopAllActions_withRunningActions_runMarkedFinished() throws Exception { Map<Action, ActionContext> actions = new HashMap<>(); actions.put(mock(Action.class), mock(ActionContext.class)); actions.put(mock(Action.class), mock(ActionContext.class)); mRunningActions.putAll(actions); mActionControl.cancelAllActions(); actions.values().forEach((ctx)-> verify(ctx, times(1)).runFinished()); } @Test public void stopAllActions_withRunningActions_requirementsMarkedNoAction() throws Exception { Map<Action, ActionContext> actions = new HashMap<>(); actions.put(mock(Action.class), mock(ActionContext.class)); actions.put(mock(Action.class), mock(ActionContext.class)); mRunningActions.putAll(actions); mActionControl.cancelAllActions(); ArgumentCaptor<Action> captor = ArgumentCaptor.forClass(Action.class); verify(mRequirementsControl, times(actions.size())).updateRequirementsNoCurrentAction(captor.capture()); MatcherAssert.assertThat(captor.getAllValues(), IsIterableContainingInAnyOrder.containsInAnyOrder(actions.keySet().toArray())); }
SchedulerIteration { public void run(SchedulerMode mode) { mActionsToRemove.clear(); startNewActions(); runActions(mode); startDefaultSubsystemActions(mode); readyForNextRun(); } SchedulerIteration(ActionControl actionControl, RequirementsControl requirementsControl, Logger logger); void run(SchedulerMode mode); }
@Test public void run_withActions_runsActions() throws Exception { ActionContext actionContext = ActionsMock.contextMocker() .runFinished(false) .build(); mActionControlMock.runningAction(actionContext); mSchedulerIteration.run(SchedulerModeMock.mockNotDisabledMode()); verify(actionContext, times(1)).run(); } @Test public void run_subsystemsWithDefaults_startsDefaultActions() throws Exception { Subsystem subsystem = mock(Subsystem.class); Action action = mock(Action.class); mSubsystemControlMock.setDefaultAction(subsystem, action); mSchedulerIteration.run(SchedulerModeMock.mockNotDisabledMode()); verify(action, times(1)).start(); } @Test public void run_actionsIsFinished_removesAction() throws Exception { ActionContext actionContext = ActionsMock.contextMocker() .runFinished(true) .build(); Action action = mActionControlMock.runningAction(actionContext); mSchedulerIteration.run(SchedulerModeMock.mockNotDisabledMode()); mActionControlMock.verify(times(1)).updateActionsForNextRun(argThat(IsIterableContaining.hasItems(action))); } @Test public void run_disabledMode_removesActionsNotAllowedInDisabled() throws Exception { Action action = ActionsMock.actionMocker() .mockRunWhenDisabled(false) .build(); mActionControlMock.runningAction(action); mSchedulerIteration.run(SchedulerModeMock.mockDisabledMode()); mActionControlMock.verify(times(1)).updateActionsForNextRun(argThat(IsIterableContaining.hasItems(action))); } @Test public void run_disabledMode_doesNotRunNotAllowedInDisabled() throws Exception { Action action = ActionsMock.actionMocker() .mockRunWhenDisabled(false) .build(); ActionContext actionContext = mActionControlMock.runningAction(action); mSchedulerIteration.run(SchedulerModeMock.mockDisabledMode()); verify(actionContext, never()).run(); } @Test public void run_userExceptionFromAction_cancelsAction() throws Exception { Action action = ActionsMock.actionMocker() .mockRunWhenDisabled(false) .build(); ActionContext actionContext = mActionControlMock.runningAction(action); when(actionContext.run()).thenThrow(new RuntimeException()); mSchedulerIteration.run(SchedulerModeMock.mockNotDisabledMode()); verify(action, times(1)).cancel(); } @Test public void run_newActionsReady_startsThem() throws Exception { Action action = ActionsMock.actionMocker() .mockRunWhenDisabled(false) .build(); ActionContext actionContext = mActionControlMock.pendingAction(action); mSchedulerIteration.run(SchedulerModeMock.mockNotDisabledMode()); verify(actionContext, times(1)).run(); }
Time implements Comparable<Time> { public boolean after(Time other) { return largerThan(other); } Time(long value, TimeUnit unit); static Time of(long value, TimeUnit unit); static Time milliseconds(long valueMs); static Time seconds(long valueSeconds); static Time seconds(double valueSeconds); static Time minutes(long valueMinutes); static Time minutes(double valueMinutes); long value(); TimeUnit unit(); Time toUnit(TimeUnit newTimeUnit); long valueAsMillis(); double valueAsSeconds(); boolean isValid(); Time add(Time other); Time sub(Time other); boolean before(Time other); boolean lessThan(Time other); boolean lessThanOrEquals(Time other); boolean after(Time other); boolean largerThan(Time other); boolean largerThanOrEquals(Time other); boolean equals(Time other); @Override int compareTo(Time other); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); static Time earliest(Time... times); static Time latest(Time... times); static final long INVALID_VALUE; static final Time INVALID; }
@Test public void after_thisIsNotValidOtherIsNotValid_returnsFalse() throws Exception { final Time THIS = Time.INVALID; final Time OTHER = Time.INVALID; assertFalse(THIS.after(OTHER)); }
SequentialActionGroup extends ActionGroupBase { @Override public final void execute() { if (mCurrentAction == null) { startNextAction(); } handleCurrentAction(); } SequentialActionGroup(Scheduler scheduler, Clock clock, Collection<Action> actions, Queue<ActionContext> actionQueue); SequentialActionGroup(Clock clock); SequentialActionGroup(); @Override SequentialActionGroup add(Action action); @Override SequentialActionGroup add(Action... actions); @Override SequentialActionGroup add(Collection<Action> actions); @Override SequentialActionGroup andThen(Action... actions); @Override final void initialize(); @Override final void execute(); @Override boolean isFinished(); @Override void end(boolean wasInterrupted); }
@Test public void execute_noActionCurrentlyRunning_startsNextAction() throws Exception { List<Action> actions = Collections.singletonList( ActionsMock.actionMocker().build() ); ActionContext context = mock(ActionContext.class); Deque<ActionContext> contexts = new ArrayDeque<>(Collections.singleton( context )); SequentialActionGroup actionGroup = new SequentialActionGroup( mock(Scheduler.class), mClock, actions, contexts); actionGroup.execute(); verify(context, times(1)).prepareForRun(); }
PeriodicAction extends ActionBase { @Override public void execute() { if (!mNextRun.isValid() || mClock.currentTime().largerThanOrEquals(mNextRun)) { mRunnable.run(); mNextRun = mClock.currentTime().add(mPeriod); } } PeriodicAction(Clock clock, Runnable runnable, Time period, Time nextRun); PeriodicAction(Clock clock, Runnable runnable, Time period); PeriodicAction(Runnable runnable, Time period); @Override void initialize(); @Override void execute(); }
@Test public void execute_notFirstRunTimeHasElapsed_runsRunnable() throws Exception { Runnable runnable = mock(Runnable.class); Time nextRun = Time.seconds(1); when(mClock.currentTime()).thenReturn(nextRun); PeriodicAction action = new PeriodicAction(mClock, runnable, Time.seconds(1), nextRun); action.execute(); verify(runnable, times(1)).run(); } @Test public void execute_notFirstRunTimeNotElapsed_notRunsRunnable() throws Exception { Runnable runnable = mock(Runnable.class); Time nextRun = Time.seconds(2); when(mClock.currentTime()).thenReturn(Time.seconds(1)); PeriodicAction action = new PeriodicAction(mClock, runnable, Time.seconds(1), nextRun); action.execute(); verify(runnable, never()).run(); }
DoubleBuffer { public void write(T value) { int index = mReadIndex.get(); mArray.set(index, value); mReadIndex.updateAndGet(mReadIndexUpdater); } DoubleBuffer(AtomicReferenceArray<T> array, AtomicInteger readIndex); DoubleBuffer(); T read(); void write(T value); }
@Test public void write_ofObject_writesObjectToWriteIndex() throws Exception { final Object VALUE = new Object(); AtomicReferenceArray<Object> innerArray = new AtomicReferenceArray<>(2); DoubleBuffer<Object> doubleBuffer = new DoubleBuffer<>(innerArray, new AtomicInteger(0)); doubleBuffer.write(VALUE); assertEquals(VALUE, innerArray.get(0)); } @Test public void write_ofObject_swapsWriteIndex() throws Exception { final Object VALUE = new Object(); AtomicReferenceArray<Object> innerArray = new AtomicReferenceArray<>(2); AtomicInteger readIndex = new AtomicInteger(0); DoubleBuffer<Object> doubleBuffer = new DoubleBuffer<>(innerArray, readIndex); doubleBuffer.write(VALUE); assertEquals(1, readIndex.get()); }
Time implements Comparable<Time> { public boolean equals(Time other) { return CompareResult.EQUAL_TO.is(compareTo(other)); } Time(long value, TimeUnit unit); static Time of(long value, TimeUnit unit); static Time milliseconds(long valueMs); static Time seconds(long valueSeconds); static Time seconds(double valueSeconds); static Time minutes(long valueMinutes); static Time minutes(double valueMinutes); long value(); TimeUnit unit(); Time toUnit(TimeUnit newTimeUnit); long valueAsMillis(); double valueAsSeconds(); boolean isValid(); Time add(Time other); Time sub(Time other); boolean before(Time other); boolean lessThan(Time other); boolean lessThanOrEquals(Time other); boolean after(Time other); boolean largerThan(Time other); boolean largerThanOrEquals(Time other); boolean equals(Time other); @Override int compareTo(Time other); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); static Time earliest(Time... times); static Time latest(Time... times); static final long INVALID_VALUE; static final Time INVALID; }
@Test public void equals_thisIsNotValidOtherIsNotValid_returnsTrue() throws Exception { final Time THIS = Time.INVALID; final Time OTHER = Time.INVALID; assertTrue(THIS.equals(OTHER)); }
DoubleBuffer { public T read() { T value = mArray.get(mReadIndex.get()); if (value == null) { throw new NoSuchElementException("nothing to read"); } return value; } DoubleBuffer(AtomicReferenceArray<T> array, AtomicInteger readIndex); DoubleBuffer(); T read(); void write(T value); }
@Test public void read_initialValues_throwsNoSuchElementException() throws Exception { assertThrows(NoSuchElementException.class, ()->{ AtomicReferenceArray<Object> innerArray = new AtomicReferenceArray<>(2); DoubleBuffer<Object> doubleBuffer = new DoubleBuffer<>(innerArray, new AtomicInteger(0)); doubleBuffer.read(); }); } @Test public void read_valueExistsInArray_returnsThatValue() throws Exception { final Object VALUE = new Object(); AtomicReferenceArray<Object> innerArray = new AtomicReferenceArray<>(2); innerArray.set(0, VALUE); DoubleBuffer<Object> doubleBuffer = new DoubleBuffer<>(innerArray, new AtomicInteger(0)); Object read = doubleBuffer.read(); assertEquals(VALUE, read); } @Test public void read_withIndexOnItem_swapsReadIndex() throws Exception { final Object VALUE = new Object(); AtomicReferenceArray<Object> innerArray = new AtomicReferenceArray<>(2); innerArray.set(0, VALUE); AtomicInteger readIndex = new AtomicInteger(0); DoubleBuffer<Object> doubleBuffer = new DoubleBuffer<>(innerArray, readIndex); Object value = doubleBuffer.read(); assertEquals(VALUE, value); }
SyncPipeJunction implements Pipeline<T> { @Override public void process(T input) throws VisionException { for (Pipeline<? super T> pipeline : mPipelines) { pipeline.process(input); } } SyncPipeJunction(Collection<Pipeline<? super T>> pipelines); @SafeVarargs SyncPipeJunction(Pipeline<? super T>... pipelines); @Override void process(T input); @Override Pipeline<T> divergeTo(Pipeline<? super T> pipeline); }
@Test public void process_forInput_passesToAllPipes() throws Exception { final Pipeline[] PIPELINES = { mock(Pipeline.class), mock(Pipeline.class), mock(Pipeline.class) }; final Object INPUT = new Object(); SyncPipeJunction<Object> syncPipeJunction = new SyncPipeJunction<>(PIPELINES); syncPipeJunction.process(INPUT); for (Pipeline pipeline : PIPELINES) { verify(pipeline, times(1)).process(eq(INPUT)); } }
SyncPipeJunction implements Pipeline<T> { @Override public Pipeline<T> divergeTo(Pipeline<? super T> pipeline) { mPipelines.add(pipeline); return this; } SyncPipeJunction(Collection<Pipeline<? super T>> pipelines); @SafeVarargs SyncPipeJunction(Pipeline<? super T>... pipelines); @Override void process(T input); @Override Pipeline<T> divergeTo(Pipeline<? super T> pipeline); }
@Test public void divergeTo_forNewPipeline_addsPipelineToJunctionWithPreviousOnes() throws Exception { final Pipeline[] PIPELINES = { mock(Pipeline.class), mock(Pipeline.class), mock(Pipeline.class) }; final Pipeline<? super Object> NEW_PIPELINE = mock(Pipeline.class); Collection<Pipeline> pipelines = new ArrayList<>(Arrays.asList(PIPELINES)); SyncPipeJunction syncPipeJunction = new SyncPipeJunction(pipelines); syncPipeJunction.divergeTo(NEW_PIPELINE); assertThat(pipelines, containsInRelativeOrder(PIPELINES)); assertThat(pipelines, hasItem(NEW_PIPELINE)); }
ProcessorChain implements Processor { @SuppressWarnings("unchecked") @Override public Object process(Object input) throws VisionException { Object out = input; for (Processor processor : mProcessors) { out = processor.process(out); } return out; } ProcessorChain(Collection<Processor> processors); ProcessorChain(Processor... processors); @SuppressWarnings("unchecked") static Processor<T, R2> create(Processor<T, R> in, Processor<? super R, R2> out); @SuppressWarnings("unchecked") @Override Object process(Object input); @Override Processor pipeTo(Processor processor); }
@Test public void process_withTwoProcessors_processesInAndPipesToOut() throws Exception { final Object INPUT = new Object(); final Object OUTPUT_IN = new Object(); final Processor<Object, Object> PROCESSOR_IN = mockProcessorWithInputOutput(INPUT, OUTPUT_IN); final Processor<Object, Object> PROCESSOR_OUT = mock(Processor.class); ProcessorChain processorChain = new ProcessorChain(PROCESSOR_IN, PROCESSOR_OUT); processorChain.process(INPUT); verify(PROCESSOR_IN, times(1)).process(eq(INPUT)); verify(PROCESSOR_OUT, times(1)).process(eq(OUTPUT_IN)); } @Test public void process_withMultipleProcessors_processesThroughAll() throws Exception { final Object[] DATA = { new Object(), new Object(), new Object(), new Object() }; final Processor[] PROCESSORS = new Processor[DATA.length - 1]; for (int i = 0; i < PROCESSORS.length; i++) { PROCESSORS[i] = mockProcessorWithInputOutput(DATA[i], DATA[i+1]); } ProcessorChain processorChain = new ProcessorChain(PROCESSORS); processorChain.process(DATA[0]); for (int i = 0; i < PROCESSORS.length; i++) { verify(PROCESSORS[i], times(1)).process(eq(DATA[i])); } } @Test public void process_withTypedProcessors_producesCorrectEndResult() throws Exception { final Processor[] PROCESSORS = { (Processor<Object, Integer>) Object::hashCode, (Processor<Integer, String>) String::valueOf, (Processor<String, Character>) input -> input.charAt(0) }; final Object INPUT = new Object(); final Object EXPECTED_RESULT = String.valueOf(INPUT.hashCode()).charAt(0); ProcessorChain processorChain = new ProcessorChain(PROCESSORS); Object output = processorChain.process(INPUT); assertThat(output, equalTo(EXPECTED_RESULT)); }
ProcessorPair implements Processor<T, R2> { @Override public R2 process(T input) throws VisionException { R out = mIn.process(input); return mOut.process(out); } ProcessorPair(Processor<T, R> in, Processor<? super R, R2> out); @Override R2 process(T input); }
@Test public void process_forInput_processesInAndPipesToOut() throws Exception { final Object INPUT = new Object(); final Object OUTPUT_IN = new Object(); final Processor<Object, Object> PROCESSOR_IN = mock(Processor.class); when(PROCESSOR_IN.process(eq(INPUT))).thenReturn(OUTPUT_IN); final Processor<Object, Object> PROCESSOR_OUT = mock(Processor.class); ProcessorPair<Object, Object, Object> processorPair = new ProcessorPair<>(PROCESSOR_IN, PROCESSOR_OUT); processorPair.process(INPUT); verify(PROCESSOR_IN, times(1)).process(eq(INPUT)); verify(PROCESSOR_OUT, times(1)).process(eq(OUTPUT_IN)); }
RequirementsControl { public void updateRequirementsNoCurrentAction(Action action) { for (Requirement requirement : action.getConfiguration().getRequirements()) { mActionsOnRequirement.remove(requirement); } } RequirementsControl(Logger logger, Map<Requirement, Action> actionsOnRequirement, Map<Subsystem, Action> defaultActionsOnSubsystems); RequirementsControl(Logger logger); void updateRequirementsNoCurrentAction(Action action); void updateRequirementsWithNewRunningAction(Action action); Optional<Action> getActionOnRequirement(Requirement requirement); void setDefaultActionOnSubsystem(Subsystem subsystem, Action action); Map<Subsystem, Action> getDefaultActionsToStart(); }
@Test public void updateRequirementsNoCurrentAction_actionUsesAllSubsystems_removesAllSubsystems() throws Exception { Collection<Subsystem> subsystems = Arrays.asList( mock(Subsystem.class), mock(Subsystem.class), mock(Subsystem.class)); Action action = ActionsMock.actionMocker() .mockWithRequirements(subsystems) .build(); subsystems.forEach((s) -> mActionsOnSubsystems.put(s, action)); mRequirementsControl.updateRequirementsNoCurrentAction(action); MatcherAssert.assertThat(mActionsOnSubsystems, IsMapWithSize.anEmptyMap()); } @Test public void updateRequirementsNoCurrentAction_actionUsesSome_removesOnlyMatchingSubsystems() throws Exception { Collection<Subsystem> otherSubsystems = Arrays.asList( mock(Subsystem.class), mock(Subsystem.class), mock(Subsystem.class)); Collection<Subsystem> usedSubsystems = Arrays.asList( mock(Subsystem.class), mock(Subsystem.class), mock(Subsystem.class)); Action action = ActionsMock.actionMocker() .mockWithRequirements(usedSubsystems) .build(); otherSubsystems.forEach((s) -> mActionsOnSubsystems.put(s, mock(Action.class))); usedSubsystems.forEach((s) -> mActionsOnSubsystems.put(s, action)); mRequirementsControl.updateRequirementsNoCurrentAction(action); MatcherAssert.assertThat(mActionsOnSubsystems.keySet(), IsIterableWithSize.iterableWithSize(otherSubsystems.size())); MatcherAssert.assertThat(mActionsOnSubsystems.keySet(), IsIterableContainingInAnyOrder.containsInAnyOrder(otherSubsystems.toArray())); }
InProcessorJunction implements Processor<T, R> { @Override public R process(T input) throws VisionException { mPipeline.process(input); return mProcessor.process(input); } InProcessorJunction(Processor<T, R> processor, Pipeline<? super T> pipeline); @Override R process(T input); @Override Processor<T, R> divergeIn(Pipeline<? super T> pipeline); }
@Test public void process_forInput_processesAndPipesInputToPipeline() throws Exception { final Object INPUT = new Object(); final Processor<Object, Object> PROCESSOR = mock(Processor.class); final Pipeline<Object> PIPELINE = mock(Pipeline.class); InProcessorJunction<Object, Object> inProcessorJunction = new InProcessorJunction<>(PROCESSOR, PIPELINE); inProcessorJunction.process(INPUT); verify(PROCESSOR, times(1)).process(eq(INPUT)); verify(PIPELINE, times(1)).process(eq(INPUT)); }
OutProcessorJunction implements Processor<T, R> { @Override public R process(T input) throws VisionException { R out = mProcessor.process(input); mPipeline.process(out); return out; } OutProcessorJunction(Processor<T, R> processor, Pipeline<? super R> pipeline); @Override R process(T input); @Override Processor<T, R> divergeOut(Pipeline<? super R> pipeline); }
@Test public void process_forInput_processesAndPipesOutputToPipeline() throws Exception { final Object INPUT = new Object(); final Object OUTPUT = new Object(); final Processor<Object, Object> PROCESSOR = mock(Processor.class); when(PROCESSOR.process(eq(INPUT))).thenReturn(OUTPUT); final Pipeline<Object> PIPELINE = mock(Pipeline.class); OutProcessorJunction<Object, Object> outProcessorJunction = new OutProcessorJunction<>(PROCESSOR, PIPELINE); outProcessorJunction.process(INPUT); verify(PROCESSOR, times(1)).process(eq(INPUT)); verify(PIPELINE, times(1)).process(eq(OUTPUT)); }
RequirementsControl { public void updateRequirementsWithNewRunningAction(Action action) { for (Requirement requirement : action.getConfiguration().getRequirements()) { if (mActionsOnRequirement.containsKey(requirement)) { Action currentAction = mActionsOnRequirement.get(requirement); currentAction.cancel(); mLogger.warn("Requirements conflict in Scheduler between {} and new action {} over requirement {}", currentAction.toString(), action.toString(), requirement.toString()); } mActionsOnRequirement.put(requirement, action); } } RequirementsControl(Logger logger, Map<Requirement, Action> actionsOnRequirement, Map<Subsystem, Action> defaultActionsOnSubsystems); RequirementsControl(Logger logger); void updateRequirementsNoCurrentAction(Action action); void updateRequirementsWithNewRunningAction(Action action); Optional<Action> getActionOnRequirement(Requirement requirement); void setDefaultActionOnSubsystem(Subsystem subsystem, Action action); Map<Subsystem, Action> getDefaultActionsToStart(); }
@Test public void updateRequirementsWithNewRunningAction_actionWithSomeRequirements_addsRequirementsToMap() throws Exception { Collection<Subsystem> otherSubsystems = Arrays.asList( mock(Subsystem.class), mock(Subsystem.class), mock(Subsystem.class)); Collection<Subsystem> usedSubsystems = Arrays.asList( mock(Subsystem.class), mock(Subsystem.class), mock(Subsystem.class)); Action action = ActionsMock.actionMocker() .mockWithRequirements(usedSubsystems) .build(); otherSubsystems.forEach((s) -> mActionsOnSubsystems.put(s, mock(Action.class))); mRequirementsControl.updateRequirementsWithNewRunningAction(action); MatcherAssert.assertThat(mActionsOnSubsystems, IsMapWithSize.aMapWithSize(usedSubsystems.size() + otherSubsystems.size())); otherSubsystems.forEach((s)-> MatcherAssert.assertThat(mActionsOnSubsystems, IsMapContaining.hasEntry(equalTo(s), any(Action.class)))); usedSubsystems.forEach((s)-> MatcherAssert.assertThat(mActionsOnSubsystems, IsMapContaining.hasEntry(s, action))); } @Test public void updateRequirementsWithNewRunningAction_requirementHasAction_cancelsAction() throws Exception { Subsystem subsystem = mock(Subsystem.class); Action action = mock(Action.class); mActionsOnSubsystems.put(subsystem, action); Action newAction = ActionsMock.actionMocker() .mockWithRequirements(Collections.singleton(subsystem)) .build(); mRequirementsControl.updateRequirementsWithNewRunningAction(newAction); verify(action, times(1)).cancel(); } @Test public void updateRequirementsWithNewRunningAction_requirementHasAction_replacesAction() throws Exception { Subsystem subsystem = mock(Subsystem.class); Action action = mock(Action.class); mActionsOnSubsystems.put(subsystem, action); Action newAction = ActionsMock.actionMocker() .mockWithRequirements(Collections.singleton(subsystem)) .build(); mRequirementsControl.updateRequirementsWithNewRunningAction(newAction); MatcherAssert.assertThat(mActionsOnSubsystems, Matchers.not(IsMapContaining.hasEntry(action, subsystem))); }
SPARQLBasedTrivialInconsistencyFinder extends AbstractTrivialInconsistencyFinder { @Override public void run(boolean resume) { for(AbstractTrivialInconsistencyFinder checker : incFinders){ if(!(checker instanceof InverseFunctionalityBasedInconsistencyFinder) || isApplyUniqueNameAssumption()){ try { checker.run(resume); fireNumberOfConflictsFound(checker.getExplanations().size()); if(checker.terminationCriteriaSatisfied()){ break; } } catch (Exception e) { e.printStackTrace(); } } } if(!terminationCriteriaSatisfied()){ fireFinished(); completed = true; } } SPARQLBasedTrivialInconsistencyFinder(SparqlEndpointKS ks); SPARQLBasedTrivialInconsistencyFinder(SparqlEndpointKS ks, InconsistencyType... inconsistencyTypes); void setInconsistencyTypes(InconsistencyType... inconsistencyTypes); @Override void setApplyUniqueNameAssumption(boolean applyUniqueNameAssumption); @Override void setStopIfInconsistencyFound(boolean stopIfInconsistencyFound); @Override void setAxiomsToIgnore(Set<OWLAxiom> axiomsToIgnore); @Override void addProgressMonitor(SPARQLBasedInconsistencyProgressMonitor mon); @Override void run(boolean resume); boolean isCompleted(); static void main(String[] args); }
@Test public void testRun() { incFinder.run(); } @Test public void testGetExplanations() { incFinder.run(); Set<Explanation<OWLAxiom>> explanations = incFinder.getExplanations(); for (Explanation<OWLAxiom> explanation : explanations) { System.out.println(explanation.getAxioms()); } }
GenerateTradeData { public List<Trade> createRandomData(int number) throws Exception { return null; } Trade createTradeData(int number, List<Party> partyList, List<Instrument> instrumentList); List<Trade> createRandomData(int number); }
@Test public void testGenerateRandomInstrument() throws Exception { GenerateRandomInstruments ranIns = new GenerateRandomInstruments(); assert (ranIns.createRandomData(50).size() == 50); } @Test public void testGeneratePartyData() throws Exception { GenerateRandomParty ransPty = new GenerateRandomParty(); assert (ransPty.createRandomData(50).size() == 50); }
SegmentedLog { public void truncateSuffix(long newEndIndex) { if (newEndIndex >= getLastLogIndex()) { return; } LOG.info("Truncating log from old end index {} to new end index {}", getLastLogIndex(), newEndIndex); while (!startLogIndexSegmentMap.isEmpty()) { Segment segment = startLogIndexSegmentMap.lastEntry().getValue(); try { if (newEndIndex == segment.getEndIndex()) { break; } else if (newEndIndex < segment.getStartIndex()) { totalSize -= segment.getFileSize(); segment.getRandomAccessFile().close(); String fullFileName = logDataDir + File.separator + segment.getFileName(); FileUtils.forceDelete(new File(fullFileName)); startLogIndexSegmentMap.remove(segment.getStartIndex()); } else if (newEndIndex < segment.getEndIndex()) { int i = (int) (newEndIndex + 1 - segment.getStartIndex()); segment.setEndIndex(newEndIndex); long newFileSize = segment.getEntries().get(i).offset; totalSize -= (segment.getFileSize() - newFileSize); segment.setFileSize(newFileSize); segment.getEntries().removeAll( segment.getEntries().subList(i, segment.getEntries().size())); FileChannel fileChannel = segment.getRandomAccessFile().getChannel(); fileChannel.truncate(segment.getFileSize()); fileChannel.close(); segment.getRandomAccessFile().close(); String oldFullFileName = logDataDir + File.separator + segment.getFileName(); String newFileName = String.format("%020d-%020d", segment.getStartIndex(), segment.getEndIndex()); segment.setFileName(newFileName); String newFullFileName = logDataDir + File.separator + segment.getFileName(); new File(oldFullFileName).renameTo(new File(newFullFileName)); segment.setRandomAccessFile(RaftFileUtils.openFile(logDataDir, segment.getFileName(), "rw")); } } catch (IOException ex) { LOG.warn("io exception, msg={}", ex.getMessage()); } } } SegmentedLog(String raftDataDir, int maxSegmentFileSize); RaftProto.LogEntry getEntry(long index); long getEntryTerm(long index); long getFirstLogIndex(); long getLastLogIndex(); long append(List<RaftProto.LogEntry> entries); void truncatePrefix(long newFirstIndex); void truncateSuffix(long newEndIndex); void loadSegmentData(Segment segment); void readSegments(); RaftProto.LogMetaData readMetaData(); void updateMetaData(Long currentTerm, Integer votedFor, Long firstLogIndex, Long commitIndex); RaftProto.LogMetaData getMetaData(); long getTotalSize(); }
@Test public void testTruncateSuffix() throws IOException { String raftDataDir = "./data"; SegmentedLog segmentedLog = new SegmentedLog(raftDataDir, 32); Assert.assertTrue(segmentedLog.getFirstLogIndex() == 1); List<RaftProto.LogEntry> entries = new ArrayList<>(); for (int i = 1; i < 10; i++) { RaftProto.LogEntry entry = RaftProto.LogEntry.newBuilder() .setData(ByteString.copyFrom(("testEntryData" + i).getBytes())) .setType(RaftProto.EntryType.ENTRY_TYPE_DATA) .setIndex(i) .setTerm(i) .build(); entries.add(entry); } long lastLogIndex = segmentedLog.append(entries); Assert.assertTrue(lastLogIndex == 9); segmentedLog.truncatePrefix(5); FileUtils.deleteDirectory(new File(raftDataDir)); }
Snapshot { public TreeMap<String, SnapshotDataFile> openSnapshotDataFiles() { TreeMap<String, SnapshotDataFile> snapshotDataFileMap = new TreeMap<>(); String snapshotDataDir = snapshotDir + File.separator + "data"; try { Path snapshotDataPath = FileSystems.getDefault().getPath(snapshotDataDir); snapshotDataPath = snapshotDataPath.toRealPath(); snapshotDataDir = snapshotDataPath.toString(); List<String> fileNames = RaftFileUtils.getSortedFilesInDirectory(snapshotDataDir, snapshotDataDir); for (String fileName : fileNames) { RandomAccessFile randomAccessFile = RaftFileUtils.openFile(snapshotDataDir, fileName, "r"); SnapshotDataFile snapshotFile = new SnapshotDataFile(); snapshotFile.fileName = fileName; snapshotFile.randomAccessFile = randomAccessFile; snapshotDataFileMap.put(fileName, snapshotFile); } } catch (IOException ex) { LOG.warn("readSnapshotDataFiles exception:", ex); throw new RuntimeException(ex); } return snapshotDataFileMap; } Snapshot(String raftDataDir); void reload(); TreeMap<String, SnapshotDataFile> openSnapshotDataFiles(); void closeSnapshotDataFiles(TreeMap<String, SnapshotDataFile> snapshotDataFileMap); RaftProto.SnapshotMetaData readMetaData(); void updateMetaData(String dir, Long lastIncludedIndex, Long lastIncludedTerm, RaftProto.Configuration configuration); RaftProto.SnapshotMetaData getMetaData(); String getSnapshotDir(); AtomicBoolean getIsInstallSnapshot(); AtomicBoolean getIsTakeSnapshot(); Lock getLock(); }
@Test public void testReadSnapshotDataFiles() throws IOException { String raftDataDir = "./data"; File file = new File("./data/message"); file.mkdirs(); File file1 = new File("./data/message/queue1.txt"); file1.createNewFile(); File file2 = new File("./data/message/queue2.txt"); file2.createNewFile(); File snapshotFile = new File("./data/snapshot"); snapshotFile.mkdirs(); Path link = FileSystems.getDefault().getPath("./data/snapshot/data"); Path target = FileSystems.getDefault().getPath("./data/message").toRealPath(); Files.createSymbolicLink(link, target); Snapshot snapshot = new Snapshot(raftDataDir); TreeMap<String, Snapshot.SnapshotDataFile> snapshotFileMap = snapshot.openSnapshotDataFiles(); System.out.println(snapshotFileMap.keySet()); Assert.assertTrue(snapshotFileMap.size() == 2); Assert.assertTrue(snapshotFileMap.firstKey().equals("queue1.txt")); Files.delete(link); FileUtils.deleteDirectory(new File(raftDataDir)); }
MergedItem { static MergedItem newInjectedRow(int type) { return new MergedItem(type, type, true); } private MergedItem(int type, long id, boolean injected); @Override boolean equals(Object o); }
@Test public void testNewInjectedRowBuilder() { MergedItem mergedItem = MergedItem.newInjectedRow(1); assertThat(mergedItem.injected, is(true)); assertThat(mergedItem.type, is(1)); assertThat(mergedItem.id, is(1L)); }
ItemsMerger { List<MergedItem> mergeItems() { MergeStrategy mergeStrategy = getMergeStrategy(); return mergeStrategy.mergeItems(); } ItemsMerger(ItemsDataProvider itemsDataProvider, MergeOptionsProvider mergeOptionsProvider); }
@Test public void hidesInjectedItemsOnEmptyChildItemsIfNotAllowed() { Item Injected_0_1 = createInjectedItem(0, 0); Item Injected_5_1 = createInjectedItem(5, 1); ItemsMerger itemsMerger = new ItemsMerger( createItemsDataProvider(Arrays.asList(Injected_0_1, Injected_5_1), Collections.<Item>emptyList()), createMergeOptions(false, false, true) ); assertThat(itemsMerger.mergeItems().isEmpty(), is(true)); } @Test public void showsInjectedItemsOnCorrectPositionOnNonEmptyChildItems() { Item Injected_0_1 = createInjectedItem(0, 0); Item Injected_5_1 = createInjectedItem(5, 1); List<Item> childItems = createChildItem(1, 1, 50); ItemsMerger itemsMerger = new ItemsMerger( createItemsDataProvider(Arrays.asList(Injected_0_1, Injected_5_1), childItems), createMergeOptions(false, false, true) ); List<MergedItem> mergedItems = itemsMerger.mergeItems(); childItems.add(Injected_0_1.position, Injected_0_1); childItems.add(Injected_5_1.position, Injected_5_1); assertEquals(createMergedItemsList(childItems), mergedItems); } @Test public void hidesInjectedItemsOnHigherPositionOnNonEmptyChildItemsIfNotAllowed() { Item Injected_0_1 = createInjectedItem(0, 0); Item Injected_5_1 = createInjectedItem(5, 1); Item Injected_5_2 = createInjectedItem(60, 2); List<Item> childItems = createChildItem(1, 1, 50); ItemsMerger itemsMerger = new ItemsMerger( createItemsDataProvider(Arrays.asList(Injected_0_1, Injected_5_1, Injected_5_2), childItems), createMergeOptions(false, false, true) ); List<MergedItem> mergedItems = itemsMerger.mergeItems(); childItems.add(Injected_0_1.position, Injected_0_1); childItems.add(Injected_5_1.position, Injected_5_1); assertEquals(createMergedItemsList(childItems), mergedItems); } @Test public void showsInjectedItemsOnHigherPositionOnNonEmptyChildItemsIfAllowed() { Item Injected_0_1 = createInjectedItem(0, 0); Item Injected_5_1 = createInjectedItem(5, 1); Item Injected_5_2 = createInjectedItem(60, 2); List<Item> childItems = createChildItem(1, 1, 50); ItemsMerger itemsMerger = new ItemsMerger( createItemsDataProvider(Arrays.asList(Injected_0_1, Injected_5_1, Injected_5_2), childItems), createMergeOptions(false, true, true) ); List<MergedItem> mergedItems = itemsMerger.mergeItems(); childItems.add(Injected_0_1.position, Injected_0_1); childItems.add(Injected_5_1.position, Injected_5_1); childItems.add(Injected_5_2); assertEquals(createMergedItemsList(childItems), mergedItems); } @Test public void hidesInjectedItemsWhenNeeded() { Item Injected_0_1 = createInjectedItem(0, 0); Item Injected_5_1 = createInjectedItem(5, 1); List<Item> childItems = createChildItem(1, 1, 50); ItemsMerger itemsMerger = new ItemsMerger( createItemsDataProvider(Arrays.asList(Injected_0_1, Injected_5_1), childItems), createMergeOptions(true, true, false) ); List<MergedItem> mergedItems = itemsMerger.mergeItems(); assertEquals(createMergedItemsList(childItems), mergedItems); } @Test public void showsInjectedItemsOnEmptyChildItemsIfAllowed() { Item Injected_0_1 = createInjectedItem(0, 0); Item Injected_5_1 = createInjectedItem(5, 1); ItemsMerger itemsMerger = new ItemsMerger( createItemsDataProvider(Arrays.asList(Injected_0_1, Injected_5_1), Collections.<Item>emptyList()), createMergeOptions(true, false, true) ); assertEquals(itemsMerger.mergeItems(), createMergedItemsList(Arrays.asList(Injected_0_1, Injected_5_1))); }
MergedItem { static MergedItem newRow(int type, long id) { return new MergedItem(type, id, false); } private MergedItem(int type, long id, boolean injected); @Override boolean equals(Object o); }
@Test public void testNewRowBuilder() { MergedItem mergedItem = MergedItem.newRow(1, 2L); assertThat(mergedItem.injected, is(false)); assertThat(mergedItem.type, is(1)); assertThat(mergedItem.id, is(2L)); } @Test public void testMergedItemEqual() { MergedItem mergedItem1 = MergedItem.newRow(1, 2L); MergedItem mergedItem2 = MergedItem.newRow(1, 2L); MergedItem mergedItem3 = MergedItem.newRow(1, 3L); assertThat(mergedItem1, is(mergedItem2)); assertThat(mergedItem1, is(not(mergedItem3))); }
VectorCalculator { int[] calculateFromChildItemPositionTranslationVector() { int maxInjectedItemPosition = getMaxInjectedItemPosition(); if (maxInjectedItemPosition != NO_POSITION) { int vectorSize = maxInjectedItemPosition - dataProvider.getInjectedItemCount() + 2; int[] vector = new int[vectorSize]; int accumulator = 0; int vectorIndex = 0; for (int i = 0; vectorIndex < vectorSize; i++) { if (!dataProvider.isItemInjectedOnPosition(i)) { vector[vectorIndex++] = accumulator; } else { accumulator++; } } return vector; } else { return EMPTY_VECTOR; } } VectorCalculator(DataProvider dataProvider); }
@Test public void calculateFromChildItemPositionTranslationVector() throws Exception { testFromChildVectorValue(Collections.<Integer>emptyList(), new int[]{ 0 }); testFromChildVectorValue(new ArrayList<Integer>() {{ add(0); }}, new int[]{ 1 }); testFromChildVectorValue(new ArrayList<Integer>() {{ add(1); add(2); add(3); add(5); }}, new int[]{ 0, 3, 4 }); testFromChildVectorValue(new ArrayList<Integer>() {{ add(0); add(2); add(4); add(5); add(7); }}, new int[]{ 1, 2, 4, 5 }); }
VectorCalculator { int[] calculateNumberOfInjectedItemsUpToPosition() { int maxInjectedItemPosition = getMaxInjectedItemPosition(); if (maxInjectedItemPosition != NO_POSITION) { int[] vector = new int[maxInjectedItemPosition + 1]; int previousValue = 0; for (int i = 0; i < vector.length; i++) { vector[i] = previousValue + (dataProvider.isItemInjectedOnPosition(i) ? 1 : 0); previousValue = vector[i]; } return vector; } else { return EMPTY_VECTOR; } } VectorCalculator(DataProvider dataProvider); }
@Test public void calculateNumberOfInjectedItemsUpToPosition() throws Exception { testNumberOfInjectedItemsVectorValue(Collections.<Integer>emptyList(), new int[]{ 0 }); testNumberOfInjectedItemsVectorValue(new ArrayList<Integer>() {{ add(0); }}, new int[]{ 1 }); testNumberOfInjectedItemsVectorValue(new ArrayList<Integer>() {{ add(1); add(2); add(3); add(5); }}, new int[]{ 0, 1, 2, 3, 3, 4 }); testNumberOfInjectedItemsVectorValue(new ArrayList<Integer>() {{ add(0); add(2); add(4); add(5); add(7); }}, new int[]{ 1, 1, 2, 2, 3, 4, 4, 5 }); }
MergedListDiffer extends DiffUtil.Callback { void updateData(List<MergedItem> oldList, List<MergedItem> newList) { this.oldList = oldList; this.newList = newList; } @Override int getOldListSize(); @Override int getNewListSize(); @Override boolean areItemsTheSame(int oldItemPosition, int newItemPosition); @Override boolean areContentsTheSame(int oldItemPosition, int newItemPosition); }
@Test public void returnsCorrectSizeOfOldList() { MergedListDiffer mergedListDiffer = new MergedListDiffer(); mergedListDiffer.updateData(new ArrayList<MergedItem>() {{ add(MergedItem.newInjectedRow(2)); add(MergedItem.newInjectedRow(3)); }}, Collections.<MergedItem>emptyList()); }
MergedListDiffer extends DiffUtil.Callback { @Override public boolean areItemsTheSame(int oldItemPosition, int newItemPosition) { MergedItem oldRow = oldList.get(oldItemPosition); MergedItem newRow = newList.get(newItemPosition); return oldRow.type == newRow.type && oldRow.id == newRow.id; } @Override int getOldListSize(); @Override int getNewListSize(); @Override boolean areItemsTheSame(int oldItemPosition, int newItemPosition); @Override boolean areContentsTheSame(int oldItemPosition, int newItemPosition); }
@Test public void testAreItemsTheSame() { MergedListDiffer mergedListDiffer = new MergedListDiffer(); mergedListDiffer.updateData(new ArrayList<MergedItem>() {{ add(MergedItem.newInjectedRow(2)); add(MergedItem.newInjectedRow(3)); }}, new ArrayList<MergedItem>() {{ add(MergedItem.newInjectedRow(2)); add(MergedItem.newInjectedRow(4)); }}); assertThat(mergedListDiffer.areItemsTheSame(0, 0), is(true)); assertThat(mergedListDiffer.areItemsTheSame(1, 1), is(false)); }
MergedListDiffer extends DiffUtil.Callback { @Override public boolean areContentsTheSame(int oldItemPosition, int newItemPosition) { return true; } @Override int getOldListSize(); @Override int getNewListSize(); @Override boolean areItemsTheSame(int oldItemPosition, int newItemPosition); @Override boolean areContentsTheSame(int oldItemPosition, int newItemPosition); }
@Test public void areContentsTheSameAlwaysReturnsTrue() { MergedListDiffer mergedListDiffer = new MergedListDiffer(); assertThat(mergedListDiffer.areContentsTheSame(1, 1), is(true)); }
Parameter implements Cloneable { public Parameter(String name) { setNameAndParent(name,null); } Parameter(String name); Parameter(String name, boolean value); Parameter(String name, int value); Parameter(String name, long value); Parameter(String name, float value); Parameter(String name, double value); Parameter(String name, String value); Parameter(String name, boolean[] values); Parameter(String name, int[] values); Parameter(String name, long[] values); Parameter(String name, float[] values); Parameter(String name, double[] values); Parameter(String name, String[] values); Parameter(String name, boolean value, String units); Parameter(String name, int value, String units); Parameter(String name, long value, String units); Parameter(String name, float value, String units); Parameter(String name, double value, String units); Parameter(String name, String value, String units); Parameter(String name, boolean[] values, String units); Parameter(String name, int[] values, String units); Parameter(String name, long[] values, String units); Parameter(String name, float[] values, String units); Parameter(String name, double[] values, String units); Parameter(String name, String[] values, String units); Parameter(String name, ParameterSet parent); Object clone(); Parameter replaceWith(Parameter par); Parameter copyTo(ParameterSet parent); Parameter copyTo(ParameterSet parent, String name); Parameter moveTo(ParameterSet parent); Parameter moveTo(ParameterSet parent, String name); void remove(); String getName(); void setName(String name); String getUnits(); void setUnits(String units); int getType(); void setType(int type); ParameterSet getParent(); boolean getBoolean(); int getInt(); long getLong(); float getFloat(); double getDouble(); String getString(); boolean[] getBooleans(); int[] getInts(); long[] getLongs(); float[] getFloats(); double[] getDoubles(); String[] getStrings(); void setBoolean(boolean value); void setInt(int value); void setLong(long value); void setFloat(float value); void setDouble(double value); void setString(String value); void setBooleans(boolean[] values); void setInts(int[] values); void setLongs(long[] values); void setFloats(float[] values); void setDoubles(double[] values); void setStrings(String[] values); boolean isNull(); boolean isBoolean(); boolean isInt(); boolean isLong(); boolean isFloat(); boolean isDouble(); boolean isString(); String toString(); boolean equals(Object o); int hashCode(); final static int NULL; final static int BOOLEAN; final static int INT; final static int LONG; final static int FLOAT; final static int DOUBLE; final static int STRING; }
@Test public void testParameter() { Parameter par = new Parameter("fo<o","Hello"); assertEquals("Hello",par.getString()); par.setString("true"); assertTrue(par.getBoolean()); par.setString("3141"); assertEquals(3141,par.getInt()); par.setString("3141.0"); assertEquals(3141.0f,par.getFloat()); par.setString("3.141"); assertEquals(3.141,par.getDouble()); double[] empty = new double[0]; par.setDoubles(empty); assertEquals(Parameter.DOUBLE,par.getType()); par.setFloats(null); assertEquals(Parameter.FLOAT,par.getType()); float[] fvalues = {1.2f,3.4f}; par.setFloats(fvalues); fvalues = par.getFloats(); assertEquals(1.2f,fvalues[0]); assertEquals(3.4f,fvalues[1]); par.setUnits("km/s"); assertEquals("km/s",par.getUnits()); boolean[] bvalues = {true,false}; par.setBooleans(bvalues); bvalues = par.getBooleans(); assertTrue(bvalues[0]); assertFalse(bvalues[1]); par.setUnits(null); assertNull(par.getUnits()); }
DMatrixSvd { public int rank() { double eps = ulp(1.0); double tol = max(_m,_n)*_s[0]*eps; int r = 0; for (int i=0; i<_mn; ++i) { if (_s[i]>tol) ++r; } return r; } DMatrixSvd(DMatrix a); DMatrix getU(); DMatrix getS(); double[] getSingularValues(); DMatrix getV(); DMatrix getVTranspose(); double norm2(); double cond(); int rank(); }
@Test public void testRank() { DMatrix a = new DMatrix(new double[][]{ {1.0, 3.0}, {7.0, 9.0}, }); DMatrixSvd svda = new DMatrixSvd(a); assertEqualExact(svda.rank(),2); DMatrix b = new DMatrix(new double[][]{ {1.0, 3.0}, {7.0, 9.0}, {0.0, 0.0}, }); DMatrixSvd svdb = new DMatrixSvd(b); assertEqualExact(svdb.rank(),2); DMatrix c = new DMatrix(new double[][]{ {1.0, 3.0, 0.0}, {7.0, 9.0, 0.0}, }); DMatrixSvd svdc = new DMatrixSvd(c); assertEqualExact(svdc.rank(),2); }
Geometry { public static double inCircle( double xa, double ya, double xb, double yb, double xc, double yc, double xd, double yd) { double adx = xa - xd; double bdx = xb - xd; double cdx = xc - xd; double ady = ya - yd; double bdy = yb - yd; double cdy = yc - yd; double bdxcdy = bdx * cdy; double cdxbdy = cdx * bdy; double alift = adx * adx + ady * ady; double cdxady = cdx * ady; double adxcdy = adx * cdy; double blift = bdx * bdx + bdy * bdy; double adxbdy = adx * bdy; double bdxady = bdx * ady; double clift = cdx * cdx + cdy * cdy; double det = alift * (bdxcdy - cdxbdy) + blift * (cdxady - adxcdy) + clift * (adxbdy - bdxady); if (bdxcdy<0.0) bdxcdy = -bdxcdy; if (cdxbdy<0.0) cdxbdy = -cdxbdy; if (adxcdy<0.0) adxcdy = -adxcdy; if (cdxady<0.0) cdxady = -cdxady; if (adxbdy<0.0) adxbdy = -adxbdy; if (bdxady<0.0) bdxady = -bdxady; double permanent = alift * (bdxcdy + cdxbdy) + blift * (cdxady + adxcdy) + clift * (adxbdy + bdxady); double errbound = INCERRBOUND * permanent; if (det>errbound || -det>errbound) return det; return inCircleExact(xa,ya,xb,yb,xc,yc,xd,yd); } static double leftOfLine( double xa, double ya, double xb, double yb, double xc, double yc); static double leftOfLine( double[] pa, double[] pb, double[] pc); static double leftOfLine( float[] pa, float[] pb, float[] pc); static double leftOfLineFast( double xa, double ya, double xb, double yb, double xc, double yc); static double leftOfLineFast( double[] pa, double[] pb, double[] pc); static double leftOfLineFast( float[] pa, float[] pb, float[] pc); static double leftOfPlane( double xa, double ya, double za, double xb, double yb, double zb, double xc, double yc, double zc, double xd, double yd, double zd); static double leftOfPlane( double[] pa, double[] pb, double[] pc, double[] pd); static double leftOfPlane( float[] pa, float[] pb, float[] pc, float[] pd); static double leftOfPlaneFast( double xa, double ya, double za, double xb, double yb, double zb, double xc, double yc, double zc, double xd, double yd, double zd); static double leftOfPlaneFast( double[] pa, double[] pb, double[] pc, double[] pd); static double leftOfPlaneFast( float[] pa, float[] pb, float[] pc, float[] pd); static double inCircle( double xa, double ya, double xb, double yb, double xc, double yc, double xd, double yd); static double inCircle( double[] pa, double[] pb, double[] pc, double[] pd); static double inCircle( float[] pa, float[] pb, float[] pc, float[] pd); static double inCircleFast( double xa, double ya, double xb, double yb, double xc, double yc, double xd, double yd); static double inCircleFast( double[] pa, double[] pb, double[] pc, double[] pd); static double inCircleFast( float[] pa, float[] pb, float[] pc, float[] pd); static double inSphere( double xa, double ya, double za, double xb, double yb, double zb, double xc, double yc, double zc, double xd, double yd, double zd, double xe, double ye, double ze); static double inSphere( double[] pa, double[] pb, double[] pc, double[] pd, double[] pe); static double inSphere( float[] pa, float[] pb, float[] pc, float[] pd, float[] pe); static double inSphereFast( double xa, double ya, double za, double xb, double yb, double zb, double xc, double yc, double zc, double xd, double yd, double zd, double xe, double ye, double ze); static double inSphereFast( double[] pa, double[] pb, double[] pc, double[] pd, double[] pe); static double inSphereFast( float[] pa, float[] pb, float[] pc, float[] pd, float[] pe); static double inOrthoSphere( double xa, double ya, double za, double wa, double xb, double yb, double zb, double wb, double xc, double yc, double zc, double wc, double xd, double yd, double zd, double wd, double xe, double ye, double ze, double we); static double inOrthoSphere( double[] pa, double[] pb, double[] pc, double[] pd, double[] pe); static double inOrthoSphere( float[] pa, float[] pb, float[] pc, float[] pd, float[] pe); static double inOrthoSphereFast( double xa, double ya, double za, double wa, double xb, double yb, double zb, double wb, double xc, double yc, double zc, double wc, double xd, double yd, double zd, double wd, double xe, double ye, double ze, double we); static double inOrthoSphereFast( double[] pa, double[] pb, double[] pc, double[] pd, double[] pe); static double inOrthoSphereFast( float[] pa, float[] pb, float[] pc, float[] pd, float[] pe); static void centerCircle( float xa, float ya, float xb, float yb, float xc, float yc, float[] po); static void centerCircle( float[] pa, float[] pb, float[] pc, float[] po); static void centerCircle( double xa, double ya, double xb, double yb, double xc, double yc, double[] po); static void centerCircle( double[] pa, double[] pb, double[] pc, double[] po); static void centerSphere( float xa, float ya, float za, float xb, float yb, float zb, float xc, float yc, float zc, float xd, float yd, float zd, float[] po); static void centerSphere( float[] pa, float[] pb, float[] pc, float[] pd, float[] po); static void centerSphere( double xa, double ya, double za, double xb, double yb, double zb, double xc, double yc, double zc, double xd, double yd, double zd, double[] po); static void centerSphere( double[] pa, double[] pb, double[] pc, double[] pd, double[] po); static void centerCircle3D( double xa, double ya, double za, double xb, double yb, double zb, double xc, double yc, double zc, double[] po); }
@Test public void testInCircle() { float xxxx = 3.14159f; float yyyy = 1.00e15f; float pa[] = {xxxx,0.0f}; float pb[] = {0.0f,yyyy}; float pc[] = {0.0f,0.0f}; float pd[] = {xxxx,yyyy}; double ra,rf; trace(""); ra = Geometry.inCircle(pa,pb,pc,pd); rf = Geometry.inCircleFast(pa,pb,pc,pd); trace("0 inCircle: "+String.format("%26.18e",ra)); trace("0 inCircleFast: "+String.format("%26.18e",rf)); assertTrue(ra==0.0); pd[X] = xxxx*(1.0f-FLT_EPSILON); ra = Geometry.inCircle(pa,pb,pc,pd); rf = Geometry.inCircleFast(pa,pb,pc,pd); trace("+ inCircle: "+String.format("%26.18e",ra)); trace("+ inCircleFast: "+String.format("%26.18e",rf)); assertTrue(ra>0.0); pd[X] = xxxx*(1.0f+FLT_EPSILON); ra = Geometry.inCircle(pa,pb,pc,pd); rf = Geometry.inCircleFast(pa,pb,pc,pd); trace("- inCircle: "+String.format("%26.18e",ra)); trace("- inCircleFast: "+String.format("%26.18e",rf)); assertTrue(ra<0.0); }
Geometry { public static double inSphere( double xa, double ya, double za, double xb, double yb, double zb, double xc, double yc, double zc, double xd, double yd, double zd, double xe, double ye, double ze) { double aex = xa - xe; double bex = xb - xe; double cex = xc - xe; double dex = xd - xe; double aey = ya - ye; double bey = yb - ye; double cey = yc - ye; double dey = yd - ye; double aez = za - ze; double bez = zb - ze; double cez = zc - ze; double dez = zd - ze; double aexbey = aex * bey; double bexaey = bex * aey; double ab = aexbey - bexaey; double bexcey = bex * cey; double cexbey = cex * bey; double bc = bexcey - cexbey; double cexdey = cex * dey; double dexcey = dex * cey; double cd = cexdey - dexcey; double dexaey = dex * aey; double aexdey = aex * dey; double da = dexaey - aexdey; double aexcey = aex * cey; double cexaey = cex * aey; double ac = aexcey - cexaey; double bexdey = bex * dey; double dexbey = dex * bey; double bd = bexdey - dexbey; double abc = aez * bc - bez * ac + cez * ab; double bcd = bez * cd - cez * bd + dez * bc; double cda = cez * da + dez * ac + aez * cd; double dab = dez * ab + aez * bd + bez * da; double alift = aex * aex + aey * aey + aez * aez; double blift = bex * bex + bey * bey + bez * bez; double clift = cex * cex + cey * cey + cez * cez; double dlift = dex * dex + dey * dey + dez * dez; double det = (dlift * abc - clift * dab) + (blift * cda - alift * bcd); if (aez<0.0) aez = -aez; if (bez<0.0) bez = -bez; if (cez<0.0) cez = -cez; if (dez<0.0) dez = -dez; if (aexbey<0.0) aexbey = -aexbey; if (bexaey<0.0) bexaey = -bexaey; if (bexcey<0.0) bexcey = -bexcey; if (cexbey<0.0) cexbey = -cexbey; if (cexdey<0.0) cexdey = -cexdey; if (dexcey<0.0) dexcey = -dexcey; if (dexaey<0.0) dexaey = -dexaey; if (aexdey<0.0) aexdey = -aexdey; if (aexcey<0.0) aexcey = -aexcey; if (cexaey<0.0) cexaey = -cexaey; if (bexdey<0.0) bexdey = -bexdey; if (dexbey<0.0) dexbey = -dexbey; double permanent = ((cexdey + dexcey) * bez + (dexbey + bexdey) * cez + (bexcey + cexbey) * dez) * alift + ((dexaey + aexdey) * cez + (aexcey + cexaey) * dez + (cexdey + dexcey) * aez) * blift + ((aexbey + bexaey) * dez + (bexdey + dexbey) * aez + (dexaey + aexdey) * bez) * clift + ((bexcey + cexbey) * aez + (cexaey + aexcey) * bez + (aexbey + bexaey) * cez) * dlift; double errbound = INSERRBOUND * permanent; if ((det > errbound) || (-det > errbound)) { return det; } return inSphereExact(xa,ya,za,xb,yb,zb,xc,yc,zc,xd,yd,zd,xe,ye,ze); } static double leftOfLine( double xa, double ya, double xb, double yb, double xc, double yc); static double leftOfLine( double[] pa, double[] pb, double[] pc); static double leftOfLine( float[] pa, float[] pb, float[] pc); static double leftOfLineFast( double xa, double ya, double xb, double yb, double xc, double yc); static double leftOfLineFast( double[] pa, double[] pb, double[] pc); static double leftOfLineFast( float[] pa, float[] pb, float[] pc); static double leftOfPlane( double xa, double ya, double za, double xb, double yb, double zb, double xc, double yc, double zc, double xd, double yd, double zd); static double leftOfPlane( double[] pa, double[] pb, double[] pc, double[] pd); static double leftOfPlane( float[] pa, float[] pb, float[] pc, float[] pd); static double leftOfPlaneFast( double xa, double ya, double za, double xb, double yb, double zb, double xc, double yc, double zc, double xd, double yd, double zd); static double leftOfPlaneFast( double[] pa, double[] pb, double[] pc, double[] pd); static double leftOfPlaneFast( float[] pa, float[] pb, float[] pc, float[] pd); static double inCircle( double xa, double ya, double xb, double yb, double xc, double yc, double xd, double yd); static double inCircle( double[] pa, double[] pb, double[] pc, double[] pd); static double inCircle( float[] pa, float[] pb, float[] pc, float[] pd); static double inCircleFast( double xa, double ya, double xb, double yb, double xc, double yc, double xd, double yd); static double inCircleFast( double[] pa, double[] pb, double[] pc, double[] pd); static double inCircleFast( float[] pa, float[] pb, float[] pc, float[] pd); static double inSphere( double xa, double ya, double za, double xb, double yb, double zb, double xc, double yc, double zc, double xd, double yd, double zd, double xe, double ye, double ze); static double inSphere( double[] pa, double[] pb, double[] pc, double[] pd, double[] pe); static double inSphere( float[] pa, float[] pb, float[] pc, float[] pd, float[] pe); static double inSphereFast( double xa, double ya, double za, double xb, double yb, double zb, double xc, double yc, double zc, double xd, double yd, double zd, double xe, double ye, double ze); static double inSphereFast( double[] pa, double[] pb, double[] pc, double[] pd, double[] pe); static double inSphereFast( float[] pa, float[] pb, float[] pc, float[] pd, float[] pe); static double inOrthoSphere( double xa, double ya, double za, double wa, double xb, double yb, double zb, double wb, double xc, double yc, double zc, double wc, double xd, double yd, double zd, double wd, double xe, double ye, double ze, double we); static double inOrthoSphere( double[] pa, double[] pb, double[] pc, double[] pd, double[] pe); static double inOrthoSphere( float[] pa, float[] pb, float[] pc, float[] pd, float[] pe); static double inOrthoSphereFast( double xa, double ya, double za, double wa, double xb, double yb, double zb, double wb, double xc, double yc, double zc, double wc, double xd, double yd, double zd, double wd, double xe, double ye, double ze, double we); static double inOrthoSphereFast( double[] pa, double[] pb, double[] pc, double[] pd, double[] pe); static double inOrthoSphereFast( float[] pa, float[] pb, float[] pc, float[] pd, float[] pe); static void centerCircle( float xa, float ya, float xb, float yb, float xc, float yc, float[] po); static void centerCircle( float[] pa, float[] pb, float[] pc, float[] po); static void centerCircle( double xa, double ya, double xb, double yb, double xc, double yc, double[] po); static void centerCircle( double[] pa, double[] pb, double[] pc, double[] po); static void centerSphere( float xa, float ya, float za, float xb, float yb, float zb, float xc, float yc, float zc, float xd, float yd, float zd, float[] po); static void centerSphere( float[] pa, float[] pb, float[] pc, float[] pd, float[] po); static void centerSphere( double xa, double ya, double za, double xb, double yb, double zb, double xc, double yc, double zc, double xd, double yd, double zd, double[] po); static void centerSphere( double[] pa, double[] pb, double[] pc, double[] pd, double[] po); static void centerCircle3D( double xa, double ya, double za, double xb, double yb, double zb, double xc, double yc, double zc, double[] po); }
@Test public void testInSphere() { float xxxx = 1.0f; float yyyy = FLT_PI; float zzzz = 1.0e6f; float pa[] = {xxxx,0.0f,0.0f}; float pb[] = {0.0f,yyyy,0.0f}; float pc[] = {0.0f,0.0f,zzzz}; float pd[] = {0.0f,0.0f,0.0f}; float pe[] = {xxxx,yyyy,zzzz}; double ra,rf; trace(""); ra = Geometry.inSphere(pa,pb,pc,pd,pe); rf = Geometry.inSphereFast(pa,pb,pc,pd,pe); trace("0 inSphere: "+String.format("%26.18e",ra)); trace("0 inSphereFast: "+String.format("%26.18e",rf)); assertTrue(ra==0.0); pe[X] = xxxx*(1.0f-FLT_EPSILON); ra = Geometry.inSphere(pa,pb,pc,pd,pe); rf = Geometry.inSphereFast(pa,pb,pc,pd,pe); trace("+ inSphere: "+String.format("%26.18e",ra)); trace("+ inSphereFast: "+String.format("%26.18e",rf)); assertTrue(ra>0.0); pe[X] = xxxx*(1.0f+FLT_EPSILON); ra = Geometry.inSphere(pa,pb,pc,pd,pe); rf = Geometry.inSphereFast(pa,pb,pc,pd,pe); trace("- inSphere: "+String.format("%26.18e",ra)); trace("- inSphereFast: "+String.format("%26.18e",rf)); assertTrue(ra<0.0); }
Geometry { public static double leftOfLine( double xa, double ya, double xb, double yb, double xc, double yc) { double detleft = (xa-xc)*(yb-yc); double detright = (ya-yc)*(xb-xc); double det = detleft-detright; double detsum; if (detleft>0.0) { if (detright<=0.0) { return det; } else { detsum = detleft+detright; } } else if (detleft<0.0) { if (detright>=0.0) { return det; } else { detsum = -detleft-detright; } } else { return det; } double errbound = O2DERRBOUND*detsum; if (det>=errbound || -det>=errbound) return det; return leftOfLineExact(xa,ya,xb,yb,xc,yc); } static double leftOfLine( double xa, double ya, double xb, double yb, double xc, double yc); static double leftOfLine( double[] pa, double[] pb, double[] pc); static double leftOfLine( float[] pa, float[] pb, float[] pc); static double leftOfLineFast( double xa, double ya, double xb, double yb, double xc, double yc); static double leftOfLineFast( double[] pa, double[] pb, double[] pc); static double leftOfLineFast( float[] pa, float[] pb, float[] pc); static double leftOfPlane( double xa, double ya, double za, double xb, double yb, double zb, double xc, double yc, double zc, double xd, double yd, double zd); static double leftOfPlane( double[] pa, double[] pb, double[] pc, double[] pd); static double leftOfPlane( float[] pa, float[] pb, float[] pc, float[] pd); static double leftOfPlaneFast( double xa, double ya, double za, double xb, double yb, double zb, double xc, double yc, double zc, double xd, double yd, double zd); static double leftOfPlaneFast( double[] pa, double[] pb, double[] pc, double[] pd); static double leftOfPlaneFast( float[] pa, float[] pb, float[] pc, float[] pd); static double inCircle( double xa, double ya, double xb, double yb, double xc, double yc, double xd, double yd); static double inCircle( double[] pa, double[] pb, double[] pc, double[] pd); static double inCircle( float[] pa, float[] pb, float[] pc, float[] pd); static double inCircleFast( double xa, double ya, double xb, double yb, double xc, double yc, double xd, double yd); static double inCircleFast( double[] pa, double[] pb, double[] pc, double[] pd); static double inCircleFast( float[] pa, float[] pb, float[] pc, float[] pd); static double inSphere( double xa, double ya, double za, double xb, double yb, double zb, double xc, double yc, double zc, double xd, double yd, double zd, double xe, double ye, double ze); static double inSphere( double[] pa, double[] pb, double[] pc, double[] pd, double[] pe); static double inSphere( float[] pa, float[] pb, float[] pc, float[] pd, float[] pe); static double inSphereFast( double xa, double ya, double za, double xb, double yb, double zb, double xc, double yc, double zc, double xd, double yd, double zd, double xe, double ye, double ze); static double inSphereFast( double[] pa, double[] pb, double[] pc, double[] pd, double[] pe); static double inSphereFast( float[] pa, float[] pb, float[] pc, float[] pd, float[] pe); static double inOrthoSphere( double xa, double ya, double za, double wa, double xb, double yb, double zb, double wb, double xc, double yc, double zc, double wc, double xd, double yd, double zd, double wd, double xe, double ye, double ze, double we); static double inOrthoSphere( double[] pa, double[] pb, double[] pc, double[] pd, double[] pe); static double inOrthoSphere( float[] pa, float[] pb, float[] pc, float[] pd, float[] pe); static double inOrthoSphereFast( double xa, double ya, double za, double wa, double xb, double yb, double zb, double wb, double xc, double yc, double zc, double wc, double xd, double yd, double zd, double wd, double xe, double ye, double ze, double we); static double inOrthoSphereFast( double[] pa, double[] pb, double[] pc, double[] pd, double[] pe); static double inOrthoSphereFast( float[] pa, float[] pb, float[] pc, float[] pd, float[] pe); static void centerCircle( float xa, float ya, float xb, float yb, float xc, float yc, float[] po); static void centerCircle( float[] pa, float[] pb, float[] pc, float[] po); static void centerCircle( double xa, double ya, double xb, double yb, double xc, double yc, double[] po); static void centerCircle( double[] pa, double[] pb, double[] pc, double[] po); static void centerSphere( float xa, float ya, float za, float xb, float yb, float zb, float xc, float yc, float zc, float xd, float yd, float zd, float[] po); static void centerSphere( float[] pa, float[] pb, float[] pc, float[] pd, float[] po); static void centerSphere( double xa, double ya, double za, double xb, double yb, double zb, double xc, double yc, double zc, double xd, double yd, double zd, double[] po); static void centerSphere( double[] pa, double[] pb, double[] pc, double[] pd, double[] po); static void centerCircle3D( double xa, double ya, double za, double xb, double yb, double zb, double xc, double yc, double zc, double[] po); }
@Test public void testLeftOfLine() { float xxxx = 2.0f; float yyyy = 1.0f; float aaaa = 1.0e15f; float pa[] = {1.0f*xxxx,1.0f*yyyy}; float pb[] = {2.0f*xxxx,2.0f*yyyy}; float pc[] = {aaaa*xxxx,aaaa*yyyy}; double ra,rf; trace(""); ra = Geometry.leftOfLine(pa,pb,pc); rf = Geometry.leftOfLineFast(pa,pb,pc); trace("0 leftOfLine: "+String.format("%26.18e",ra)); trace("0 leftOfLineFast: "+String.format("%26.18e",rf)); assertTrue(ra==0.0); pc[X] = aaaa*xxxx*(1.0f-FLT_EPSILON); ra = Geometry.leftOfLine(pa,pb,pc); rf = Geometry.leftOfLineFast(pa,pb,pc); trace("+ leftOfLine: "+String.format("%26.18e",ra)); trace("+ leftOfLineFast: "+String.format("%26.18e",rf)); assertTrue(ra>0.0); pc[X] = aaaa*xxxx*(1.0f+FLT_EPSILON); ra = Geometry.leftOfLine(pa,pb,pc); rf = Geometry.leftOfLineFast(pa,pb,pc); trace("- leftOfLine: "+String.format("%26.18e",ra)); trace("- leftOfLineFast: "+String.format("%26.18e",rf)); assertTrue(ra<0.0); }
Geometry { public static double leftOfPlane( double xa, double ya, double za, double xb, double yb, double zb, double xc, double yc, double zc, double xd, double yd, double zd) { double adx = xa - xd; double bdx = xb - xd; double cdx = xc - xd; double ady = ya - yd; double bdy = yb - yd; double cdy = yc - yd; double adz = za - zd; double bdz = zb - zd; double cdz = zc - zd; double bdxcdy = bdx * cdy; double cdxbdy = cdx * bdy; double cdxady = cdx * ady; double adxcdy = adx * cdy; double adxbdy = adx * bdy; double bdxady = bdx * ady; double det = adz * (bdxcdy - cdxbdy) + bdz * (cdxady - adxcdy) + cdz * (adxbdy - bdxady); if (adz<0.0) adz = -adz; if (bdz<0.0) bdz = -bdz; if (cdz<0.0) cdz = -cdz; if (bdxcdy<0.0) bdxcdy = -bdxcdy; if (cdxbdy<0.0) cdxbdy = -cdxbdy; if (cdxady<0.0) cdxady = -cdxady; if (adxcdy<0.0) adxcdy = -adxcdy; if (adxbdy<0.0) adxbdy = -adxbdy; if (bdxady<0.0) bdxady = -bdxady; double permanent = (bdxcdy + cdxbdy) * adz + (cdxady + adxcdy) * bdz + (adxbdy + bdxady) * cdz; double errbound = O3DERRBOUND * permanent; if ((det > errbound) || (-det > errbound)) { return det; } return leftOfPlaneExact(xa,ya,za,xb,yb,zb,xc,yc,zc,xd,yd,zd); } static double leftOfLine( double xa, double ya, double xb, double yb, double xc, double yc); static double leftOfLine( double[] pa, double[] pb, double[] pc); static double leftOfLine( float[] pa, float[] pb, float[] pc); static double leftOfLineFast( double xa, double ya, double xb, double yb, double xc, double yc); static double leftOfLineFast( double[] pa, double[] pb, double[] pc); static double leftOfLineFast( float[] pa, float[] pb, float[] pc); static double leftOfPlane( double xa, double ya, double za, double xb, double yb, double zb, double xc, double yc, double zc, double xd, double yd, double zd); static double leftOfPlane( double[] pa, double[] pb, double[] pc, double[] pd); static double leftOfPlane( float[] pa, float[] pb, float[] pc, float[] pd); static double leftOfPlaneFast( double xa, double ya, double za, double xb, double yb, double zb, double xc, double yc, double zc, double xd, double yd, double zd); static double leftOfPlaneFast( double[] pa, double[] pb, double[] pc, double[] pd); static double leftOfPlaneFast( float[] pa, float[] pb, float[] pc, float[] pd); static double inCircle( double xa, double ya, double xb, double yb, double xc, double yc, double xd, double yd); static double inCircle( double[] pa, double[] pb, double[] pc, double[] pd); static double inCircle( float[] pa, float[] pb, float[] pc, float[] pd); static double inCircleFast( double xa, double ya, double xb, double yb, double xc, double yc, double xd, double yd); static double inCircleFast( double[] pa, double[] pb, double[] pc, double[] pd); static double inCircleFast( float[] pa, float[] pb, float[] pc, float[] pd); static double inSphere( double xa, double ya, double za, double xb, double yb, double zb, double xc, double yc, double zc, double xd, double yd, double zd, double xe, double ye, double ze); static double inSphere( double[] pa, double[] pb, double[] pc, double[] pd, double[] pe); static double inSphere( float[] pa, float[] pb, float[] pc, float[] pd, float[] pe); static double inSphereFast( double xa, double ya, double za, double xb, double yb, double zb, double xc, double yc, double zc, double xd, double yd, double zd, double xe, double ye, double ze); static double inSphereFast( double[] pa, double[] pb, double[] pc, double[] pd, double[] pe); static double inSphereFast( float[] pa, float[] pb, float[] pc, float[] pd, float[] pe); static double inOrthoSphere( double xa, double ya, double za, double wa, double xb, double yb, double zb, double wb, double xc, double yc, double zc, double wc, double xd, double yd, double zd, double wd, double xe, double ye, double ze, double we); static double inOrthoSphere( double[] pa, double[] pb, double[] pc, double[] pd, double[] pe); static double inOrthoSphere( float[] pa, float[] pb, float[] pc, float[] pd, float[] pe); static double inOrthoSphereFast( double xa, double ya, double za, double wa, double xb, double yb, double zb, double wb, double xc, double yc, double zc, double wc, double xd, double yd, double zd, double wd, double xe, double ye, double ze, double we); static double inOrthoSphereFast( double[] pa, double[] pb, double[] pc, double[] pd, double[] pe); static double inOrthoSphereFast( float[] pa, float[] pb, float[] pc, float[] pd, float[] pe); static void centerCircle( float xa, float ya, float xb, float yb, float xc, float yc, float[] po); static void centerCircle( float[] pa, float[] pb, float[] pc, float[] po); static void centerCircle( double xa, double ya, double xb, double yb, double xc, double yc, double[] po); static void centerCircle( double[] pa, double[] pb, double[] pc, double[] po); static void centerSphere( float xa, float ya, float za, float xb, float yb, float zb, float xc, float yc, float zc, float xd, float yd, float zd, float[] po); static void centerSphere( float[] pa, float[] pb, float[] pc, float[] pd, float[] po); static void centerSphere( double xa, double ya, double za, double xb, double yb, double zb, double xc, double yc, double zc, double xd, double yd, double zd, double[] po); static void centerSphere( double[] pa, double[] pb, double[] pc, double[] pd, double[] po); static void centerCircle3D( double xa, double ya, double za, double xb, double yb, double zb, double xc, double yc, double zc, double[] po); }
@Test public void testLeftOfPlane() { float xxxx = 1.0f; float yyyy = 1.0f; float zzzz = 1.0e15f; float pa[] = {xxxx,0.0f,0.1f}; float pb[] = {0.0f,yyyy,3.3f}; float pc[] = {0.0f,yyyy,6.7f}; float pd[] = {xxxx,0.0f,zzzz}; double ra,rf; trace(""); ra = Geometry.leftOfPlane(pa,pb,pc,pd); rf = Geometry.leftOfPlaneFast(pa,pb,pc,pd); trace("0 leftOfPlane: "+String.format("%26.18e",ra)); trace("0 leftOfPlaneFast: "+String.format("%26.18e",rf)); assertTrue(ra==0.0); pd[X] = xxxx*(1.0f-FLT_EPSILON); ra = Geometry.leftOfPlane(pa,pb,pc,pd); rf = Geometry.leftOfPlaneFast(pa,pb,pc,pd); trace("+ leftOfPlane: "+String.format("%26.18e",ra)); trace("+ leftOfPlaneFast: "+String.format("%26.18e",rf)); assertTrue(ra>0.0); pd[X] = xxxx*(1.0f+FLT_EPSILON); ra = Geometry.leftOfPlane(pa,pb,pc,pd); rf = Geometry.leftOfPlaneFast(pa,pb,pc,pd); trace("- leftOfPlane: "+String.format("%26.18e",ra)); trace("- leftOfPlaneFast: "+String.format("%26.18e",rf)); assertTrue(ra<0.0); }
Geometry { public static void centerCircle3D( double xa, double ya, double za, double xb, double yb, double zb, double xc, double yc, double zc, double[] po) { double acx = xa - xc; double acy = ya - yc; double acz = za - zc; double bcx = xb - xc; double bcy = yb - yc; double bcz = zb - zc; double acs = acx*acx+acy*acy+acz*acz; double bcs = bcx*bcx+bcy*bcy+bcz*bcz; double abx = leftOfLine(ya,za,yb,zb,yc,zc); double aby = leftOfLine(za,xa,zb,xb,zc,xc); double abz = leftOfLine(xa,ya,xb,yb,xc,yc); double scale = 0.5/(abx*abx+aby*aby+abz*abz); po[0] = xc+scale*((acs*bcy-bcs*acy)*abz-(acs*bcz-bcs*acz)*aby); po[1] = yc+scale*((acs*bcz-bcs*acz)*abx-(acs*bcx-bcs*acx)*abz); po[2] = zc+scale*((acs*bcx-bcs*acx)*aby-(acs*bcy-bcs*acy)*abx); } static double leftOfLine( double xa, double ya, double xb, double yb, double xc, double yc); static double leftOfLine( double[] pa, double[] pb, double[] pc); static double leftOfLine( float[] pa, float[] pb, float[] pc); static double leftOfLineFast( double xa, double ya, double xb, double yb, double xc, double yc); static double leftOfLineFast( double[] pa, double[] pb, double[] pc); static double leftOfLineFast( float[] pa, float[] pb, float[] pc); static double leftOfPlane( double xa, double ya, double za, double xb, double yb, double zb, double xc, double yc, double zc, double xd, double yd, double zd); static double leftOfPlane( double[] pa, double[] pb, double[] pc, double[] pd); static double leftOfPlane( float[] pa, float[] pb, float[] pc, float[] pd); static double leftOfPlaneFast( double xa, double ya, double za, double xb, double yb, double zb, double xc, double yc, double zc, double xd, double yd, double zd); static double leftOfPlaneFast( double[] pa, double[] pb, double[] pc, double[] pd); static double leftOfPlaneFast( float[] pa, float[] pb, float[] pc, float[] pd); static double inCircle( double xa, double ya, double xb, double yb, double xc, double yc, double xd, double yd); static double inCircle( double[] pa, double[] pb, double[] pc, double[] pd); static double inCircle( float[] pa, float[] pb, float[] pc, float[] pd); static double inCircleFast( double xa, double ya, double xb, double yb, double xc, double yc, double xd, double yd); static double inCircleFast( double[] pa, double[] pb, double[] pc, double[] pd); static double inCircleFast( float[] pa, float[] pb, float[] pc, float[] pd); static double inSphere( double xa, double ya, double za, double xb, double yb, double zb, double xc, double yc, double zc, double xd, double yd, double zd, double xe, double ye, double ze); static double inSphere( double[] pa, double[] pb, double[] pc, double[] pd, double[] pe); static double inSphere( float[] pa, float[] pb, float[] pc, float[] pd, float[] pe); static double inSphereFast( double xa, double ya, double za, double xb, double yb, double zb, double xc, double yc, double zc, double xd, double yd, double zd, double xe, double ye, double ze); static double inSphereFast( double[] pa, double[] pb, double[] pc, double[] pd, double[] pe); static double inSphereFast( float[] pa, float[] pb, float[] pc, float[] pd, float[] pe); static double inOrthoSphere( double xa, double ya, double za, double wa, double xb, double yb, double zb, double wb, double xc, double yc, double zc, double wc, double xd, double yd, double zd, double wd, double xe, double ye, double ze, double we); static double inOrthoSphere( double[] pa, double[] pb, double[] pc, double[] pd, double[] pe); static double inOrthoSphere( float[] pa, float[] pb, float[] pc, float[] pd, float[] pe); static double inOrthoSphereFast( double xa, double ya, double za, double wa, double xb, double yb, double zb, double wb, double xc, double yc, double zc, double wc, double xd, double yd, double zd, double wd, double xe, double ye, double ze, double we); static double inOrthoSphereFast( double[] pa, double[] pb, double[] pc, double[] pd, double[] pe); static double inOrthoSphereFast( float[] pa, float[] pb, float[] pc, float[] pd, float[] pe); static void centerCircle( float xa, float ya, float xb, float yb, float xc, float yc, float[] po); static void centerCircle( float[] pa, float[] pb, float[] pc, float[] po); static void centerCircle( double xa, double ya, double xb, double yb, double xc, double yc, double[] po); static void centerCircle( double[] pa, double[] pb, double[] pc, double[] po); static void centerSphere( float xa, float ya, float za, float xb, float yb, float zb, float xc, float yc, float zc, float xd, float yd, float zd, float[] po); static void centerSphere( float[] pa, float[] pb, float[] pc, float[] pd, float[] po); static void centerSphere( double xa, double ya, double za, double xb, double yb, double zb, double xc, double yc, double zc, double xd, double yd, double zd, double[] po); static void centerSphere( double[] pa, double[] pb, double[] pc, double[] pd, double[] po); static void centerCircle3D( double xa, double ya, double za, double xb, double yb, double zb, double xc, double yc, double zc, double[] po); }
@Test public void testCenterCircle3D() { double[] po = {0.0,0.0,0.0}; Geometry.centerCircle3D(0,1,0, 0,1,1, 0,0,1, po); assertTrue(po[0]==0.0); assertTrue(po[1]==0.5); assertTrue(po[2]==0.5); Geometry.centerCircle3D(0,0,1, 1,0,1, 1,0,0, po); assertTrue(po[0]==0.5); assertTrue(po[1]==0.0); assertTrue(po[2]==0.5); Geometry.centerCircle3D(1,0,0, 1,1,0, 0,1,0, po); assertTrue(po[0]==0.5); assertTrue(po[1]==0.5); assertTrue(po[2]==0.0); Geometry.centerCircle3D(1,1,0, 1,1,1, 1,0,1, po); assertTrue(po[0]==1.0); assertTrue(po[1]==0.5); assertTrue(po[2]==0.5); Geometry.centerCircle3D(0,1,1, 1,1,1, 1,1,0, po); assertTrue(po[0]==0.5); assertTrue(po[1]==1.0); assertTrue(po[2]==0.5); Geometry.centerCircle3D(1,0,1, 1,1,1, 0,1,1, po); assertTrue(po[0]==0.5); assertTrue(po[1]==0.5); assertTrue(po[2]==1.0); }
TridiagonalFMatrix { public void solve(float[] r, float[] u) { if (_w==null) _w = new float[_n]; float t = _b[0]; u[0] = r[0]/t; for (int j=1; j<_n; ++j) { _w[j] = _c[j-1]/t; t = _b[j]-_a[j]*_w[j]; u[j] = (r[j]-_a[j]*u[j-1])/t; } for (int j=_n-1; j>0; --j) u[j-1] -= _w[j]*u[j]; } TridiagonalFMatrix(int n); TridiagonalFMatrix(int n, float[] a, float[] b, float[] c); int n(); float[] a(); float[] b(); float[] c(); void solve(float[] r, float[] u); float[] times(float[] x); void times(float[] x, float[] y); }
@Test public void testSolve() { int n = 100; float[] a = randfloat(n); float[] b = randfloat(n); float[] c = randfloat(n); for (int i=0; i<n; ++i) b[i] += a[i]+c[i]; TridiagonalFMatrix t = new TridiagonalFMatrix(n,a,b,c); float[] r = randfloat(n); float[] u = zerofloat(n); t.solve(r,u); float[] s = t.times(u); assertEqualFuzzy(r,s); }
DMatrixQrd { public boolean isFullRank() { for (int j=0; j<_n; ++j) { if (_rdiag[j]==0.0) return false; } return true; } DMatrixQrd(DMatrix a); boolean isFullRank(); DMatrix getQ(); DMatrix getR(); DMatrix solve(DMatrix b); }
@Test public void testRankDeficient() { DMatrix a = new DMatrix(new double[][]{ {0.0, 0.0}, {3.0, 4.0}, }); DMatrixQrd qrd = new DMatrixQrd(a); assertFalse(qrd.isFullRank()); }
ColorMap { public static float[] rgbToHsl(float r, float g, float b) { float h,s,l; float[] hsl = new float[3]; float min = min(min(r,g),b); float max = max(max(r,g),b); l = (max+min)/2f; if (max==min) h = s = 0.0f; else { float diff = max - min; s = (l>0.5f) ? diff / (2f - max - min) : diff / (max + min); if (max==r) h = (g-b)/diff + ((g<b) ? 6.0f : 0.0f); else if (max==g) h = (b-r)/diff + 2.0f; else h = (r-g)/diff + 4.0f; h/=6.0f; } hsl[0] = h * 360; hsl[1] = s; hsl[2] = l; return hsl; } ColorMap(IndexColorModel colorModel); ColorMap(double vmin, double vmax, IndexColorModel colorModel); ColorMap(double vmin, double vmax, Color[] c); ColorMap(double vmin, double vmax, byte[] r, byte[] g, byte[] b); ColorMap(double vmin, double vmax, float[] r, float[] g, float[] b); ColorMap(Color c); ColorMap(double vmin, double vmax, Color c); double getMinValue(); double getMaxValue(); IndexColorModel getColorModel(); Color getColor(double v); int getIndex(double v); float[] getRgbFloats(float[] v); float[] getHslFloats(float[] v); float[] getCieLabFloats(float[] v); static float[] rgbToHsl(float r, float g, float b); static float[] hslToRgb(float h, float s, float l); static float[] rgbToCieLab(float[] rgb); static float[] rgbToCieLab(float r, float g, float b); static float[] cieLabToRgb(float[] lab); static float[] cieLabToRgb(float Ls, float as, float bs); void setValueRange(double vmin, double vmax); void setColorModel(IndexColorModel colorModel); void setColorModel(Color c); void addListener(ColorMapListener cml); void removeListener(ColorMapListener cml); static IndexColorModel getGray(); static IndexColorModel getGray(double g0, double g255); static IndexColorModel getGray(double g0, double g255, double alpha); static IndexColorModel getJet(); static IndexColorModel getJet(double alpha); static IndexColorModel getGmtJet(); static IndexColorModel getGmtJet(double alpha); static IndexColorModel getPrism(); static IndexColorModel getHue(); static IndexColorModel getHueRedToBlue(); static IndexColorModel getHueBlueToRed(); static IndexColorModel getHue(double h0, double h255); static IndexColorModel getHue(double h0, double h255, double alpha); static IndexColorModel getRedWhiteBlue(); static IndexColorModel getBlueWhiteRed(); static IndexColorModel getGrayYellowRed(); static IndexColorModel makeIndexColorModel(Color[] c); static IndexColorModel makeSolidColors(Color c); static IndexColorModel setAlpha(IndexColorModel icm, double alpha); static IndexColorModel setAlpha(IndexColorModel icm, float[] alpha); static final IndexColorModel GRAY; static final IndexColorModel JET; static final IndexColorModel GMT_JET; static final IndexColorModel HUE; static final IndexColorModel HUE_RED_TO_BLUE; static final IndexColorModel HUE_BLUE_TO_RED; static final IndexColorModel PRISM; static final IndexColorModel RED_WHITE_BLUE; static final IndexColorModel BLUE_WHITE_RED; static final IndexColorModel GRAY_YELLOW_RED; }
@Test public void testRgbToHsl() { float r,g,b; float h,s,l; for (int i=0; i<_rgbhsl.length; ++i) { r = _rgbhsl[i][0]; g = _rgbhsl[i][1]; b = _rgbhsl[i][2]; h = _rgbhsl[i][3]; s = _rgbhsl[i][4]; l = _rgbhsl[i][5]; float[] expected = { h, s, l }; float[] test = ColorMap.rgbToHsl(r,g,b); assertEquals(expected[0],test[0],0); assertEquals(expected[1],test[1],0); assertEquals(expected[2],test[2],0); } }
ColorMap { public static float[] hslToRgb(float h, float s, float l) { float r = 0, g = 0, b = 0; float c = (1 - Math.abs(2*l-1)) * s; float x = c * (1 - Math.abs((h/60.0f)%2-1)); float m = l - c/2.0f; if (h>= 0 && h< 60) { r = c; g = x; b = 0;} else if (h>= 60 && h<120) { r = x; g = c; b = 0;} else if (h>=120 && h<180) { r = 0; g = c; b = x;} else if (h>=180 && h<240) { r = 0; g = x; b = c;} else if (h>=240 && h<300) { r = x; g = 0; b = c;} else { r = c; g = 0; b = x;} r += m; g += m; b += m; r = min(1.0f,max(0.0f,r)); g = min(1.0f,max(0.0f,g)); b = min(1.0f,max(0.0f,b)); return new float[] {r,g,b}; } ColorMap(IndexColorModel colorModel); ColorMap(double vmin, double vmax, IndexColorModel colorModel); ColorMap(double vmin, double vmax, Color[] c); ColorMap(double vmin, double vmax, byte[] r, byte[] g, byte[] b); ColorMap(double vmin, double vmax, float[] r, float[] g, float[] b); ColorMap(Color c); ColorMap(double vmin, double vmax, Color c); double getMinValue(); double getMaxValue(); IndexColorModel getColorModel(); Color getColor(double v); int getIndex(double v); float[] getRgbFloats(float[] v); float[] getHslFloats(float[] v); float[] getCieLabFloats(float[] v); static float[] rgbToHsl(float r, float g, float b); static float[] hslToRgb(float h, float s, float l); static float[] rgbToCieLab(float[] rgb); static float[] rgbToCieLab(float r, float g, float b); static float[] cieLabToRgb(float[] lab); static float[] cieLabToRgb(float Ls, float as, float bs); void setValueRange(double vmin, double vmax); void setColorModel(IndexColorModel colorModel); void setColorModel(Color c); void addListener(ColorMapListener cml); void removeListener(ColorMapListener cml); static IndexColorModel getGray(); static IndexColorModel getGray(double g0, double g255); static IndexColorModel getGray(double g0, double g255, double alpha); static IndexColorModel getJet(); static IndexColorModel getJet(double alpha); static IndexColorModel getGmtJet(); static IndexColorModel getGmtJet(double alpha); static IndexColorModel getPrism(); static IndexColorModel getHue(); static IndexColorModel getHueRedToBlue(); static IndexColorModel getHueBlueToRed(); static IndexColorModel getHue(double h0, double h255); static IndexColorModel getHue(double h0, double h255, double alpha); static IndexColorModel getRedWhiteBlue(); static IndexColorModel getBlueWhiteRed(); static IndexColorModel getGrayYellowRed(); static IndexColorModel makeIndexColorModel(Color[] c); static IndexColorModel makeSolidColors(Color c); static IndexColorModel setAlpha(IndexColorModel icm, double alpha); static IndexColorModel setAlpha(IndexColorModel icm, float[] alpha); static final IndexColorModel GRAY; static final IndexColorModel JET; static final IndexColorModel GMT_JET; static final IndexColorModel HUE; static final IndexColorModel HUE_RED_TO_BLUE; static final IndexColorModel HUE_BLUE_TO_RED; static final IndexColorModel PRISM; static final IndexColorModel RED_WHITE_BLUE; static final IndexColorModel BLUE_WHITE_RED; static final IndexColorModel GRAY_YELLOW_RED; }
@Test public void testHslToRgb() { float r,g,b; float h,s,l; for (int i=0; i<_rgbhsl.length; ++i) { r = _rgbhsl[i][0]; g = _rgbhsl[i][1]; b = _rgbhsl[i][2]; h = _rgbhsl[i][3]; s = _rgbhsl[i][4]; l = _rgbhsl[i][5]; float[] expected = { r, g, b }; float[] test = ColorMap.hslToRgb(h,s,l); assertEquals(expected[0],test[0],0); assertEquals(expected[1],test[1],0); assertEquals(expected[2],test[2],0); } }
Units implements Cloneable { public static synchronized boolean define(String name, boolean plural, String definition) throws UnitsFormatException { return addDefinition(name,plural,definition); } Units(); Units(String definition); Object clone(); boolean equals(Object object); boolean equals(Units units); float toSI(float value); double toSI(double value); float fromSI(float value); double fromSI(double value); float floatShiftFrom(Units units); double doubleShiftFrom(Units units); float floatScaleFrom(Units units); double doubleScaleFrom(Units units); boolean haveDimensions(); boolean haveDimensionsOf(Units units); String standardDefinition(); static Units add(Units units, double s); static Units sub(Units units, double s); static Units mul(Units units, double s); static Units div(Units units, double s); static Units mul(Units units1, Units units2); static Units div(Units units1, Units units2); static Units inv(Units units); static Units pow(Units units, int p); static synchronized boolean define(String name, boolean plural, String definition); static synchronized boolean isValidDefinition(String definition); static synchronized boolean isDefined(String name); }
@Test public void testDefine() { boolean isValid, defined; try { isValid = Units.isValidDefinition("degrees F"); assertTrue(isValid); Units.define("degrees F",false,"degF"); defined = Units.isDefined("degrees F"); assertTrue(defined); isValid = Units.isValidDefinition("degrees C"); assertTrue(isValid); Units.define("degrees C",false,"degC"); defined = Units.isDefined("degrees C"); assertTrue(defined); Units.define("cubic_inches",false,"in^3"); defined = Units.isDefined("m"); assertTrue(defined); defined = Units.define("m",false,"meters"); assertTrue(!defined); } catch (UnitsFormatException e) { assertTrue(false); } defined = true; try { Units.define("foo_inches",false,"foo inches"); } catch (UnitsFormatException e) { defined = false; } assertTrue(!defined); }
ColorMap { public static float[] rgbToCieLab(float[] rgb) { float[] xyz = rgbToCieXyz(rgb); float Xn = 95.047f; float Yn = 100.000f; float Zn = 108.883f; xyz[0]/=Xn; xyz[1]/=Yn; xyz[2]/=Zn; return cieXyzToCieLab(xyz); } ColorMap(IndexColorModel colorModel); ColorMap(double vmin, double vmax, IndexColorModel colorModel); ColorMap(double vmin, double vmax, Color[] c); ColorMap(double vmin, double vmax, byte[] r, byte[] g, byte[] b); ColorMap(double vmin, double vmax, float[] r, float[] g, float[] b); ColorMap(Color c); ColorMap(double vmin, double vmax, Color c); double getMinValue(); double getMaxValue(); IndexColorModel getColorModel(); Color getColor(double v); int getIndex(double v); float[] getRgbFloats(float[] v); float[] getHslFloats(float[] v); float[] getCieLabFloats(float[] v); static float[] rgbToHsl(float r, float g, float b); static float[] hslToRgb(float h, float s, float l); static float[] rgbToCieLab(float[] rgb); static float[] rgbToCieLab(float r, float g, float b); static float[] cieLabToRgb(float[] lab); static float[] cieLabToRgb(float Ls, float as, float bs); void setValueRange(double vmin, double vmax); void setColorModel(IndexColorModel colorModel); void setColorModel(Color c); void addListener(ColorMapListener cml); void removeListener(ColorMapListener cml); static IndexColorModel getGray(); static IndexColorModel getGray(double g0, double g255); static IndexColorModel getGray(double g0, double g255, double alpha); static IndexColorModel getJet(); static IndexColorModel getJet(double alpha); static IndexColorModel getGmtJet(); static IndexColorModel getGmtJet(double alpha); static IndexColorModel getPrism(); static IndexColorModel getHue(); static IndexColorModel getHueRedToBlue(); static IndexColorModel getHueBlueToRed(); static IndexColorModel getHue(double h0, double h255); static IndexColorModel getHue(double h0, double h255, double alpha); static IndexColorModel getRedWhiteBlue(); static IndexColorModel getBlueWhiteRed(); static IndexColorModel getGrayYellowRed(); static IndexColorModel makeIndexColorModel(Color[] c); static IndexColorModel makeSolidColors(Color c); static IndexColorModel setAlpha(IndexColorModel icm, double alpha); static IndexColorModel setAlpha(IndexColorModel icm, float[] alpha); static final IndexColorModel GRAY; static final IndexColorModel JET; static final IndexColorModel GMT_JET; static final IndexColorModel HUE; static final IndexColorModel HUE_RED_TO_BLUE; static final IndexColorModel HUE_BLUE_TO_RED; static final IndexColorModel PRISM; static final IndexColorModel RED_WHITE_BLUE; static final IndexColorModel BLUE_WHITE_RED; static final IndexColorModel GRAY_YELLOW_RED; }
@Test public void testRgbToCieLab() { float r,g,b; float Ls,as,bs; for (int i=0; i<_rgbcielab.length; ++i) { r = _rgbcielab[i][0]; g = _rgbcielab[i][1]; b = _rgbcielab[i][2]; Ls = _rgbcielab[i][3]; as = _rgbcielab[i][4]; bs = _rgbcielab[i][5]; float[] expected = { Ls, as, bs }; float[] test = ColorMap.rgbToCieLab(r,g,b); assertEquals(expected[0],test[0],0.01); assertEquals(expected[1],test[1],0.01); assertEquals(expected[2],test[2],0.01); } }
ColorMap { public static float[] cieLabToRgb(float[] lab) { float[] xyz = cieLabToCieXyz(lab); float Xn = 95.047f; float Yn = 100.000f; float Zn = 108.883f; xyz[0]*=Xn; xyz[1]*=Yn; xyz[2]*=Zn; float[] rgb = cieXyzToRgb(xyz); rgb[0] = min(1.0f,max(0.0f,rgb[0])); rgb[1] = min(1.0f,max(0.0f,rgb[1])); rgb[2] = min(1.0f,max(0.0f,rgb[2])); return rgb; } ColorMap(IndexColorModel colorModel); ColorMap(double vmin, double vmax, IndexColorModel colorModel); ColorMap(double vmin, double vmax, Color[] c); ColorMap(double vmin, double vmax, byte[] r, byte[] g, byte[] b); ColorMap(double vmin, double vmax, float[] r, float[] g, float[] b); ColorMap(Color c); ColorMap(double vmin, double vmax, Color c); double getMinValue(); double getMaxValue(); IndexColorModel getColorModel(); Color getColor(double v); int getIndex(double v); float[] getRgbFloats(float[] v); float[] getHslFloats(float[] v); float[] getCieLabFloats(float[] v); static float[] rgbToHsl(float r, float g, float b); static float[] hslToRgb(float h, float s, float l); static float[] rgbToCieLab(float[] rgb); static float[] rgbToCieLab(float r, float g, float b); static float[] cieLabToRgb(float[] lab); static float[] cieLabToRgb(float Ls, float as, float bs); void setValueRange(double vmin, double vmax); void setColorModel(IndexColorModel colorModel); void setColorModel(Color c); void addListener(ColorMapListener cml); void removeListener(ColorMapListener cml); static IndexColorModel getGray(); static IndexColorModel getGray(double g0, double g255); static IndexColorModel getGray(double g0, double g255, double alpha); static IndexColorModel getJet(); static IndexColorModel getJet(double alpha); static IndexColorModel getGmtJet(); static IndexColorModel getGmtJet(double alpha); static IndexColorModel getPrism(); static IndexColorModel getHue(); static IndexColorModel getHueRedToBlue(); static IndexColorModel getHueBlueToRed(); static IndexColorModel getHue(double h0, double h255); static IndexColorModel getHue(double h0, double h255, double alpha); static IndexColorModel getRedWhiteBlue(); static IndexColorModel getBlueWhiteRed(); static IndexColorModel getGrayYellowRed(); static IndexColorModel makeIndexColorModel(Color[] c); static IndexColorModel makeSolidColors(Color c); static IndexColorModel setAlpha(IndexColorModel icm, double alpha); static IndexColorModel setAlpha(IndexColorModel icm, float[] alpha); static final IndexColorModel GRAY; static final IndexColorModel JET; static final IndexColorModel GMT_JET; static final IndexColorModel HUE; static final IndexColorModel HUE_RED_TO_BLUE; static final IndexColorModel HUE_BLUE_TO_RED; static final IndexColorModel PRISM; static final IndexColorModel RED_WHITE_BLUE; static final IndexColorModel BLUE_WHITE_RED; static final IndexColorModel GRAY_YELLOW_RED; }
@Test public void testCieLabToRgb() { float r,g,b; float Ls,as,bs; for (int i=0; i<_rgbcielab.length; ++i) { r = _rgbcielab[i][0]; g = _rgbcielab[i][1]; b = _rgbcielab[i][2]; Ls = _rgbcielab[i][3]; as = _rgbcielab[i][4]; bs = _rgbcielab[i][5]; float[] expected = { r, g, b }; float[] test = ColorMap.cieLabToRgb(Ls,as,bs); assertEquals(expected[0],test[0],0.01); assertEquals(expected[1],test[1],0.01); assertEquals(expected[2],test[2],0.01); } }
SincInterpolator { public static SincInterpolator fromErrorAndFrequency( double emax, double fmax) { return new SincInterpolator(emax,fmax,0); } SincInterpolator(); private SincInterpolator(double emax,double fmax,int lmax); static SincInterpolator fromErrorAndLength( double emax, int lmax); static SincInterpolator fromErrorAndFrequency( double emax, double fmax); static SincInterpolator fromFrequencyAndLength( double fmax, int lmax); double getMaximumError(); double getMaximumFrequency(); int getMaximumLength(); long getTableBytes(); Extrapolation getExtrapolation(); void setExtrapolation(Extrapolation extrap); float interpolate( int nxu, double dxu, double fxu, float[] yu, double xi); void interpolate( int nxu, double dxu, double fxu, float[] yu, int nxi, float[] xi, float[] yi); void interpolate( int nxu, double dxu, double fxu, float[] yu, int nxi, double dxi, double fxi, float[] yi); float interpolate( int nx1u, double dx1u, double fx1u, int nx2u, double dx2u, double fx2u, float[][] yu, double x1i, double x2i); float interpolate( int nx1u, double dx1u, double fx1u, int nx2u, double dx2u, double fx2u, int nx3u, double dx3u, double fx3u, float[][][] yu, double x1i, double x2i, double x3i); float interpolate(Sampling sxu, float[] yu, double xi); void interpolate( Sampling sxu, float[] yu, Sampling sxi, float[] yi); float interpolate( Sampling sx1u, Sampling sx2u, float[][] yu, double x1i, double x2i); float interpolate( Sampling sx1u, Sampling sx2u, Sampling sx3u, float[][][] yu, double x1i, double x2i, double x3i); void interpolateComplex( int nxu, double dxu, double fxu, float[] yu, int nxi, double dxi, double fxi, float[] yi); void interpolateComplex( int nxu, double dxu, double fxu, float[] yu, int nxi, float[] xi, float[] yi); void interpolateComplex( Sampling sxu, float[] yu, Sampling sxi, float[] yi); void accumulate( double xa, float ya, int nxu, double dxu, double fxu, float[] yu); void accumulate( int nxa, float[] xa, float[] ya, int nxu, double dxu, double fxu, float[] yu); float[][] getTable(); int getNumberInTable(); int getLengthInTable(); }
@Test public void testErrorAndFrequency() { for (double emax:_emaxs) { for (double fmax:_fmaxs) { SincInterpolator si = SincInterpolator.fromErrorAndFrequency(emax,fmax); testInterpolator(si); } } }
SincInterpolator { public static SincInterpolator fromErrorAndLength( double emax, int lmax) { return new SincInterpolator(emax,0.0,lmax); } SincInterpolator(); private SincInterpolator(double emax,double fmax,int lmax); static SincInterpolator fromErrorAndLength( double emax, int lmax); static SincInterpolator fromErrorAndFrequency( double emax, double fmax); static SincInterpolator fromFrequencyAndLength( double fmax, int lmax); double getMaximumError(); double getMaximumFrequency(); int getMaximumLength(); long getTableBytes(); Extrapolation getExtrapolation(); void setExtrapolation(Extrapolation extrap); float interpolate( int nxu, double dxu, double fxu, float[] yu, double xi); void interpolate( int nxu, double dxu, double fxu, float[] yu, int nxi, float[] xi, float[] yi); void interpolate( int nxu, double dxu, double fxu, float[] yu, int nxi, double dxi, double fxi, float[] yi); float interpolate( int nx1u, double dx1u, double fx1u, int nx2u, double dx2u, double fx2u, float[][] yu, double x1i, double x2i); float interpolate( int nx1u, double dx1u, double fx1u, int nx2u, double dx2u, double fx2u, int nx3u, double dx3u, double fx3u, float[][][] yu, double x1i, double x2i, double x3i); float interpolate(Sampling sxu, float[] yu, double xi); void interpolate( Sampling sxu, float[] yu, Sampling sxi, float[] yi); float interpolate( Sampling sx1u, Sampling sx2u, float[][] yu, double x1i, double x2i); float interpolate( Sampling sx1u, Sampling sx2u, Sampling sx3u, float[][][] yu, double x1i, double x2i, double x3i); void interpolateComplex( int nxu, double dxu, double fxu, float[] yu, int nxi, double dxi, double fxi, float[] yi); void interpolateComplex( int nxu, double dxu, double fxu, float[] yu, int nxi, float[] xi, float[] yi); void interpolateComplex( Sampling sxu, float[] yu, Sampling sxi, float[] yi); void accumulate( double xa, float ya, int nxu, double dxu, double fxu, float[] yu); void accumulate( int nxa, float[] xa, float[] ya, int nxu, double dxu, double fxu, float[] yu); float[][] getTable(); int getNumberInTable(); int getLengthInTable(); }
@Test public void testErrorAndLength() { for (double emax:_emaxs) { for (int lmax:_lmaxs) { SincInterpolator si = SincInterpolator.fromErrorAndLength(emax,lmax); testInterpolator(si); } } }
SincInterpolator { public static SincInterpolator fromFrequencyAndLength( double fmax, int lmax) { return new SincInterpolator(0.0,fmax,lmax); } SincInterpolator(); private SincInterpolator(double emax,double fmax,int lmax); static SincInterpolator fromErrorAndLength( double emax, int lmax); static SincInterpolator fromErrorAndFrequency( double emax, double fmax); static SincInterpolator fromFrequencyAndLength( double fmax, int lmax); double getMaximumError(); double getMaximumFrequency(); int getMaximumLength(); long getTableBytes(); Extrapolation getExtrapolation(); void setExtrapolation(Extrapolation extrap); float interpolate( int nxu, double dxu, double fxu, float[] yu, double xi); void interpolate( int nxu, double dxu, double fxu, float[] yu, int nxi, float[] xi, float[] yi); void interpolate( int nxu, double dxu, double fxu, float[] yu, int nxi, double dxi, double fxi, float[] yi); float interpolate( int nx1u, double dx1u, double fx1u, int nx2u, double dx2u, double fx2u, float[][] yu, double x1i, double x2i); float interpolate( int nx1u, double dx1u, double fx1u, int nx2u, double dx2u, double fx2u, int nx3u, double dx3u, double fx3u, float[][][] yu, double x1i, double x2i, double x3i); float interpolate(Sampling sxu, float[] yu, double xi); void interpolate( Sampling sxu, float[] yu, Sampling sxi, float[] yi); float interpolate( Sampling sx1u, Sampling sx2u, float[][] yu, double x1i, double x2i); float interpolate( Sampling sx1u, Sampling sx2u, Sampling sx3u, float[][][] yu, double x1i, double x2i, double x3i); void interpolateComplex( int nxu, double dxu, double fxu, float[] yu, int nxi, double dxi, double fxi, float[] yi); void interpolateComplex( int nxu, double dxu, double fxu, float[] yu, int nxi, float[] xi, float[] yi); void interpolateComplex( Sampling sxu, float[] yu, Sampling sxi, float[] yi); void accumulate( double xa, float ya, int nxu, double dxu, double fxu, float[] yu); void accumulate( int nxa, float[] xa, float[] ya, int nxu, double dxu, double fxu, float[] yu); float[][] getTable(); int getNumberInTable(); int getLengthInTable(); }
@Test public void testFrequencyAndLength() { for (double fmax:_fmaxs) { for (int lmax:_lmaxs) { if ((1.0-2.0*fmax)*lmax>1.0) { SincInterpolator si = SincInterpolator.fromFrequencyAndLength(fmax,lmax); testInterpolator(si); } } } }
SincInterpolator { public void accumulate( double xa, float ya, int nxu, double dxu, double fxu, float[] yu) { double xscale = 1.0/dxu; double xshift = _lsinc-fxu*xscale; int nxum = nxu-_lsinc; accumulate(xscale,xshift,nxum,xa,ya,nxu,yu); } SincInterpolator(); private SincInterpolator(double emax,double fmax,int lmax); static SincInterpolator fromErrorAndLength( double emax, int lmax); static SincInterpolator fromErrorAndFrequency( double emax, double fmax); static SincInterpolator fromFrequencyAndLength( double fmax, int lmax); double getMaximumError(); double getMaximumFrequency(); int getMaximumLength(); long getTableBytes(); Extrapolation getExtrapolation(); void setExtrapolation(Extrapolation extrap); float interpolate( int nxu, double dxu, double fxu, float[] yu, double xi); void interpolate( int nxu, double dxu, double fxu, float[] yu, int nxi, float[] xi, float[] yi); void interpolate( int nxu, double dxu, double fxu, float[] yu, int nxi, double dxi, double fxi, float[] yi); float interpolate( int nx1u, double dx1u, double fx1u, int nx2u, double dx2u, double fx2u, float[][] yu, double x1i, double x2i); float interpolate( int nx1u, double dx1u, double fx1u, int nx2u, double dx2u, double fx2u, int nx3u, double dx3u, double fx3u, float[][][] yu, double x1i, double x2i, double x3i); float interpolate(Sampling sxu, float[] yu, double xi); void interpolate( Sampling sxu, float[] yu, Sampling sxi, float[] yi); float interpolate( Sampling sx1u, Sampling sx2u, float[][] yu, double x1i, double x2i); float interpolate( Sampling sx1u, Sampling sx2u, Sampling sx3u, float[][][] yu, double x1i, double x2i, double x3i); void interpolateComplex( int nxu, double dxu, double fxu, float[] yu, int nxi, double dxi, double fxi, float[] yi); void interpolateComplex( int nxu, double dxu, double fxu, float[] yu, int nxi, float[] xi, float[] yi); void interpolateComplex( Sampling sxu, float[] yu, Sampling sxi, float[] yi); void accumulate( double xa, float ya, int nxu, double dxu, double fxu, float[] yu); void accumulate( int nxa, float[] xa, float[] ya, int nxu, double dxu, double fxu, float[] yu); float[][] getTable(); int getNumberInTable(); int getLengthInTable(); }
@Test public void testAccumulate() { Random random = new Random(123456); for (int repeat=0; repeat<5; ++repeat) { for (SincInterpolator.Extrapolation extrapolation: SincInterpolator.Extrapolation.values()) { int nxu = 201; double fxu = Math.PI; double dxu = Math.E; double exu = fxu + dxu*(nxu-1); float[] yu = new float[nxu]; for (int i=0; i<nxu; ++i) { yu[i] = 2*random.nextFloat() - 1; } int nx = 2*nxu; float[] x = new float[nx]; float[] y = new float[nx]; for (int i=0; i<nxu; ++i) { x[i] = (float)((1.2*random.nextFloat()-0.1)*(exu-fxu) + fxu); y[i] = 2*random.nextFloat() - 1; } SincInterpolator si = new SincInterpolator(); si.setExtrapolation(extrapolation); float[] yi = new float[nx]; si.interpolate(nxu, dxu, fxu, yu, nx, x, yi); float[] ya = new float[nxu]; si.accumulate(nx, x, y, nxu, dxu, fxu, ya); double yuYa = 0; for (int ixu=0; ixu<nxu; ++ixu) { yuYa += yu[ixu]*ya[ixu]; } double yYi = 0; for (int ix=0; ix<nx; ++ix) { yYi += y[ix]*yi[ix]; } double ratio = yuYa/yYi; String message = "yu.ya="+yuYa+" y.yi="+yYi+" ratio="+ratio; trace(message); assertTrue(ratio > 0.99999); assertTrue(ratio < 1.00001); } } }
RecursiveExponentialFilter { public void apply(float[] x, float[] y) { apply1(x,y); } RecursiveExponentialFilter(double sigma); RecursiveExponentialFilter(double sigma1, double sigma23); RecursiveExponentialFilter( double sigma1, double sigma2, double sigma3); void setEdges(Edges edges); void apply(float[] x, float[] y); void apply(float[][] x, float[][] y); void apply(float[][][] x, float[][][] y); void apply1(float[] x, float[] y); void apply1(float[][] x, float[][] y); void apply2(float[][] x, float[][] y); void apply1(float[][][] x, float[][][] y); void apply2(float[][][] x, float[][][] y); void apply3(float[][][] x, float[][][] y); }
@Test public void testFrequencyResponse() { int n = 501; double sigma = 4.0; float[] x = new float[n]; x[n/2] = 1.0f; float[] ye = new float[n]; float[] yg = new float[n]; RecursiveExponentialFilter ref = new RecursiveExponentialFilter(sigma); RecursiveGaussianFilter rgf = new RecursiveGaussianFilter(sigma); ref.apply(x,ye); rgf.apply0(x,yg); Fft fft = new Fft(n); fft.setCenter(true); Sampling sf = fft.getFrequencySampling1(); int i0 = sf.indexOfNearest(0.0); float[] ae = cabs(fft.applyForward(ye)); float[] ag = cabs(fft.applyForward(yg)); float e0 = ae[i0]; float e1 = (ae[i0+1]-ae[i0-1])/2.0f; float e2 = ae[i0+1]-2.0f*ae[i0]+ae[i0-1]; float g0 = ag[i0]; float g1 = (ag[i0+1]-ag[i0-1])/2.0f; float g2 = ag[i0+1]-2.0f*ag[i0]+ag[i0-1]; assertEquals(e0,g0,0.0001); assertEquals(e1,g1,0.0001); assertEquals(e2,g2,0.01*abs(g2)); }
HilbertTransformFilter { public void apply(int n, float[] x, float[] y) { Conv.conv(_filter.length,-(_filter.length-1)/2,_filter,n,0,x,n,0,y); } HilbertTransformFilter(); HilbertTransformFilter(int nmax, float emax, float fmin, float fmax); void apply(int n, float[] x, float[] y); int length(); }
@Test public void testApply() { int[] nmax_test = {NMAX_DEFAULT,100000,100000,100000,100000}; float[] emax_test = {EMAX_DEFAULT,0.010f,0.010f,0.001f,0.001f}; float[] fmin_test = {FMIN_DEFAULT,0.050f,0.025f,0.100f,0.010f}; float[] fmax_test = {FMAX_DEFAULT,0.475f,0.450f,0.400f,0.490f}; int ntest = emax_test.length; for (int itest=0; itest<ntest; ++itest) { int nmax = nmax_test[itest]; float emax = emax_test[itest]; float fmin = fmin_test[itest]; float fmax = fmax_test[itest]; HilbertTransformFilter htf = new HilbertTransformFilter(nmax,emax,fmin,fmax); int lhtf = htf.length(); int nxy = lhtf; float[] x = new float[nxy]; x[(lhtf-1)/2] = 1.0f; float[] y = new float[nxy]; htf.apply(nxy,x,y); int nfft = FftReal.nfftSmall(16*nxy); FftReal fft = new FftReal(nfft); int mfft = nfft/2+1; float[] hfft = new float[2*mfft]; for (int i=0; i<nxy; ++i) hfft[i] = y[i]; fft.realToComplex(1,hfft,hfft); int jfmin = 1+(int)(fmin*nfft); int jfmax = (int)(fmax*nfft); float[] afft = abs(sub(cabs(hfft),1.0f)); float error = max(copy(1+jfmax-jfmin,jfmin,afft)); assertTrue(error<=emax,"actual error less than maximum expected error"); } }
FftFilter { public float[] apply(float[] x) { float[] y = new float[x.length]; apply(x,y); return y; } FftFilter(float[] h); FftFilter(int kh, float[] h); FftFilter(float[][] h); FftFilter(int kh1, int kh2, float[][] h); FftFilter(float[][][] h); FftFilter(int kh1, int kh2, int kh3, float[][][] h); void setExtrapolation(Extrapolation extrapolation); void setFilterCaching(boolean filterCaching); float[] apply(float[] x); void apply(float[] x, float[] y); float[][] apply(float[][] x); void apply(float[][] x, float[][] y); float[][][] apply(float[][][] x); void apply(float[][][] x, float[][][] y); }
@Test public void test1Random() { int ntest = 1000; int nmin = 1; int nmax = 8; for (int itest=0; itest<ntest; ++itest) { int nh = nmin+_random.nextInt(1+nmax-nmin); int nx = nmin+_random.nextInt(1+nmax-nmin); int ny = nx; int nz = nx; int kh = _random.nextInt(nh); float[] h = randfloat(nh); float[] x = randfloat(nx); float[] y = randfloat(ny); float[] z = randfloat(nz); FftFilter ff = new FftFilter(kh,h); ff.apply(x,y); Conv.conv(nh,-kh,h,nx,0,x,nz,0,z); assertArrayEquals(z,y); } } @Test public void test2Random() { int ntest = 1000; int nmin = 1; int nmax = 8; for (int itest=0; itest<ntest; ++itest) { int nh1 = nmin+_random.nextInt(1+nmax-nmin); int nh2 = nmin+_random.nextInt(1+nmax-nmin); int nx1 = nmin+_random.nextInt(1+nmax-nmin); int nx2 = nmin+_random.nextInt(1+nmax-nmin); int ny1 = nx1; int ny2 = nx2; int nz1 = nx1; int nz2 = nx2; int kh1 = _random.nextInt(nh1); int kh2 = _random.nextInt(nh2); float[][] h = randfloat(nh1,nh2); float[][] x = randfloat(nx1,nx2); float[][] y = randfloat(ny1,ny2); float[][] z = randfloat(nz1,nz2); FftFilter ff = new FftFilter(kh1,kh2,h); ff.apply(x,y); Conv.conv(nh1,nh2,-kh1,-kh2,h,nx1,nx2,0,0,x,nz1,nz2,0,0,z); assertArrayEquals(z,y); } } @Test public void test3Random() { int ntest = 100; int nmin = 1; int nmax = 8; for (int itest=0; itest<ntest; ++itest) { int nh1 = nmin+_random.nextInt(1+nmax-nmin); int nh2 = nmin+_random.nextInt(1+nmax-nmin); int nh3 = nmin+_random.nextInt(1+nmax-nmin); int nx1 = nmin+_random.nextInt(1+nmax-nmin); int nx2 = nmin+_random.nextInt(1+nmax-nmin); int nx3 = nmin+_random.nextInt(1+nmax-nmin); int ny1 = nx1; int ny2 = nx2; int ny3 = nx3; int nz1 = nx1; int nz2 = nx2; int nz3 = nx3; int kh1 = _random.nextInt(nh1); int kh2 = _random.nextInt(nh2); int kh3 = _random.nextInt(nh3); float[][][] h = randfloat(nh1,nh2,nh3); float[][][] x = randfloat(nx1,nx2,nx3); float[][][] y = randfloat(ny1,ny2,ny3); float[][][] z = randfloat(nz1,nz2,nz3); FftFilter ff = new FftFilter(kh1,kh2,kh3,h); ff.apply(x,y); Conv.conv(nh1,nh2,nh3,-kh1,-kh2,-kh3,h, nx1,nx2,nx3,0,0,0,x, nz1,nz2,nz3,0,0,0,z); assertArrayEquals(z,y); } }
Parallel { public static void loop(int end, LoopInt body) { loop(0,end,1,1,body); } static void loop(int end, LoopInt body); static void loop(int begin, int end, LoopInt body); static void loop(int begin, int end, int step, LoopInt body); static void loop( int begin, int end, int step, int chunk, LoopInt body); static V reduce(int end, ReduceInt<V> body); static V reduce(int begin, int end, ReduceInt<V> body); static V reduce( int begin, int end, int step, ReduceInt<V> body); static V reduce( int begin, int end, int step, int chunk, ReduceInt<V> body); static void setParallel(boolean parallel); }
@Test public void testUnsafe() { final Unsafe<Worker> nts = new Unsafe<Worker>(); loop(20,new LoopInt() { public void compute(int i) { Worker w = nts.get(); if (w==null) nts.set(w=new Worker()); w.work(); } }); }
Eigen { public static void solveSymmetric22(float[][] a, float[][] v, float[] d) { float a00 = a[0][0]; float a01 = a[0][1], a11 = a[1][1]; float v00 = 1.0f, v01 = 0.0f; float v10 = 0.0f, v11 = 1.0f; if (a01!=0.0f) { float tiny = 0.1f*sqrt(FLT_EPSILON); float c,r,s,t,u,vpr,vqr; u = a11-a00; if (abs(a01)<tiny*abs(u)) { t = a01/u; } else { r = 0.5f*u/a01; t = (r>=0.0f)?1.0f/(r+sqrt(1.0f+r*r)):1.0f/(r-sqrt(1.0f+r*r)); } c = 1.0f/sqrt(1.0f+t*t); s = t*c; u = s/(1.0f+c); r = t*a01; a00 -= r; a11 += r; vpr = v00; vqr = v10; v00 = vpr-s*(vqr+vpr*u); v10 = vqr+s*(vpr-vqr*u); vpr = v01; vqr = v11; v01 = vpr-s*(vqr+vpr*u); v11 = vqr+s*(vpr-vqr*u); } d[0] = a00; d[1] = a11; v[0][0] = v00; v[0][1] = v01; v[1][0] = v10; v[1][1] = v11; if (d[0]<d[1]) { float dt = d[1]; d[1] = d[0]; d[0] = dt; float[] vt = v[1]; v[1] = v[0]; v[0] = vt; } } static void solveSymmetric22(float[][] a, float[][] v, float[] d); static void solveSymmetric22(double[][] a, double[][] v, double[] d); static void solveSymmetric33(double[][] a, double[][] v, double[] d); static void solveSymmetric33Fast( double[][] a, double[][] v, double[] d); }
@Test public void testSymmetric22() { int nrand = 10000; double[][] v = new double[2][2]; double[] d = new double[2]; for (int irand=0; irand<nrand; ++irand) { double[][] a = randdouble(2,2); a = add(a, transpose(a)); Eigen.solveSymmetric22(a,v,d); check(a,v,d); } }
Eigen { public static void solveSymmetric33(double[][] a, double[][] v, double[] d) { solveSymmetric33Jacobi(a,v,d); } static void solveSymmetric22(float[][] a, float[][] v, float[] d); static void solveSymmetric22(double[][] a, double[][] v, double[] d); static void solveSymmetric33(double[][] a, double[][] v, double[] d); static void solveSymmetric33Fast( double[][] a, double[][] v, double[] d); }
@Test public void testSymmetric33() { double[][] v = new double[3][3]; double[] d = new double[3]; int nrand = 10000; for (int irand=0; irand<nrand; ++irand) { double[][] a = makeRandomSymmetric33(); Eigen.solveSymmetric33(a,v,d); check(a,v,d); } } @Test public void testSymmetric33Special() { double[][] v = new double[3][3]; double[] d = new double[3]; double[][][] as = {ASMALL,A100,A110,A111,ATEST1}; for (double[][] a:as) { Eigen.solveSymmetric33(a,v,d); check(a,v,d); } }
LocalOrientFilter { public void apply(float[][] x, float[][] theta, float[][] u1, float[][] u2, float[][] v1, float[][] v2, float[][] eu, float[][] ev, float[][] el) { float[][][] t = new float[8][][]; int nt = 0; if (theta!=null) t[nt++] = theta; if (u1!=null) t[nt++] = u1; if (u2!=null) t[nt++] = u2; if (v1!=null) t[nt++] = v1; if (v2!=null) t[nt++] = v2; if (eu!=null) t[nt++] = eu; if (ev!=null) t[nt++] = ev; if (el!=null) t[nt++] = el; int n1 = x[0].length; int n2 = x.length; float[][] g1 = (nt>0)?t[0]:new float[n2][n1]; float[][] g2 = (nt>1)?t[1]:new float[n2][n1]; _rgfGradient1.apply10(x,g1); _rgfGradient2.apply01(x,g2); float[][] g11 = g1; float[][] g22 = g2; float[][] g12 = (nt>2)?t[2]:new float[n2][n1]; for (int i2=0; i2<n2; ++i2) { for (int i1=0; i1<n1; ++i1) { float g1i = g1[i2][i1]; float g2i = g2[i2][i1]; g11[i2][i1] = g1i*g1i; g22[i2][i1] = g2i*g2i; g12[i2][i1] = g1i*g2i; } } if (_rgfSmoother1!=null || _rgfSmoother2!=null) { float[][] h = (nt>3)?t[3]:new float[n2][n1]; float[][][] gs = {g11,g22,g12}; for (float[][] g:gs) { if (_rgfSmoother1!=null) { _rgfSmoother1.apply0X(g,h); } else { copy(g,h); } if (_rgfSmoother2!=null) { _rgfSmoother2.applyX0(h,g); } else { copy(h,g); } } } float[][] a = new float[2][2]; float[][] z = new float[2][2]; float[] e = new float[2]; for (int i2=0; i2<n2; ++i2) { for (int i1=0; i1<n1; ++i1) { a[0][0] = g11[i2][i1]; a[0][1] = g12[i2][i1]; a[1][0] = g12[i2][i1]; a[1][1] = g22[i2][i1]; Eigen.solveSymmetric22(a,z,e); float u1i = z[0][0]; float u2i = z[0][1]; if (u1i<0.0f) { u1i = -u1i; u2i = -u2i; } float v1i = -u2i; float v2i = u1i; float eui = e[0]; float evi = e[1]; if (evi<0.0f) evi = 0.0f; if (eui<evi) eui = evi; if (theta!=null) theta[i2][i1] = asin(u2i); if (u1!=null) u1[i2][i1] = u1i; if (u2!=null) u2[i2][i1] = u2i; if (v1!=null) v1[i2][i1] = v1i; if (v2!=null) v2[i2][i1] = v2i; if (eu!=null) eu[i2][i1] = eui; if (ev!=null) ev[i2][i1] = evi; if (el!=null) el[i2][i1] = (eui-evi)/eui; } } } LocalOrientFilter(double sigma); LocalOrientFilter(double sigma1, double sigma2); LocalOrientFilter(double sigma1, double sigma2, double sigma3); void setGradientSmoothing(double sigma); void setGradientSmoothing(double sigma1, double sigma2); void setGradientSmoothing( double sigma1, double sigma2, double sigma3); void applyForTheta(float[][] x, float[][] theta); void applyForNormal(float[][] x, float[][] u1, float[][] u2); void applyForNormalLinear(float[][] x, float[][] u1, float[][] u2, float[][] el); EigenTensors2 applyForTensors(float[][] x); void apply(float[][] x, float[][] theta, float[][] u1, float[][] u2, float[][] v1, float[][] v2, float[][] eu, float[][] ev, float[][] el); void applyForThetaPhi(float[][][] x, float[][][] theta, float[][][] phi); void applyForNormal(float[][][] x, float[][][] u1, float[][][] u2, float[][][] u3); void applyForNormalPlanar(float[][][] x, float[][][] u1, float[][][] u2, float[][][] u3, float[][][] ep); void applyForInline(float[][][] x, float[][][] w1, float[][][] w2, float[][][] w3); void applyForInlineLinear(float[][][] x, float[][][] w1, float[][][] w2, float[][][] w3, float[][][] el); EigenTensors3 applyForTensors(float[][][] x); EigenTensors3 applyForTensors(float[][][] x, boolean compressed); void apply(float[][][] x, float[][][] theta, float[][][] phi, float[][][] u1, float[][][] u2, float[][][] u3, float[][][] v1, float[][][] v2, float[][][] v3, float[][][] w1, float[][][] w2, float[][][] w3, float[][][] eu, float[][][] ev, float[][][] ew, float[][][] ep, float[][][] el); }
@Test public void test2() { double sigma = 8.0; int n1 = 1+4*(int)(3*sigma); int n2 = n1+2; LocalOrientFilter lof = new LocalOrientFilter(sigma); float pi = FLT_PI; float[] dips = {-0.49f*pi,-0.20f*pi,-0.01f,0.01f,0.20f*pi,0.49f*pi}; for (float dip:dips) { float k = 0.3f; float c = k*cos(dip); float s = k*sin(dip); float[][] x = sin(rampfloat(0.0f,c,s,n1,n2)); float[][] theta = new float[n2][n1]; float[][] u1 = new float[n2][n1]; float[][] u2 = new float[n2][n1]; float[][] v1 = new float[n2][n1]; float[][] v2 = new float[n2][n1]; float[][] eu = new float[n2][n1]; float[][] ev = new float[n2][n1]; float[][] el = new float[n2][n1]; lof.apply(x,theta,u1,u2,v1,v2,eu,ev,el); assertEqualsLocal(dip,theta,0.01); assertEqualsLocal(cos(dip),u1,0.01); assertEqualsLocal(sin(dip),u2,0.01); assertEqualsLocal(-sin(dip),v1,0.01); assertEqualsLocal(cos(dip),v2,0.01); assertEqualsLocal(1.0f,el,0.01); } } @Test public void test3Planar() { double sigma = 6.0; int n1 = 1+2*(int)(3*sigma); int n2 = n1+2; int n3 = n2+2; LocalOrientFilter lof = new LocalOrientFilter(sigma); float pi = FLT_PI; float[] azis = {-0.50f*pi,0.25f*pi,0.99f*pi}; float[] dips = { 0.01f*pi,0.20f*pi,0.49f*pi}; for (float azi:azis) { for (float dip:dips) { float k = 0.3f; float ku1 = k*cos(dip); float ku2 = k*sin(dip)*cos(azi); float ku3 = k*sin(dip)*sin(azi); float[][][] x = sin(rampfloat(0.0f,ku1,ku2,ku3,n1,n2,n3)); float[][][] theta = new float[n3][n2][n1]; float[][][] phi = new float[n3][n2][n1]; float[][][] u1 = new float[n3][n2][n1]; float[][][] u2 = new float[n3][n2][n1]; float[][][] u3 = new float[n3][n2][n1]; float[][][] v1 = new float[n3][n2][n1]; float[][][] v2 = new float[n3][n2][n1]; float[][][] v3 = new float[n3][n2][n1]; float[][][] w1 = new float[n3][n2][n1]; float[][][] w2 = new float[n3][n2][n1]; float[][][] w3 = new float[n3][n2][n1]; float[][][] eu = new float[n3][n2][n1]; float[][][] ev = new float[n3][n2][n1]; float[][][] ew = new float[n3][n2][n1]; float[][][] ep = new float[n3][n2][n1]; float[][][] el = new float[n3][n2][n1]; lof.apply(x,theta,phi,u1,u2,u3,v1,v2,v3,w1,w2,w3,eu,ev,ew,ep,el); assertEqualsLocal(dip,theta,0.02); assertEqualsLocal(azi,phi,0.02); assertEqualsLocal(cos(dip),u1,0.02); assertEqualsLocal(sin(dip)*cos(azi),u2,0.02); assertEqualsLocal(sin(dip)*sin(azi),u3,0.02); assertEqualsLocal(1.0,ep,0.02); assertEqualsLocal(0.0,el,0.02); } } } @Test public void test3Linear() { double sigma = 6.0; int n1 = 1+2*(int)(3*sigma); int n2 = n1+2; int n3 = n2+2; LocalOrientFilter lof = new LocalOrientFilter(sigma); float pi = FLT_PI; float[] azis = {-0.50f*pi,0.25f*pi,0.99f*pi}; float[] dips = { 0.01f*pi,0.20f*pi,0.49f*pi}; for (float azi:azis) { for (float dip:dips) { float a1 = (n1-1)/2; float a2 = (n2-1)/2; float a3 = (n3-1)/2; float b1 = cos(dip); float b2 = sin(dip)*cos(azi); float b3 = sin(dip)*sin(azi); float[][][] x = new float[n3][n2][n1]; for (int i3=0; i3<n3; ++i3) { float x3 = i3-a3; for (int i2=0; i2<n2; ++i2) { float x2 = i2-a2; for (int i1=0; i1<n1; ++i1) { float x1 = i1-a1; float t = x1*b1+x2*b2+x3*b3; float d1 = x1-t*b1; float d2 = x2-t*b2; float d3 = x3-t*b3; x[i3][i2][i1] = exp(-0.125f*(d1*d1+d2*d2+d3*d3)); } } } float[][][] theta = new float[n3][n2][n1]; float[][][] phi = new float[n3][n2][n1]; float[][][] u1 = new float[n3][n2][n1]; float[][][] u2 = new float[n3][n2][n1]; float[][][] u3 = new float[n3][n2][n1]; float[][][] v1 = new float[n3][n2][n1]; float[][][] v2 = new float[n3][n2][n1]; float[][][] v3 = new float[n3][n2][n1]; float[][][] w1 = new float[n3][n2][n1]; float[][][] w2 = new float[n3][n2][n1]; float[][][] w3 = new float[n3][n2][n1]; float[][][] eu = new float[n3][n2][n1]; float[][][] ev = new float[n3][n2][n1]; float[][][] ew = new float[n3][n2][n1]; float[][][] ep = new float[n3][n2][n1]; float[][][] el = new float[n3][n2][n1]; lof.apply(x,theta,phi,u1,u2,u3,v1,v2,v3,w1,w2,w3,eu,ev,ew,ep,el); assertAbsEqual(cos(dip),w1,0.10); assertAbsEqual(sin(dip)*cos(azi),w2,0.10); assertAbsEqual(sin(dip)*sin(azi),w3,0.10); assertEqualsLocal(0.0,ep,0.2); assertEqualsLocal(1.0,el,0.2); } } }
Real1 { public Real1 plus(Real1 ra) { return add(this,ra); } Real1(Sampling s); Real1(float[] v); Real1(Sampling s, float[] v); Real1(int n, double d, double f); Real1(int n, double d, double f, float[] v); Real1(Real1 r); Sampling getSampling(); float[] getValues(); Real1 resample(Sampling s); Real1 plus(Real1 ra); Real1 plus(float ar); Real1 convolve(Real1 ra); Sampling getFourierSampling(int nmin); static Real1 zero(int n); static Real1 zero(Sampling s); static Real1 fill(double ar, int n); static Real1 fill(double ar, Sampling s); static Real1 ramp(double fv, double dv, int nv); static Real1 ramp(double fv, double dv, Sampling s); static Real1 add(Real1 ra, Real1 rb); static Real1 add(float ar, Real1 rb); static Real1 add(Real1 ra, float br); static Real1 sub(Real1 ra, Real1 rb); static Real1 sub(float ar, Real1 rb); static Real1 sub(Real1 ra, float br); static Real1 mul(Real1 ra, Real1 rb); static Real1 mul(float ar, Real1 rb); static Real1 mul(Real1 ra, float br); static Real1 div(Real1 ra, Real1 rb); static Real1 div(float ar, Real1 rb); static Real1 div(Real1 ra, float br); }
@Test public void testMath() { Real1 ra = RAMP1; Real1 rb = RAMP1; Real1 rc = ra.plus(rb); Real1 re = RAMP2; assertRealEquals(re,rc); }
Real1 { public Real1 resample(Sampling s) { Sampling t = _s; int[] overlap = t.overlapWith(s); if (overlap!=null) { int ni = overlap[0]; int it = overlap[1]; int is = overlap[2]; Real1 rt = this; Real1 rs = new Real1(s); float[] xt = rt.getValues(); float[] xs = rs.getValues(); while (--ni>=0) xs[is++] = xt[it++]; return rs; } throw new UnsupportedOperationException("no interpolation, yet"); } Real1(Sampling s); Real1(float[] v); Real1(Sampling s, float[] v); Real1(int n, double d, double f); Real1(int n, double d, double f, float[] v); Real1(Real1 r); Sampling getSampling(); float[] getValues(); Real1 resample(Sampling s); Real1 plus(Real1 ra); Real1 plus(float ar); Real1 convolve(Real1 ra); Sampling getFourierSampling(int nmin); static Real1 zero(int n); static Real1 zero(Sampling s); static Real1 fill(double ar, int n); static Real1 fill(double ar, Sampling s); static Real1 ramp(double fv, double dv, int nv); static Real1 ramp(double fv, double dv, Sampling s); static Real1 add(Real1 ra, Real1 rb); static Real1 add(float ar, Real1 rb); static Real1 add(Real1 ra, float br); static Real1 sub(Real1 ra, Real1 rb); static Real1 sub(float ar, Real1 rb); static Real1 sub(Real1 ra, float br); static Real1 mul(Real1 ra, Real1 rb); static Real1 mul(float ar, Real1 rb); static Real1 mul(Real1 ra, float br); static Real1 div(Real1 ra, Real1 rb); static Real1 div(float ar, Real1 rb); static Real1 div(Real1 ra, float br); }
@Test public void testResample() { Real1 ra = FILL1; Sampling sa = ra.getSampling(); int n1 = sa.getCount(); double d1 = sa.getDelta(); int m1 = n1/3; Sampling sb = sa.shift(-m1*d1); Real1 rb = ra.resample(sb); float[] vb = rb.getValues(); for (int i1=0; i1<m1; ++i1) assertEquals(0.0,vb[i1],0.0); for (int i1=m1; i1<n1; ++i1) assertEquals(1.0,vb[i1],0.0); Sampling sc = sa.shift(m1*d1); Real1 rc = ra.resample(sc); float[] vc = rc.getValues(); for (int i1=0; i1<n1-m1; ++i1) assertEquals(1.0,vc[i1],0.0); for (int i1=n1-m1; i1<n1; ++i1) assertEquals(0.0,vc[i1],0.0); }
RecursiveGaussianFilter { public void apply0(float[] x, float[] y) { _filter.applyN(0,x,y); } RecursiveGaussianFilter(double sigma, Method method); RecursiveGaussianFilter(double sigma); void apply0(float[] x, float[] y); void apply1(float[] x, float[] y); void apply2(float[] x, float[] y); void apply0X(float[][] x, float[][] y); void apply1X(float[][] x, float[][] y); void apply2X(float[][] x, float[][] y); void applyX0(float[][] x, float[][] y); void applyX1(float[][] x, float[][] y); void applyX2(float[][] x, float[][] y); void apply0XX(float[][][] x, float[][][] y); void apply1XX(float[][][] x, float[][][] y); void apply2XX(float[][][] x, float[][][] y); void applyX0X(float[][][] x, float[][][] y); void applyX1X(float[][][] x, float[][][] y); void applyX2X(float[][][] x, float[][][] y); void applyXX0(float[][][] x, float[][][] y); void applyXX1(float[][][] x, float[][][] y); void applyXX2(float[][][] x, float[][][] y); void apply00(float[][] x, float[][] y); void apply10(float[][] x, float[][] y); void apply01(float[][] x, float[][] y); void apply11(float[][] x, float[][] y); void apply20(float[][] x, float[][] y); void apply02(float[][] x, float[][] y); void apply000(float[][][] x, float[][][] y); void apply100(float[][][] x, float[][][] y); void apply010(float[][][] x, float[][][] y); void apply001(float[][][] x, float[][][] y); void apply110(float[][][] x, float[][][] y); void apply101(float[][][] x, float[][][] y); void apply011(float[][][] x, float[][][] y); void apply200(float[][][] x, float[][][] y); void apply020(float[][][] x, float[][][] y); void apply002(float[][][] x, float[][][] y); }
@Test public void test1() { float sigma = 10.0f; int n = 1+2*(int)(sigma*4.0f); int k = (n-1)/2; float[] x = zerofloat(n); float[] y = zerofloat(n); x[k] = 1.0f; float tolerance = 0.01f*gaussian(sigma,0.0f); RecursiveGaussianFilter rf = new RecursiveGaussianFilter(sigma); rf.apply0(x,y); for (int i=0; i<n; ++i) { float gi = gaussian(sigma,i-k); assertEquals(gi,y[i],tolerance); } }
MedianFinder { public float findMedian(float[] x) { Check.argument(_n==x.length,"length of x is valid"); copy(x,_x); int k = (_n-1)/2; quickPartialSort(k,_x); float xmed = _x[k]; if (_n%2==0) { float xmin = _x[_n-1]; for (int i=_n-2; i>k; --i) if (_x[i]<xmin) xmin = _x[i]; xmed = 0.5f*(xmed+xmin); } return xmed; } MedianFinder(int n); float findMedian(float[] x); float findMedian(float[] w, float[] x); }
@Test public void testUnweighted() { Random r = new Random(); int ntest = 100; for (int itest=0; itest<ntest; ++itest) { int n = 1+(r.nextBoolean()?r.nextInt(100):r.nextInt(10)); float[] f = randfloat(n); float[] w = fillfloat(1.0f,n); if (r.nextBoolean()) { for (int i=n/4; i<3*n/4; ++i) f[i] = f[0]; } MedianFinder mf = new MedianFinder(n); float ew = mf.findMedian(w,f); float eu = mf.findMedian(f); assertEquals(ew,eu); } } @Test public void testWeighted() { Random r = new Random(); int ntest = 100; for (int itest=0; itest<ntest; ++itest) { int n = 1+(r.nextBoolean()?r.nextInt(100):r.nextInt(10)); float[] w = randfloat(n); float[] f = randfloat(n); int[] k = rampint(0,1,n); quickIndexSort(f,k); float wsum = 0.0f; float wtotal = sum(w); int i; for (i=0; i<n && wsum<0.5f*wtotal; ++i) wsum += w[k[i]]; float qslow = f[k[i-1]]; MedianFinder mf = new MedianFinder(n); float qfast = mf.findMedian(w,f); assertEquals(qslow,qfast); } }
RecursiveGaussianFilter { public void apply00(float[][] x, float[][] y) { _filter.applyXN(0,x,y); _filter.applyNX(0,y,y); } RecursiveGaussianFilter(double sigma, Method method); RecursiveGaussianFilter(double sigma); void apply0(float[] x, float[] y); void apply1(float[] x, float[] y); void apply2(float[] x, float[] y); void apply0X(float[][] x, float[][] y); void apply1X(float[][] x, float[][] y); void apply2X(float[][] x, float[][] y); void applyX0(float[][] x, float[][] y); void applyX1(float[][] x, float[][] y); void applyX2(float[][] x, float[][] y); void apply0XX(float[][][] x, float[][][] y); void apply1XX(float[][][] x, float[][][] y); void apply2XX(float[][][] x, float[][][] y); void applyX0X(float[][][] x, float[][][] y); void applyX1X(float[][][] x, float[][][] y); void applyX2X(float[][][] x, float[][][] y); void applyXX0(float[][][] x, float[][][] y); void applyXX1(float[][][] x, float[][][] y); void applyXX2(float[][][] x, float[][][] y); void apply00(float[][] x, float[][] y); void apply10(float[][] x, float[][] y); void apply01(float[][] x, float[][] y); void apply11(float[][] x, float[][] y); void apply20(float[][] x, float[][] y); void apply02(float[][] x, float[][] y); void apply000(float[][][] x, float[][][] y); void apply100(float[][][] x, float[][][] y); void apply010(float[][][] x, float[][][] y); void apply001(float[][][] x, float[][][] y); void apply110(float[][][] x, float[][][] y); void apply101(float[][][] x, float[][][] y); void apply011(float[][][] x, float[][][] y); void apply200(float[][][] x, float[][][] y); void apply020(float[][][] x, float[][][] y); void apply002(float[][][] x, float[][][] y); }
@Test public void test2() { float sigma = 10.0f; int n1 = 1+2*(int)(sigma*4.0f); int n2 = n1+2; int k1 = (n1-1)/2; int k2 = (n2-1)/2; float[][] x = zerofloat(n1,n2); float[][] y = zerofloat(n1,n2); x[k2][k1] = 1.0f; float tolerance = 0.01f*gaussian(sigma,0.0f,0.0f); RecursiveGaussianFilter rf = new RecursiveGaussianFilter(sigma); rf.apply00(x,y); for (int i2=0; i2<n2; ++i2) { for (int i1=0; i1<n1; ++i1) { float gi = gaussian(sigma,i1-k1,i2-k2); assertEquals(gi,y[i2][i1],tolerance); } } }
RecursiveGaussianFilter { public void apply000(float[][][] x, float[][][] y) { _filter.applyXXN(0,x,y); _filter.applyXNX(0,y,y); _filter.applyNXX(0,y,y); } RecursiveGaussianFilter(double sigma, Method method); RecursiveGaussianFilter(double sigma); void apply0(float[] x, float[] y); void apply1(float[] x, float[] y); void apply2(float[] x, float[] y); void apply0X(float[][] x, float[][] y); void apply1X(float[][] x, float[][] y); void apply2X(float[][] x, float[][] y); void applyX0(float[][] x, float[][] y); void applyX1(float[][] x, float[][] y); void applyX2(float[][] x, float[][] y); void apply0XX(float[][][] x, float[][][] y); void apply1XX(float[][][] x, float[][][] y); void apply2XX(float[][][] x, float[][][] y); void applyX0X(float[][][] x, float[][][] y); void applyX1X(float[][][] x, float[][][] y); void applyX2X(float[][][] x, float[][][] y); void applyXX0(float[][][] x, float[][][] y); void applyXX1(float[][][] x, float[][][] y); void applyXX2(float[][][] x, float[][][] y); void apply00(float[][] x, float[][] y); void apply10(float[][] x, float[][] y); void apply01(float[][] x, float[][] y); void apply11(float[][] x, float[][] y); void apply20(float[][] x, float[][] y); void apply02(float[][] x, float[][] y); void apply000(float[][][] x, float[][][] y); void apply100(float[][][] x, float[][][] y); void apply010(float[][][] x, float[][][] y); void apply001(float[][][] x, float[][][] y); void apply110(float[][][] x, float[][][] y); void apply101(float[][][] x, float[][][] y); void apply011(float[][][] x, float[][][] y); void apply200(float[][][] x, float[][][] y); void apply020(float[][][] x, float[][][] y); void apply002(float[][][] x, float[][][] y); }
@Test public void test3() { float sigma = 10.0f; int n1 = 1+2*(int)(sigma*4.0f); int n2 = n1+2; int n3 = n2+2; int k1 = (n1-1)/2; int k2 = (n2-1)/2; int k3 = (n3-1)/2; float[][][] x = zerofloat(n1,n2,n3); float[][][] y = zerofloat(n1,n2,n3); x[k3][k2][k1] = 1.0f; float tolerance = 0.01f*gaussian(sigma,0.0f,0.0f); RecursiveGaussianFilter rf = new RecursiveGaussianFilter(sigma); rf.apply000(x,y); for (int i3=0; i3<n3; ++i3) { for (int i2=0; i2<n2; ++i2) { for (int i1=0; i1<n1; ++i1) { float gi = gaussian(sigma,i1-k1,i2-k2,i3-k3); assertEquals(gi,y[i3][i2][i1],tolerance); } } } }
SymmetricTridiagonalFilter { private static SymmetricTridiagonalFilter makeRandomFilter() { java.util.Random r = new java.util.Random(); float af,ai,al,b; boolean aeq2b = r.nextBoolean(); boolean abneg = r.nextBoolean(); boolean afzs = r.nextBoolean(); boolean alzs = r.nextBoolean(); if (aeq2b && afzs==true && alzs==true) { if (r.nextBoolean()) { afzs = false; } else { alzs = false; } } b = r.nextFloat(); ai = 2.0f*b; if (!aeq2b) ai += max(0.001,r.nextFloat())*b; if (abneg) ai = -ai; af = ai; al = ai; if (afzs) af = ai+b; if (alzs) al = ai+b; return new SymmetricTridiagonalFilter(af,ai,al,b); } SymmetricTridiagonalFilter( double af, double ai, double al, double b); void apply(float[] x, float[] y); void apply1(final float[][] x, final float[][] y); void apply2(final float[][] x, final float[][] y); void apply1(final float[][][] x, final float[][][] y); void apply2(final float[][][] x, final float[][][] y); void apply3(float[][][] x, float[][][] y); void applyInverse(float[] x, float[] y); void applyInverse1(final float[][] x, final float[][] y); void applyInverse2(float[][] x, float[][] y); void applyInverse1(final float[][][] x, final float[][][] y); void applyInverse2(final float[][][] x, final float[][][] y); void applyInverse3(float[][][] x, float[][][] y); static void test1Simple(); static void test2Simple(); static void test3Simple(); static void test1Random(); static void test2Random(); static void test3Random(); static void main(String[] args); }
@Test private static SymmetricTridiagonalFilter makeRandomFilter() { java.util.Random r = new java.util.Random(); float af,ai,al,b; boolean aeq2b = r.nextBoolean(); boolean abneg = r.nextBoolean(); boolean afzs = r.nextBoolean(); boolean alzs = r.nextBoolean(); if (aeq2b && afzs==true && alzs==true) { if (r.nextBoolean()) { afzs = false; } else { alzs = false; } } b = r.nextFloat(); ai = 2.0f*b; if (!aeq2b) ai += max(0.001,r.nextFloat())*b; if (abneg) ai = -ai; af = ai; al = ai; if (afzs) af = ai+b; if (alzs) al = ai+b; return new SymmetricTridiagonalFilter(af,ai,al,b); }
LocalShiftFinder { public void find1( int min1, int max1, float[] f, float[] g, float[] u) { findShifts(min1,max1,f,g,u,null,null); } LocalShiftFinder(double sigma); LocalShiftFinder(double sigma1, double sigma2); LocalShiftFinder(double sigma1, double sigma2, double sigma3); void setInterpolateDisplacements(boolean enable); void find1( int min1, int max1, float[] f, float[] g, float[] u); void find1( int min1, int max1, float[] f, float[] g, float[] u, float[] c, float[] d); void find1( int min1, int max1, float[][] f, float[][] g, float[][] u); void find2( int min2, int max2, float[][] f, float[][] g, float[][] u); void find1( int min1, int max1, float[][][] f, float[][][] g, float[][][] u); void find2( int min2, int max2, float[][][] f, float[][][] g, float[][][] u); void find3( int min3, int max3, float[][][] f, float[][][] g, float[][][] u); void shift1(float[] du, float[] u1, float[] h); void shift1(float[][] du, float[][] u1, float[][] u2, float[][] h); void shift2(float[][] du, float[][] u1, float[][] u2, float[][] h); void shift1( float[][][] du, float[][][] u1, float[][][] u2, float[][][] u3, float[][][] h); void shift2( float[][][] du, float[][][] u1, float[][][] u2, float[][][] u3, float[][][] h); void shift3( float[][][] du, float[][][] u1, float[][][] u2, float[][][] u3, float[][][] h); void whiten(float[][] f, float[][] g); void whiten(double sigma, float[][] f, float[][] g); void whiten(float[][][] f, float[][][] g); void whiten(double sigma, float[][][] f, float[][][] g); }
@Test public void testCosine() { float w = 0.02f*2.0f*FLT_PI; int n1 = 1001; float shift = 10.0f; float sigma = 8.0f*shift; float[] f = cos(rampfloat(w*shift,w,n1)); float[] g = cos(rampfloat(0.0f,w,n1)); float[] u = new float[n1]; float[] c = new float[n1]; float[] d = new float[n1]; int min1 = -2*(int)shift; int max1 = 2*(int)shift; LocalShiftFinder lsf = new LocalShiftFinder(shift); lsf.find1(min1,max1,f,g,u,c,d); for (int i1=n1/4; i1<3*n1/4; ++i1) { assertEquals(shift,u[i1],0.02f); assertEquals(1.0f,c[i1],0.02f); assertEquals(1.0f,d[i1],0.02f); } }
BicubicInterpolator2 { public float interpolate(float x1, float x2) { return interpolate00(x1,x2); } BicubicInterpolator2(float[] x1, float[] x2, float[][] y); BicubicInterpolator2( Method method1, Method method2, float[] x1, float[] x2, float[][] y); BicubicInterpolator2( Method method1, Method method2, int n1, int n2, float[] x1, float[] x2, float[][] y); float interpolate(float x1, float x2); float interpolate00(float x1, float x2); float interpolate10(float x1, float x2); float interpolate01(float x1, float x2); float[][] interpolate(Sampling s1, Sampling s2); float[][] interpolate00(Sampling s1, Sampling s2); void interpolate(Sampling s1, Sampling s2, float[][] y); void interpolate00(Sampling s1, Sampling s2, float[][] y); float[][] interpolate(float[] x1, float[] x2); float[][] interpolate00(float[] x1, float[] x2); void interpolate(float[] x1, float[] x2, float[][] y); void interpolate00(float[] x1, float[] x2, float[][] y); }
@Test public void testArrayValues() { float[][][] xy = sampleTestFunction(11,13); float[] x1 = xy[0][0]; float[] x2 = xy[0][1]; float[][] y = xy[1]; float x1min = min(x1), x1max = max(x1); float x2min = min(x2), x2max = max(x2); BicubicInterpolator2 bi = makeInterpolator(x1,x2,y); int n1i = 101; int n2i = 102; float d1i = (x1max-x1min)/(n1i-1); float d2i = (x2max-x2min)/(n2i-1); float f1i = x1min; float f2i = x2min; float[] x1i = rampfloat(f1i,d1i,n1i); float[] x2i = rampfloat(f2i,d2i,n2i); float[][] yi = bi.interpolate(x1i,x2i); for (int i2i=0; i2i<n2i; ++i2i) for (int i1i=0; i1i<n1i; ++i1i) assertEqual(testFunction00(x1i[i1i],x2i[i2i]),yi[i2i][i1i]); } @Test public void testSampleValues() { float[][][] xy = sampleTestFunction(11,13); float[] x1 = xy[0][0]; float[] x2 = xy[0][1]; float[][] y = xy[1]; float x1min = min(x1), x1max = max(x1); float x2min = min(x2), x2max = max(x2); BicubicInterpolator2 bi = makeInterpolator(x1,x2,y); int n1i = 101; int n2i = 102; float d1i = (x1max-x1min)/(n1i-1); float d2i = (x2max-x2min)/(n2i-1); float f1i = x1min; float f2i = x2min; Sampling s1i = new Sampling(n1i,d1i,f1i); Sampling s2i = new Sampling(n2i,d2i,f2i); float[][] yi = bi.interpolate(s1i,s2i); for (int i2i=0; i2i<n2i; ++i2i) { float x2i = (float)s2i.getValue(i2i); for (int i1i=0; i1i<n1i; ++i1i) { float x1i = (float)s1i.getValue(i1i); assertEqual(testFunction00(x1i,x2i),yi[i2i][i1i]); } } }
TrilinearInterpolator3 { public float interpolate(float x1, float x2, float x3) { return interpolate000(x1,x2,x3); } TrilinearInterpolator3( float[] x1, float[] x2, float[] x3, float[][][] y); TrilinearInterpolator3( int n1, int n2, int n3, float[] x1, float[] x2, float[] x3, float[][][] y); float interpolate(float x1, float x2, float x3); float interpolate000(float x1, float x2, float x3); float interpolate100(float x1, float x2, float x3); float interpolate010(float x1, float x2, float x3); float interpolate001(float x1, float x2, float x3); float[][][] interpolate(Sampling s1, Sampling s2, Sampling s3); float[][][] interpolate000(Sampling s1, Sampling s2, Sampling s3); void interpolate( Sampling s1, Sampling s2, Sampling s3, float[][][] y); void interpolate000( Sampling s1, Sampling s2, Sampling s3, float[][][] y); float[][][] interpolate(float[] x1, float[] x2, float[] x3); float[][][] interpolate000(float[] x1, float[] x2, float[] x3); void interpolate( float[] x1, float[] x2, float[] x3, float[][][] y); void interpolate000( float[] x1, float[] x2, float[] x3, float[][][] y); }
@Test public void testArrayValues() { float[][][][] xy = sampleTestFunction(11,12,13); float[] x1 = xy[0][0][0]; float[] x2 = xy[0][0][1]; float[] x3 = xy[0][0][2]; float[][][] y = xy[1]; float x1min = min(x1), x1max = max(x1); float x2min = min(x2), x2max = max(x2); float x3min = min(x3), x3max = max(x3); TrilinearInterpolator3 ti = makeInterpolator(x1,x2,x3,y); int n1i = 51; int n2i = 52; int n3i = 53; float d1i = (x1max-x1min)/(n1i-1); float d2i = (x2max-x2min)/(n2i-1); float d3i = (x3max-x3min)/(n3i-1); float f1i = x1min; float f2i = x2min; float f3i = x3min; float[] x1i = rampfloat(f1i,d1i,n1i); float[] x2i = rampfloat(f2i,d2i,n2i); float[] x3i = rampfloat(f3i,d3i,n3i); float[][][] yi = ti.interpolate(x1i,x2i,x3i); for (int i3i=0; i3i<n3i; ++i3i) { for (int i2i=0; i2i<n2i; ++i2i) { for (int i1i=0; i1i<n1i; ++i1i) { float zi = testFunction000(x1i[i1i],x2i[i2i],x3i[i3i]); assertEqual(zi,yi[i3i][i2i][i1i]); } } } } @Test public void testSampleValues() { float[][][][] xy = sampleTestFunction(11,12,13); float[] x1 = xy[0][0][0]; float[] x2 = xy[0][0][1]; float[] x3 = xy[0][0][2]; float[][][] y = xy[1]; float x1min = min(x1), x1max = max(x1); float x2min = min(x2), x2max = max(x2); float x3min = min(x3), x3max = max(x3); TrilinearInterpolator3 ti = makeInterpolator(x1,x2,x3,y); int n1i = 51; int n2i = 52; int n3i = 53; float d1i = (x1max-x1min)/(n1i-1); float d2i = (x2max-x2min)/(n2i-1); float d3i = (x3max-x3min)/(n3i-1); float f1i = x1min; float f2i = x2min; float f3i = x3min; Sampling s1i = new Sampling(n1i,d1i,f1i); Sampling s2i = new Sampling(n2i,d2i,f2i); Sampling s3i = new Sampling(n3i,d3i,f3i); float[][][] yi = ti.interpolate(s1i,s2i,s3i); for (int i3i=0; i3i<n3i; ++i3i) { float x3i = (float)s3i.getValue(i3i); for (int i2i=0; i2i<n2i; ++i2i) { float x2i = (float)s2i.getValue(i2i); for (int i1i=0; i1i<n1i; ++i1i) { float x1i = (float)s1i.getValue(i1i); float zi = testFunction000(x1i,x2i,x3i); assertEqual(zi,yi[i3i][i2i][i1i]); } } } }
TricubicInterpolator3 { public float interpolate(float x1, float x2, float x3) { return interpolate000(x1,x2,x3); } TricubicInterpolator3( float[] x1, float[] x2, float[] x3, float[][][] y); TricubicInterpolator3( Method method1, Method method2, Method method3, float[] x1, float[] x2, float[] x3, float[][][] y); TricubicInterpolator3( Method method1, Method method2, Method method3, int n1, int n2, int n3, float[] x1, float[] x2, float[] x3, float[][][] y); float interpolate(float x1, float x2, float x3); float interpolate000(float x1, float x2, float x3); float interpolate100(float x1, float x2, float x3); float interpolate010(float x1, float x2, float x3); float interpolate001(float x1, float x2, float x3); float[][][] interpolate(Sampling s1, Sampling s2, Sampling s3); float[][][] interpolate000(Sampling s1, Sampling s2, Sampling s3); void interpolate( Sampling s1, Sampling s2, Sampling s3, float[][][] y); void interpolate000( Sampling s1, Sampling s2, Sampling s3, float[][][] y); float[][][] interpolate(float[] x1, float[] x2, float[] x3); float[][][] interpolate000(float[] x1, float[] x2, float[] x3); void interpolate( float[] x1, float[] x2, float[] x3, float[][][] y); void interpolate000( float[] x1, float[] x2, float[] x3, float[][][] y); }
@Test public void testArrayValues() { float[][][][] xy = sampleTestFunction(11,12,13); float[] x1 = xy[0][0][0]; float[] x2 = xy[0][0][1]; float[] x3 = xy[0][0][2]; float[][][] y = xy[1]; float x1min = min(x1), x1max = max(x1); float x2min = min(x2), x2max = max(x2); float x3min = min(x3), x3max = max(x3); TricubicInterpolator3 ti = makeInterpolator(x1,x2,x3,y); int n1i = 51; int n2i = 52; int n3i = 53; float d1i = (x1max-x1min)/(n1i-1); float d2i = (x2max-x2min)/(n2i-1); float d3i = (x3max-x3min)/(n3i-1); float f1i = x1min; float f2i = x2min; float f3i = x3min; float[] x1i = rampfloat(f1i,d1i,n1i); float[] x2i = rampfloat(f2i,d2i,n2i); float[] x3i = rampfloat(f3i,d3i,n3i); float[][][] yi = ti.interpolate(x1i,x2i,x3i); for (int i3i=0; i3i<n3i; ++i3i) { for (int i2i=0; i2i<n2i; ++i2i) { for (int i1i=0; i1i<n1i; ++i1i) { float zi = testFunction000(x1i[i1i],x2i[i2i],x3i[i3i]); assertNear(zi,yi[i3i][i2i][i1i]); } } } } @Test public void testSampleValues() { float[][][][] xy = sampleTestFunction(11,12,13); float[] x1 = xy[0][0][0]; float[] x2 = xy[0][0][1]; float[] x3 = xy[0][0][2]; float[][][] y = xy[1]; float x1min = min(x1), x1max = max(x1); float x2min = min(x2), x2max = max(x2); float x3min = min(x3), x3max = max(x3); TricubicInterpolator3 ti = makeInterpolator(x1,x2,x3,y); int n1i = 51; int n2i = 52; int n3i = 53; float d1i = (x1max-x1min)/(n1i-1); float d2i = (x2max-x2min)/(n2i-1); float d3i = (x3max-x3min)/(n3i-1); float f1i = x1min; float f2i = x2min; float f3i = x3min; Sampling s1i = new Sampling(n1i,d1i,f1i); Sampling s2i = new Sampling(n2i,d2i,f2i); Sampling s3i = new Sampling(n3i,d3i,f3i); float[][][] yi = ti.interpolate(s1i,s2i,s3i); for (int i3i=0; i3i<n3i; ++i3i) { float x3i = (float)s3i.getValue(i3i); for (int i2i=0; i2i<n2i; ++i2i) { float x2i = (float)s2i.getValue(i2i); for (int i1i=0; i1i<n1i; ++i1i) { float x1i = (float)s1i.getValue(i1i); float zi = testFunction000(x1i,x2i,x3i); assertNear(zi,yi[i3i][i2i][i1i]); } } } }
BilinearInterpolator2 { public float interpolate(float x1, float x2) { return interpolate00(x1,x2); } BilinearInterpolator2(float[] x1, float[] x2, float[][] y); BilinearInterpolator2( int n1, int n2, float[] x1, float[] x2, float[][] y); float interpolate(float x1, float x2); float interpolate00(float x1, float x2); float interpolate10(float x1, float x2); float interpolate01(float x1, float x2); float[][] interpolate(Sampling s1, Sampling s2); float[][] interpolate00(Sampling s1, Sampling s2); void interpolate(Sampling s1, Sampling s2, float[][] y); void interpolate00(Sampling s1, Sampling s2, float[][] y); float[][] interpolate(float[] x1, float[] x2); float[][] interpolate00(float[] x1, float[] x2); void interpolate(float[] x1, float[] x2, float[][] y); void interpolate00(float[] x1, float[] x2, float[][] y); }
@Test public void testArrayValues() { float[][][] xy = sampleTestFunction(11,13); float[] x1 = xy[0][0]; float[] x2 = xy[0][1]; float[][] y = xy[1]; float x1min = min(x1), x1max = max(x1); float x2min = min(x2), x2max = max(x2); BilinearInterpolator2 bi = makeInterpolator(x1,x2,y); int n1i = 101; int n2i = 102; float d1i = (x1max-x1min)/(n1i-1); float d2i = (x2max-x2min)/(n2i-1); float f1i = x1min; float f2i = x2min; float[] x1i = rampfloat(f1i,d1i,n1i); float[] x2i = rampfloat(f2i,d2i,n2i); float[][] yi = bi.interpolate(x1i,x2i); for (int i2i=0; i2i<n2i; ++i2i) for (int i1i=0; i1i<n1i; ++i1i) assertNear(testFunction00(x1i[i1i],x2i[i2i]),yi[i2i][i1i]); } @Test public void testSampleValues() { float[][][] xy = sampleTestFunction(11,13); float[] x1 = xy[0][0]; float[] x2 = xy[0][1]; float[][] y = xy[1]; float x1min = min(x1), x1max = max(x1); float x2min = min(x2), x2max = max(x2); BilinearInterpolator2 bi = makeInterpolator(x1,x2,y); int n1i = 101; int n2i = 102; float d1i = (x1max-x1min)/(n1i-1); float d2i = (x2max-x2min)/(n2i-1); float f1i = x1min; float f2i = x2min; Sampling s1i = new Sampling(n1i,d1i,f1i); Sampling s2i = new Sampling(n2i,d2i,f2i); float[][] yi = bi.interpolate(s1i,s2i); for (int i2i=0; i2i<n2i; ++i2i) { float x2i = (float)s2i.getValue(i2i); for (int i1i=0; i1i<n1i; ++i1i) { float x1i = (float)s1i.getValue(i1i); assertNear(testFunction00(x1i,x2i),yi[i2i][i1i]); } } }
Projector { public void merge(Projector p) { if (p==null) return; double u0a = _u0; double u1a = _u1; double v0a = _v0; double v1a = _v1; double u0b = p._u0; double u1b = p._u1; double v0b = p._v0; double v1b = p._v1; if (signum(v1a-v0a)!=signum(v1b-v0b)) { u0b = 1.0-p._u1; u1b = 1.0-p._u0; v0b = p._v1; v1b = p._v0; } double vmin = min(min(v0a,v1a),min(v0b,v1b)); double vmax = max(max(v0a,v1a),max(v0b,v1b)); _v0 = (v0a<v1a)?vmin:vmax; _v1 = (v0a<v1a)?vmax:vmin; double r0a = (v0a-_v0)/(_v1-_v0); double r0b = (v0b-_v0)/(_v1-_v0); double r1a = (v1a-_v0)/(_v1-_v0); double r1b = (v1b-_v0)/(_v1-_v0); assert 0<=r0a && r0a<1 : r0a; assert 0<=r0b && r0b<1 : r0b; assert 0<r1a && r1a<=1 : r1a; assert 0<r1b && r1b<=1 : r1b; double u0 = 0.0; double u1 = 1.0; int niter = 0; do { _u0 = u0; _u1 = u1; u0 = max((u0a-r0a*_u1)/(1.0-r0a),(u0b-r0b*_u1)/(1.0-r0b)); u1 = min((u1a-(1.0-r1a)*_u0)/r1a,(u1b-(1.0-r1b)*_u0)/r1b); ++niter; } while ((_u0<u0 || u1<_u1) && niter<10); assert niter<10:"niter<10"; assert 0.0<=_u0 && _u0<_u1 && _u1<=1.0:"_u0 and _u1 valid"; if(p.isLinear() && !isLinear()) setScale(AxisScale.LINEAR); computeShiftsAndScales(); } Projector(double v0, double v1); Projector(double v0, double v1, AxisScale scale); Projector(double v0, double v1, double u0, double u1); Projector(double v0, double v1, double u0, double u1, AxisScale s); Projector(Projector p); double u(double v); double v(double u); double u0(); double u1(); double v0(); double v1(); AxisScale getScale(); boolean isLinear(); boolean isLog(); void merge(Projector p); double getScaleRatio(Projector p); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); }
@Test public void testMergeA () { Projector pa = new Projector(0, 1); Projector pb = new Projector(0, 1); pa.merge(pb); Projector expected = new Projector(0,1); assertVeryClose(expected,pa); } @Test public void testMergeB () { Projector pa = new Projector(0, 1); Projector pb = new Projector(1, 0); pa.merge(pb); Projector expected = new Projector(0,1); assertVeryClose(expected,pa); } @Test public void testMergeC () { Projector pa = new Projector(1, 0); Projector pb = new Projector(0, 1); pa.merge(pb); Projector expected = new Projector(1,0); assertVeryClose(expected,pa); } @Test public void testMergeD () { Projector pa = new Projector(1, 0); Projector pb = new Projector(1, 0); pa.merge(pb); Projector expected = new Projector(1,0); assertVeryClose(expected,pa); } @Test public void testMergeE () { Projector pa = new Projector(10, 0); Projector pb = new Projector( 1, 11); pa.merge(pb); Projector expected = new Projector(11,0); assertVeryClose(expected, pa); } @Test public void testMergeF () { Projector pa = new Projector(10, 5); Projector pb = new Projector( 1, 11); pa.merge(pb); Projector expected = new Projector(11,1); assertVeryClose(expected, pa); } @Test public void testMergeG () { Projector pa = new Projector( 1, 11); Projector pb = new Projector(10, 0); pa.merge(pb); Projector expected = new Projector(0,11); assertVeryClose(expected, pa); } @Test public void testMergeH () { Projector pa = new Projector( 1.5, 1.4); Projector pb = new Projector( 1, 2); pa.merge(pb); Projector expected = new Projector(2,1); assertVeryClose(expected, pa); } @Test public void testMerge1 () { Projector pa = new Projector(10, 20, 0.1, 0.8); Projector pb = new Projector(10, 20, 0.0, 1.0); pa.merge(pb); Projector expected = new Projector(10, 20, 0.1, 0.8); assertVeryClose(expected,pa); } @Test public void testMerge1r () { Projector pa = new Projector(10, 20, 0.0, 1.0); Projector pb = new Projector(10, 20, 0.1, 0.8); pa.merge(pb); Projector expected = new Projector(10, 20, 0.1, 0.8); assertVeryClose(expected,pa); } @Test public void testMerge2 () { Projector pa = new Projector(10, 20, 0.1, 0.8); Projector pb = new Projector(20, 10, 0.0, 1.0); pa.merge(pb); Projector expected = new Projector(10, 20, 0.1, 0.8); assertVeryClose(expected,pa); } @Test public void testMerge2r () { Projector pa = new Projector(20, 10, 0.0, 1.0); Projector pb = new Projector(10, 20, 0.1, 0.8); pa.merge(pb); Projector expected = new Projector(20, 10, 0.2, 0.9); assertVeryClose(expected,pa); } @Test public void testMerge3 () { Projector pa = new Projector(10, 20, 0.0, 1.0); Projector pb = new Projector(20, 10, 0.1, 0.8); pa.merge(pb); Projector expected = new Projector(10, 20, 0.2, 0.9); assertVeryClose(expected,pa); } @Test public void testMerge3r () { Projector pa = new Projector(20, 10, 0.1, 0.8); Projector pb = new Projector(10, 20, 0.0, 1.0); pa.merge(pb); Projector expected = new Projector(20, 10, 0.1, 0.8); assertVeryClose(expected,pa); } @Test public void testMergeALog () { Projector pa = new Projector(0, 1, AxisScale.LOG10); Projector pb = new Projector(0, 1, AxisScale.LOG10); pa.merge(pb); Projector expected = new Projector(0,1, AxisScale.LOG10); assertVeryClose(expected,pa); } @Test public void testMergeBLog () { Projector pa = new Projector(0, 1, AxisScale.LOG10); Projector pb = new Projector(1, 0, AxisScale.LOG10); pa.merge(pb); Projector expected = new Projector(0,1, AxisScale.LOG10); assertVeryClose(expected,pa); } @Test public void testMergeCLog () { Projector pa = new Projector(1, 0, AxisScale.LOG10); Projector pb = new Projector(0, 1, AxisScale.LOG10); pa.merge(pb); Projector expected = new Projector(1,0, AxisScale.LOG10); assertVeryClose(expected,pa); } @Test public void testMergeDLog () { Projector pa = new Projector(1, 0, AxisScale.LOG10); Projector pb = new Projector(1, 0, AxisScale.LOG10); pa.merge(pb); Projector expected = new Projector(1,0, AxisScale.LOG10); assertVeryClose(expected,pa); } @Test public void testMergeELog () { Projector pa = new Projector(10, 0, AxisScale.LOG10); Projector pb = new Projector( 1, 11, AxisScale.LOG10); pa.merge(pb); Projector expected = new Projector(11,0, AxisScale.LOG10); assertVeryClose(expected, pa); } @Test public void testMergeFLog () { Projector pa = new Projector(10, 5, AxisScale.LOG10); Projector pb = new Projector( 1, 11, AxisScale.LOG10); pa.merge(pb); Projector expected = new Projector(11,1, AxisScale.LOG10); assertVeryClose(expected, pa); } @Test public void testMergeGLog () { Projector pa = new Projector( 1, 11, AxisScale.LOG10); Projector pb = new Projector(10, 0, AxisScale.LOG10); pa.merge(pb); Projector expected = new Projector(0,11, AxisScale.LOG10); assertVeryClose(expected, pa); } @Test public void testMergeHLog () { Projector pa = new Projector( 1.5, 1.4, AxisScale.LOG10); Projector pb = new Projector( 1, 2, AxisScale.LOG10); pa.merge(pb); Projector expected = new Projector(2,1, AxisScale.LOG10); assertVeryClose(expected, pa); } @Test public void testMerge1Log () { Projector pa = new Projector(10, 20, 0.1, 0.8, AxisScale.LOG10); Projector pb = new Projector(10, 20, 0.0, 1.0, AxisScale.LOG10); pa.merge(pb); Projector expected = new Projector(10, 20, 0.1, 0.8, AxisScale.LOG10); assertVeryClose(expected,pa); } @Test public void testMerge1rLog () { Projector pa = new Projector(10, 20, 0.0, 1.0, AxisScale.LOG10); Projector pb = new Projector(10, 20, 0.1, 0.8, AxisScale.LOG10); pa.merge(pb); Projector expected = new Projector(10, 20, 0.1, 0.8, AxisScale.LOG10); assertVeryClose(expected,pa); } @Test public void testMerge2Log () { Projector pa = new Projector(10, 20, 0.1, 0.8, AxisScale.LOG10); Projector pb = new Projector(20, 10, 0.0, 1.0, AxisScale.LOG10); pa.merge(pb); Projector expected = new Projector(10, 20, 0.1, 0.8, AxisScale.LOG10); assertVeryClose(expected,pa); } @Test public void testMerge2rLog () { Projector pa = new Projector(20, 10, 0.0, 1.0, AxisScale.LOG10); Projector pb = new Projector(10, 20, 0.1, 0.8, AxisScale.LOG10); pa.merge(pb); Projector expected = new Projector(20, 10, 0.2, 0.9, AxisScale.LOG10); assertVeryClose(expected,pa); } @Test public void testMerge3Log () { Projector pa = new Projector(10, 20, 0.0, 1.0, AxisScale.LOG10); Projector pb = new Projector(20, 10, 0.1, 0.8, AxisScale.LOG10); pa.merge(pb); Projector expected = new Projector(10, 20, 0.2, 0.9, AxisScale.LOG10); assertVeryClose(expected,pa); } @Test public void testMerge3rLog () { Projector pa = new Projector(20, 10, 0.1, 0.8, AxisScale.LOG10); Projector pb = new Projector(10, 20, 0.0, 1.0, AxisScale.LOG10); pa.merge(pb); Projector expected = new Projector(20, 10, 0.1, 0.8, AxisScale.LOG10); assertVeryClose(expected,pa); }
ArrayQueue { public E first() { if (_size==0) throw new NoSuchElementException(); @SuppressWarnings("unchecked") E e = (E)_array[_first]; return e; } ArrayQueue(); ArrayQueue(int capacity); void add(E e); E first(); E remove(); boolean isEmpty(); void ensureCapacity(int capacity); int size(); void trimToSize(); }
@Test(expectedExceptions = NoSuchElementException.class) public void testEmptyQueueFirstElementThrowsException() { aq.first(); }
Projector { public AxisScale getScale() { return _scaleType; } Projector(double v0, double v1); Projector(double v0, double v1, AxisScale scale); Projector(double v0, double v1, double u0, double u1); Projector(double v0, double v1, double u0, double u1, AxisScale s); Projector(Projector p); double u(double v); double v(double u); double u0(); double u1(); double v0(); double v1(); AxisScale getScale(); boolean isLinear(); boolean isLog(); void merge(Projector p); double getScaleRatio(Projector p); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); }
@Test public void testAutoLinear() { Projector p = new Projector(0.0, 100, 0.0, 1.0); assertTrue(p.getScale() == AxisScale.LINEAR); }
ArrayQueue { public E remove() { if (_size==0) throw new NoSuchElementException(); @SuppressWarnings("unchecked") E e = (E)_array[_first]; ++_first; if (_first==_length) _first = 0; --_size; if (_size*3<_length) resize(_size*2); return e; } ArrayQueue(); ArrayQueue(int capacity); void add(E e); E first(); E remove(); boolean isEmpty(); void ensureCapacity(int capacity); int size(); void trimToSize(); }
@Test(expectedExceptions = NoSuchElementException.class) public void testEmptyQueueRemoveElementThrowsException() { aq.remove(); }
AtomicFloat extends Number implements java.io.Serializable { public final float get() { return f(_ai.get()); } AtomicFloat(); AtomicFloat(float value); final float get(); final void set(float value); final float getAndSet(float value); final boolean compareAndSet(float expect, float update); final boolean weakCompareAndSet(float expect, float update); final float getAndIncrement(); final float getAndDecrement(); final float getAndAdd(float delta); final float incrementAndGet(); final float decrementAndGet(); final float addAndGet(float delta); String toString(); int intValue(); long longValue(); float floatValue(); double doubleValue(); }
@Test public void testDefaultConstructor() { assertEquals(0.0,af.get(),epsilon); } @Test public void testConstructorSingleParameter() { float expected = RANDOM.nextFloat(); AtomicFloat af = new AtomicFloat(expected); assertEquals(expected,af.get(),epsilon); }
AtomicFloat extends Number implements java.io.Serializable { public final void set(float value) { _ai.set(i(value)); } AtomicFloat(); AtomicFloat(float value); final float get(); final void set(float value); final float getAndSet(float value); final boolean compareAndSet(float expect, float update); final boolean weakCompareAndSet(float expect, float update); final float getAndIncrement(); final float getAndDecrement(); final float getAndAdd(float delta); final float incrementAndGet(); final float decrementAndGet(); final float addAndGet(float delta); String toString(); int intValue(); long longValue(); float floatValue(); double doubleValue(); }
@Test public void testSet() { float expected = RANDOM.nextFloat(); af.set(expected); assertEquals(expected, af.get(),epsilon); }
AtomicFloat extends Number implements java.io.Serializable { public final float addAndGet(float delta) { for (;;) { int iexpect = _ai.get(); float expect = f(iexpect); float update = expect+delta; int iupdate = i(update); if (_ai.compareAndSet(iexpect,iupdate)) return update; } } AtomicFloat(); AtomicFloat(float value); final float get(); final void set(float value); final float getAndSet(float value); final boolean compareAndSet(float expect, float update); final boolean weakCompareAndSet(float expect, float update); final float getAndIncrement(); final float getAndDecrement(); final float getAndAdd(float delta); final float incrementAndGet(); final float decrementAndGet(); final float addAndGet(float delta); String toString(); int intValue(); long longValue(); float floatValue(); double doubleValue(); }
@Test public void testAddAndGet() { float expected = 0.0f; float actual; for (int i=0; i<10; ++i) { float nf = RANDOM.nextFloat(); expected += nf; actual = af.addAndGet(nf); assertEquals(expected, actual,epsilon); } }
CleanFormatter extends Formatter { @Override public synchronized String format(LogRecord record) { String message = formatMessage(record); if (message == null) return null; if (message.length() == 0) return message; message = Localize.filter(message, record.getResourceBundle()); if (message.endsWith("\\")) { message = message.substring(0,message.length()-1); } else if (message.matches("^\\s*("+NL+")?$")) { } else { message = message +NL; } Level level = record.getLevel(); if (level.equals(Level.INFO)) { } else if (level.equals(Level.WARNING)) { if (!message.contains("WARNING")) { message = prependToLines(s_prefix+level+": ", message); } else { message = s_prefix+message; } } else if (level.equals(Level.SEVERE)) { message = prependToLines(level+": ", message); if (!lastLevel.equals(Level.SEVERE)) { message = s_prefix + "**** SEVERE WARNING **** ("+ record.getSourceClassName()+ "." + record.getSourceMethodName()+" "+ getTimeStamp(record.getMillis())+" "+ "#" + record.getThreadID() + ")"+NL+ message; } } else if (level.equals(Level.FINE) || level.equals(Level.FINER) || level.equals(Level.FINEST)) { String shortPackage = record.getLoggerName(); int index = shortPackage.lastIndexOf('.'); if (index>0) shortPackage = shortPackage.substring(index+1); message = prependToLines (level+" "+shortPackage+": ", message); } else { message = prependToLines (level+ " " + s_time_formatter.format(new Date()) + " "+ record.getLoggerName()+": ", message); } if (record.getThrown() != null) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); record.getThrown().printStackTrace(pw); pw.close(); message +=sw.toString(); } lastLevel = level; return message; } static void setWarningPrefix(String prefix); @Override synchronized String format(LogRecord record); static String prependToLines(String prepend, String lines); }
@Test public void testFormatter() { CleanHandler.setDefaultHandler(); Logger logger = Logger.getLogger("edu.mines.jtk.util.CleanFormatter"); CleanFormatter cf = new CleanFormatter(); String[] messages = new String[] {"one", "two", "three"}; Level[] levels = new Level[] {Level.INFO, Level.WARNING, Level.SEVERE}; String[] s = new String[3]; for (int i=0; i<messages.length; ++i) { LogRecord lr = new LogRecord(levels[i], messages[i]); lr.setSourceClassName("Class"); lr.setSourceMethodName("method"); s[i] = cf.format(lr); assertTrue(s[i].endsWith(messages[i]+NL)); logger.fine("|"+s[i]+"|"); } assertTrue(s[0].equals("one"+NL)); assertTrue(s[1].equals("WARNING: two"+NL)); assertTrue(s[2].matches("^\\*\\*\\*\\* SEVERE WARNING \\*\\*\\*\\* "+ "\\(Class.method \\d+-\\d+ #.*\\)"+NL+ "SEVERE: three"+NL+"$")); }
AtomicFloat extends Number implements java.io.Serializable { public final boolean compareAndSet(float expect, float update) { return _ai.compareAndSet(i(expect),i(update)); } AtomicFloat(); AtomicFloat(float value); final float get(); final void set(float value); final float getAndSet(float value); final boolean compareAndSet(float expect, float update); final boolean weakCompareAndSet(float expect, float update); final float getAndIncrement(); final float getAndDecrement(); final float getAndAdd(float delta); final float incrementAndGet(); final float decrementAndGet(); final float addAndGet(float delta); String toString(); int intValue(); long longValue(); float floatValue(); double doubleValue(); }
@Test public void testCompareAndSet() { af.compareAndSet(1.0f,2.0f); assertEquals(0.0f,af.get()); af.compareAndSet(0.0f,1.0f); assertEquals(1.0f,af.get()); }
AtomicFloat extends Number implements java.io.Serializable { public final boolean weakCompareAndSet(float expect, float update) { return _ai.weakCompareAndSet(i(expect),i(update)); } AtomicFloat(); AtomicFloat(float value); final float get(); final void set(float value); final float getAndSet(float value); final boolean compareAndSet(float expect, float update); final boolean weakCompareAndSet(float expect, float update); final float getAndIncrement(); final float getAndDecrement(); final float getAndAdd(float delta); final float incrementAndGet(); final float decrementAndGet(); final float addAndGet(float delta); String toString(); int intValue(); long longValue(); float floatValue(); double doubleValue(); }
@Test public void testWeakCompareAndSet() { af.weakCompareAndSet(0.0f,1.0f); assertEquals(1.0f,af.get()); }
AtomicFloat extends Number implements java.io.Serializable { public final float incrementAndGet() { return addAndGet(1.0f); } AtomicFloat(); AtomicFloat(float value); final float get(); final void set(float value); final float getAndSet(float value); final boolean compareAndSet(float expect, float update); final boolean weakCompareAndSet(float expect, float update); final float getAndIncrement(); final float getAndDecrement(); final float getAndAdd(float delta); final float incrementAndGet(); final float decrementAndGet(); final float addAndGet(float delta); String toString(); int intValue(); long longValue(); float floatValue(); double doubleValue(); }
@Test public void testIncrementAndGet() { float val; for (int i=0; i<10; ++i) { val = af.get(); assertEquals((float)(i ),val,1.0E-8); val = af.incrementAndGet(); assertEquals((float)(i+1),val,1.0E-8); val = af.get(); assertEquals((float)(i+1),val,1.0E-8); } }
AtomicFloat extends Number implements java.io.Serializable { public final float decrementAndGet() { return addAndGet(-1.0f); } AtomicFloat(); AtomicFloat(float value); final float get(); final void set(float value); final float getAndSet(float value); final boolean compareAndSet(float expect, float update); final boolean weakCompareAndSet(float expect, float update); final float getAndIncrement(); final float getAndDecrement(); final float getAndAdd(float delta); final float incrementAndGet(); final float decrementAndGet(); final float addAndGet(float delta); String toString(); int intValue(); long longValue(); float floatValue(); double doubleValue(); }
@Test public void testDecrementAndGet() { float val = 10.0f; af.set(val); for (int i=10; i>0; --i) { val = af.get(); assertEquals((float)(i ),val,1.0E-8); val = af.decrementAndGet(); assertEquals((float)(i-1),val,1.0E-8); val = af.get(); assertEquals((float)(i-1),val,1.0E-8); } }
AtomicFloat extends Number implements java.io.Serializable { public final float getAndIncrement() { return getAndAdd(1.0f); } AtomicFloat(); AtomicFloat(float value); final float get(); final void set(float value); final float getAndSet(float value); final boolean compareAndSet(float expect, float update); final boolean weakCompareAndSet(float expect, float update); final float getAndIncrement(); final float getAndDecrement(); final float getAndAdd(float delta); final float incrementAndGet(); final float decrementAndGet(); final float addAndGet(float delta); String toString(); int intValue(); long longValue(); float floatValue(); double doubleValue(); }
@Test public void testGetAndIncrement() { float val; for (int i=0; i<10; ++i) { val = af.get(); assertEquals((float)(i ),val,1.0E-8); val = af.getAndIncrement(); assertEquals((float)(i ),val,1.0E-8); val = af.get(); assertEquals((float)(i+1),val,1.0E-8); } }
AtomicFloat extends Number implements java.io.Serializable { public final float getAndDecrement() { return getAndAdd(-1.0f); } AtomicFloat(); AtomicFloat(float value); final float get(); final void set(float value); final float getAndSet(float value); final boolean compareAndSet(float expect, float update); final boolean weakCompareAndSet(float expect, float update); final float getAndIncrement(); final float getAndDecrement(); final float getAndAdd(float delta); final float incrementAndGet(); final float decrementAndGet(); final float addAndGet(float delta); String toString(); int intValue(); long longValue(); float floatValue(); double doubleValue(); }
@Test public void testGetAndDecrement() { float val = 10.0f; af.set(val); for (int i=10; i>0; --i) { val = af.get(); assertEquals((float)(i ),val,1.0E-8); val = af.getAndDecrement(); assertEquals((float)(i ),val,1.0E-8); val = af.get(); assertEquals((float)(i-1),val,1.0E-8); } }
AtomicFloat extends Number implements java.io.Serializable { public final float getAndSet(float value) { return f(_ai.getAndSet(i(value))); } AtomicFloat(); AtomicFloat(float value); final float get(); final void set(float value); final float getAndSet(float value); final boolean compareAndSet(float expect, float update); final boolean weakCompareAndSet(float expect, float update); final float getAndIncrement(); final float getAndDecrement(); final float getAndAdd(float delta); final float incrementAndGet(); final float decrementAndGet(); final float addAndGet(float delta); String toString(); int intValue(); long longValue(); float floatValue(); double doubleValue(); }
@Test public void testGetAndSet() { float expected0 = RANDOM.nextFloat(); float expected1 = RANDOM.nextFloat(); AtomicFloat af = new AtomicFloat(expected0); float actual0 = af.getAndSet(expected1); float actual1 = af.get(); assertEquals(expected0,actual0,epsilon); assertEquals(expected1,actual1,epsilon); }
AtomicDouble extends Number implements java.io.Serializable { public final double get() { return d(_al.get()); } AtomicDouble(); AtomicDouble(double value); final double get(); final void set(double value); final double getAndSet(double value); final boolean compareAndSet(double expect, double update); final boolean weakCompareAndSet(double expect, double update); final double getAndIncrement(); final double getAndDecrement(); final double getAndAdd(double delta); final double incrementAndGet(); final double decrementAndGet(); final double addAndGet(double delta); String toString(); int intValue(); long longValue(); float floatValue(); double doubleValue(); }
@Test public void testDefaultConstructor() { assertEquals(0.0,ad.get(),epsilon); } @Test public void testConstructorSingleParameter() { double expected = RANDOM.nextDouble(); AtomicDouble ad = new AtomicDouble(expected); assertEquals(expected,ad.get(),epsilon); }
AtomicDouble extends Number implements java.io.Serializable { public final void set(double value) { _al.set(l(value)); } AtomicDouble(); AtomicDouble(double value); final double get(); final void set(double value); final double getAndSet(double value); final boolean compareAndSet(double expect, double update); final boolean weakCompareAndSet(double expect, double update); final double getAndIncrement(); final double getAndDecrement(); final double getAndAdd(double delta); final double incrementAndGet(); final double decrementAndGet(); final double addAndGet(double delta); String toString(); int intValue(); long longValue(); float floatValue(); double doubleValue(); }
@Test public void testSet() { double expected = RANDOM.nextDouble(); ad.set(expected); assertEquals(expected, ad.get(),epsilon); }