Example usage for java.util.concurrent.atomic AtomicInteger getAndIncrement

List of usage examples for java.util.concurrent.atomic AtomicInteger getAndIncrement

Introduction

In this page you can find the example usage for java.util.concurrent.atomic AtomicInteger getAndIncrement.

Prototype

public final int getAndIncrement() 

Source Link

Document

Atomically increments the current value, with memory effects as specified by VarHandle#getAndAdd .

Usage

From source file:com.github.naoghuman.testdata.abclist.service.LinkMappingService.java

@Override
protected Task<Void> createTask() {
    return new Task<Void>() {
        {/*w ww .  j a  va  2 s .c o m*/
            updateProgress(0, saveMaxEntities);
        }

        @Override
        protected Void call() throws Exception {
            LoggerFacade.getDefault().deactivate(Boolean.TRUE);

            final StopWatch stopWatch = new StopWatch();
            stopWatch.start();

            /*
             1) over all links
             2) if random > 0.005d then do
             3) otherwise create a link without parent
             4) get 1-10 terms, create LinkMapping foreach of them
             - means a link is mapped to 1-10 terms
             5) get 0-10 topics, create LinkMapping foreach of them
             - means a link is mapped to 0-10 topics
            */

            final ObservableList<Link> links = SqlProvider.getDefault().findAllLinks();
            final ObservableList<Term> terms = SqlProvider.getDefault().findAllTerms();
            final int sizeTerms = terms.size();
            final ObservableList<Topic> topics = SqlProvider.getDefault().findAllTopics();
            final int sizeTopics = topics.size();
            final AtomicInteger index = new AtomicInteger(0);

            final CrudService crudService = DatabaseFacade.getDefault().getCrudService(entityName);
            final AtomicLong id = new AtomicLong(
                    -1_000_000_000L + DatabaseFacade.getDefault().getCrudService().count(entityName));
            links.stream() // 1
                    .forEach(link -> {
                        // 2) Should the [Link] have a parent
                        final double random = TestdataGenerator.RANDOM.nextDouble();
                        if (random > 0.005d) {
                            // 4) Create [Link]s with parent [Term]
                            final int maxTerms = TestdataGenerator.RANDOM.nextInt(10) + 1;
                            for (int i = 0; i < maxTerms; i++) {
                                final LinkMapping lm = ModelProvider.getDefault().getLinkMapping();
                                lm.setId(id.getAndIncrement());

                                final Term term = terms.get(TestdataGenerator.RANDOM.nextInt(sizeTerms));
                                lm.setParentId(term.getId());
                                lm.setParentType(LinkMappingType.TERM);

                                lm.setChildId(link.getId());
                                lm.setChildType(LinkMappingType.LINK);

                                crudService.create(lm);
                            }

                            // 5) Create [Link]s with parent [Topic]
                            final int maxTopics = TestdataGenerator.RANDOM.nextInt(11);
                            for (int i = 0; i < maxTopics; i++) {
                                final LinkMapping lm = ModelProvider.getDefault().getLinkMapping();
                                lm.setId(id.getAndIncrement());

                                final Topic topic = topics.get(TestdataGenerator.RANDOM.nextInt(sizeTopics));
                                lm.setParentId(topic.getId());
                                lm.setParentType(LinkMappingType.TOPIC);

                                lm.setChildId(link.getId());
                                lm.setChildType(LinkMappingType.LINK);

                                crudService.create(lm);
                            }
                        } else {
                            // 3) Some [Link]s havn't a parent
                            final LinkMapping lm = ModelProvider.getDefault().getLinkMapping();
                            lm.setId(id.getAndIncrement());
                            lm.setParentId(IDefaultConfiguration.DEFAULT_ID);
                            lm.setParentType(LinkMappingType.NOT_DEFINED);
                            lm.setChildId(link.getId());
                            lm.setChildType(LinkMappingType.LINK);

                            crudService.create(lm);
                        }

                        updateProgress(index.getAndIncrement(), saveMaxEntities);
                    });

            LoggerFacade.getDefault().deactivate(Boolean.FALSE);
            stopWatch.split();
            LoggerFacade.getDefault().debug(this.getClass(),
                    "  + " + stopWatch.toSplitString() + " for " + saveMaxEntities + " LinkMappings."); // NOI18N
            stopWatch.stop();

            return null;
        }
    };
}

From source file:org.neo4j.io.pagecache.PageCacheTest.java

@Test
public void pagedFileFlushAndForceMustQueryTheGivenIOPSLimiter() throws Exception {
    int pagesToDirty = 10_000;
    PageCache cache = getPageCache(fs, nextPowerOf2(pagesToDirty), pageCachePageSize, PageCacheTracer.NULL);
    PagedFile pf = cache.map(file("a"), filePageSize);

    // Dirty a bunch of data
    dirtyManyPages(pf, pagesToDirty);/*from   w w w. java  2 s. c o m*/

    AtomicInteger callbackCounter = new AtomicInteger();
    AtomicInteger ioCounter = new AtomicInteger();
    pf.flushAndForce((previousStamp, recentlyCompletedIOs, swapper) -> {
        ioCounter.addAndGet(recentlyCompletedIOs);
        return callbackCounter.getAndIncrement();
    });
    pf.close();

    assertThat(callbackCounter.get(), greaterThan(0));
    assertThat(ioCounter.get(), greaterThanOrEqualTo(pagesToDirty - 30)); // -30 because of the eviction thread
}

From source file:org.neo4j.io.pagecache.PageCacheTest.java

@Test
public void pageCacheFlushAndForceMustQueryTheGivenIOPSLimiter() throws Exception {
    int pagesToDirty = 10_000;
    PageCache cache = getPageCache(fs, nextPowerOf2(2 * pagesToDirty), pageCachePageSize, PageCacheTracer.NULL);
    PagedFile pfA = cache.map(existingFile("a"), filePageSize);
    PagedFile pfB = cache.map(existingFile("b"), filePageSize);

    dirtyManyPages(pfA, pagesToDirty);/*from  www .  jav a  2s  .  co m*/
    dirtyManyPages(pfB, pagesToDirty);

    AtomicInteger callbackCounter = new AtomicInteger();
    AtomicInteger ioCounter = new AtomicInteger();
    cache.flushAndForce((previousStamp, recentlyCompletedIOs, swapper) -> {
        ioCounter.addAndGet(recentlyCompletedIOs);
        return callbackCounter.getAndIncrement();
    });
    pfA.close();
    pfB.close();

    assertThat(callbackCounter.get(), greaterThan(0));
    assertThat(ioCounter.get(), greaterThanOrEqualTo(pagesToDirty * 2 - 30)); // -30 because of the eviction thread
}

From source file:org.neo4j.io.pagecache.PageCacheTest.java

private PageSwapperFactory factoryCountingSyncDevice(final AtomicInteger syncDeviceCounter,
        final Queue<Integer> expectedCountsInForce) {
    SingleFilePageSwapperFactory factory = new SingleFilePageSwapperFactory() {
        @Override/* ww w. j  a  va  2 s. co  m*/
        public void syncDevice() {
            super.syncDevice();
            syncDeviceCounter.getAndIncrement();
        }

        @Override
        public PageSwapper createPageSwapper(File file, int filePageSize, PageEvictionCallback onEviction,
                boolean createIfNotExist) throws IOException {
            PageSwapper delegate = super.createPageSwapper(file, filePageSize, onEviction, createIfNotExist);
            return new DelegatingPageSwapper(delegate) {
                @Override
                public void force() throws IOException {
                    super.force();
                    assertThat(syncDeviceCounter.get(), is(expectedCountsInForce.poll()));
                }
            };
        }
    };
    factory.setFileSystemAbstraction(fs);
    return factory;
}

From source file:org.neo4j.io.pagecache.PageCacheTest.java

private DelegatingFileSystemAbstraction writeAndForceCountingFs(final AtomicInteger writeCounter,
        final AtomicInteger forceCounter) {
    return new DelegatingFileSystemAbstraction(fs) {
        @Override//  www. ja v a 2 s .  co  m
        public StoreChannel open(File fileName, String mode) throws IOException {
            return new DelegatingStoreChannel(super.open(fileName, mode)) {
                @Override
                public void writeAll(ByteBuffer src, long position) throws IOException {
                    writeCounter.getAndIncrement();
                    super.writeAll(src, position);
                }

                @Override
                public void force(boolean metaData) throws IOException {
                    forceCounter.getAndIncrement();
                    super.force(metaData);
                }
            };
        }
    };
}

From source file:it.unibo.alchemist.language.protelis.util.ProtelisLoader.java

private static <T> AnnotatedTree<?> parseExpression(final Expression e,
        final Map<FasterString, FunctionDefinition> nameToFun,
        final Map<FunctionDef, FunctionDefinition> funToFun, final AtomicInteger id) {
    if (e instanceof DoubleVal) {
        return new NumericConstant(((DoubleVal) e).getVal());
    }/*from   w  ww .  j ava  2 s.c o m*/
    if (e instanceof StringVal) {
        return new Constant<>(((StringVal) e).getVal());
    }
    if (e instanceof BooleanVal) {
        return new Constant<>(((BooleanVal) e).isVal());
    }
    if (e instanceof TupleVal) {
        final List<Expression> expr = extractArgs((TupleVal) e);
        List<AnnotatedTree<?>> list = new ArrayList<>();
        for (Expression exp : expr) {
            list.add(parseExpression(exp, nameToFun, funToFun, id));
        }
        final AnnotatedTree<?>[] args = new AnnotatedTree<?>[list.size()];
        int i = 0;
        for (AnnotatedTree<?> t : list) {
            args[i++] = t;
        }
        return new CreateTuple(args);
    }
    if (e instanceof VAR) {
        return new Variable(((VAR) e).getName());
    }
    if (e == null) {
        throw new IllegalArgumentException("null expression, this is a bug.");
    }
    final EObject eRef = e.getReference();
    if (eRef != null) {
        /*
         * Function or method call
         */
        if (eRef instanceof JvmOperation) {
            final JvmOperation m = (JvmOperation) eRef;
            return parseMethod(m, extractArgs(e), nameToFun, funToFun, id);
        } else if (eRef instanceof FunctionDef) {
            final FunctionDef fun = (FunctionDef) eRef;
            return parseFunction(fun, extractArgs(e), nameToFun, funToFun, id);
        } else {
            throw new IllegalStateException("I do not know how I should interpret a call to a "
                    + eRef.getClass().getSimpleName() + " object.");
        }
    }
    final String name = e.getName();
    if (name == null) {
        /*
         * Envelope: recurse in
         */
        final EObject val = e.getV();
        return parseExpression((Expression) val, nameToFun, funToFun, id);
    }
    if (BINARY_OPERATORS.contains(name) && e.getLeft() != null && e.getRight() != null) {
        return new BinaryOp(name, parseExpression(e.getLeft(), nameToFun, funToFun, id),
                parseExpression(e.getRight(), nameToFun, funToFun, id));
    }
    if (UNARY_OPERATORS.contains(name) && e.getLeft() == null && e.getRight() != null) {
        return new UnaryOp(name, parseExpression(e.getRight(), nameToFun, funToFun, id));
    }
    if (name.equals(REP_NAME)) {
        final RepInitialize ri = e.getInit().getArgs().get(0);
        final String x = ri.getX().getName();
        return new RepCall<>(new FasterString(x), parseExpression(ri.getW(), nameToFun, funToFun, id),
                parseBlock(e.getBody(), nameToFun, funToFun, id));
    }
    if (name.equals(IF_NAME)) {
        @SuppressWarnings(UNCHECKED)
        final AnnotatedTree<Boolean> cond = (AnnotatedTree<Boolean>) parseExpression(e.getCond(), nameToFun,
                funToFun, id);
        @SuppressWarnings(UNCHECKED)
        final AnnotatedTree<T> then = (AnnotatedTree<T>) parseBlock(e.getThen(), nameToFun, funToFun, id);
        @SuppressWarnings(UNCHECKED)
        final AnnotatedTree<T> elze = (AnnotatedTree<T>) parseBlock(e.getElse(), nameToFun, funToFun, id);
        return new If<>(cond, then, elze);
    }
    if (name.equals(PI_NAME)) {
        return new Constant<>(Math.PI);
    }
    if (name.equals(E_NAME)) {
        return new Constant<>(Math.E);
    }
    if (name.equals(RAND_NAME)) {
        return new Random();
    }
    if (name.equals(DT_NAME)) {
        return new Dt();
    }
    if (name.equals(SELF_NAME)) {
        return new Self();
    }
    if (name.equals(NBR_NAME)) {
        return new NBRCall(parseExpression(e.getArg(), nameToFun, funToFun, id));
    }
    if (name.equals(ALIGNED_MAP)) {
        @SuppressWarnings(UNCHECKED)
        final AnnotatedTree<Field> arg = (AnnotatedTree<Field>) parseExpression(e.getArg(), nameToFun, funToFun,
                id);
        @SuppressWarnings(UNCHECKED)
        final AnnotatedTree<FunctionDefinition> cond = (AnnotatedTree<FunctionDefinition>) parseExpression(
                e.getCond(), nameToFun, funToFun, id);
        @SuppressWarnings(UNCHECKED)
        final AnnotatedTree<FunctionDefinition> op = (AnnotatedTree<FunctionDefinition>) parseExpression(
                e.getOp(), nameToFun, funToFun, id);
        final AnnotatedTree<?> def = parseExpression(e.getDefault(), nameToFun, funToFun, id);
        return new AlignedMap(arg, cond, op, def);
    }
    if (name.equals(LAMBDA_NAME)) {
        final FunctionDefinition lambda = new FunctionDefinition("l$" + id.getAndIncrement(),
                extractArgsFromLambda(e));
        final AnnotatedTree<?> body = parseBlock(e.getBody(), nameToFun, funToFun, id);
        lambda.setBody(body);
        return new Constant<>(lambda);
    }
    if (name.equals(NBR_RANGE)) {
        return new NBRRange();
    }
    if (name.equals(EVAL_NAME)) {
        final AnnotatedTree<?> arg = parseExpression(e.getArg(), nameToFun, funToFun, id);
        return new Eval(arg);
    }
    if (name.equals(DOT_NAME)) {
        final AnnotatedTree<?> target = parseExpression(e.getLeft(), nameToFun, funToFun, id);
        final List<AnnotatedTree<?>> args = parseArgs(extractArgs(e), nameToFun, funToFun, id);
        return new DotOperator(e.getMethodName(), target, args);
    }
    if (name.equals(MUX_NAME)) {
        final AnnotatedTree<?> cond = parseExpression(e.getCond(), nameToFun, funToFun, id);
        final AnnotatedTree<?> then = parseBlock(e.getThen(), nameToFun, funToFun, id);
        final AnnotatedTree<?> elze = parseBlock(e.getElse(), nameToFun, funToFun, id);
        return new TernaryOp(MUX_NAME, cond, then, elze);
    }
    if (name.endsWith(HOOD_END)) {
        final String op = name.replace(HOOD_END, "");
        final HoodOp hop = HoodOp.get(op);
        if (hop == null) {
            throw new UnsupportedOperationException("Unsupported hood operation: " + op);
        }
        @SuppressWarnings(UNCHECKED)
        final AnnotatedTree<Field> arg = (AnnotatedTree<Field>) parseExpression(e.getArg(), nameToFun, funToFun,
                id);
        return new HoodCall(arg, hop, e.isInclusive());
    }
    throw new UnsupportedOperationException(
            "Unsupported operation: " + (e.getName() != null ? e.getName() : "Unknown"));
}

From source file:com.appdynamics.analytics.processor.event.ElasticSearchEventService.java

public void bulkUpdateEventType(final int requestVersion, String eventType, final String body)
/*      */ {/*  w w  w  . j  av a 2s. c o  m*/
    /*  358 */ final String finalEventType = this.indexNameResolver.resolveEventType(eventType);
    /*  359 */ List<String> accountNames = getAllAccountNamesForEventType(eventType);
    /*  360 */ log.info(
            "Performing bulk update for event type [{}] - will update a total of [{}] accounts with mappings [{}]",
            new Object[] { eventType, Integer.valueOf(accountNames.size()), body });
    /*      */
    /*      */
    /*      */
    /*  364 */ int numberOfRetries = 3;
    /*      */
    /*      */
    /*  367 */ int maxAllowedFailures = 100;
    /*  368 */ final AtomicInteger totalFailures = new AtomicInteger(0);
    /*      */
    /*      */
    /*      */
    /*  372 */ ExecutorService batchProcessors = Executors.newFixedThreadPool(5);
    /*  373 */ List<Future<Exception>> batches = new ArrayList();
    /*  374 */ for (final String accountName : accountNames) {
        /*  375 */ batches.add(batchProcessors.submit(new Callable()
        /*      */ {
            /*      */ public Exception call() throws Exception {
                /*  378 */ for (int i = 1; i <= 3; i++) {
                    /*      */ try {
                        /*  380 */ ElasticSearchEventService.log
                                .info("Updating account [{}] and event type [{}]");
                        /*  381 */ ElasticSearchEventService.this.updateEventType(requestVersion, accountName,
                                finalEventType, body);
                        /*      */ }
                    /*      */ catch (EventTypeMissingException | IndexMissingException
                            | TypeMissingException e) {
                        /*  384 */ ElasticSearchEventService.log.info(
                                "While performing bulk update for event [{}] and account [{}], event type was not found - probably means there was no index with the corresponding mapping data. Actual error [{}]",
                                new Object[] { finalEventType, accountName, e.getMessage() });
                        /*      */
                        /*      */ }
                    /*      */ catch (Exception e)
                    /*      */ {
                        /*      */
                        /*  390 */ if ((e.getCause() instanceof MergeMappingException)) {
                            /*  391 */ ElasticSearchEventService.log.info(
                                    "Standard update failed due to merge mapping exception, forcing rollover for account [{}] and event type [{}]",
                                    accountName, finalEventType);
                            /*      */
                            /*      */
                            /*  394 */ ElasticSearchEventService.this.forceRollover(accountName, finalEventType,
                                    body);
                            /*      */ } else {
                            /*  396 */ ElasticSearchEventService.log.error(
                                    "Bulk update for account [{}] and event type [{}] failed with exception [{}] - sleeping and retrying - try {} of {}",
                                    new Object[] { accountName, finalEventType, e.getMessage(),
                                            Integer.valueOf(i), Integer.valueOf(3) });
                            /*      */
                            /*      */
                            /*      */
                            /*  400 */ if ((totalFailures.getAndIncrement() > 100) || (i == 3)) {
                                /*  401 */ return e;
                                /*      */ }
                            /*  403 */ ConcurrencyHelper.sleep(1000 * i);
                            /*      */ }
                        /*      */ }
                    /*      */ }
                /*  407 */ return null;
                /*      */ }
            /*      */ }));
        /*      */ }
    /*      */
    /*  412 */ for (Future<Exception> batch : batches) {
        /*  413 */ Exception e = (Exception) ConcurrencyHelper.getOrCancel(batch, 300, log);
        /*  414 */ if (e != null) {
            /*  415 */ throw Throwables.propagate(e);
            /*      */ }
        /*      */ }
    /*      */
    /*  419 */ ConcurrencyHelper.stop(batchProcessors, log);
    /*      */ }

From source file:org.jboss.pnc.pvt.execution.JenkinsExecutor.java

private void startMonitor(String jobName, int buildNumber, final JenkinsExecution execution,
        final CallBack callBack) {
    AtomicInteger statusRetrieveFailed = new AtomicInteger(0);
    final Runnable checking = new Runnable() {

        @Override// www  .j ava2s. c  om
        public void run() {
            long start = System.currentTimeMillis();

            try {
                Build jenkinsBuild = getBuild(jobName, buildNumber);
                if (jenkinsBuild == null) {
                    getMonitorExecutorService().schedule(this, getMonitorInterval(), TimeUnit.SECONDS);
                    return;
                }

                BuildWithDetails jenkinsBuildDetails = jenkinsBuild.details();
                String log = jenkinsBuildDetails.getConsoleOutputText();
                if (log != null) {
                    execution.getReport().setMainLog(log);
                    if (callBack != null) {
                        callBack.onLogChanged(execution);
                    }
                }
                BuildResult result = jenkinsBuildDetails.getResult();
                long timeout = jenkinsConfig.getJobTimeOut();
                if (timeout > 0) {
                    long end = System.currentTimeMillis();
                    if (end - start >= timeout) {
                        throw new RuntimeException("Timeout to check build status of Jenkins job: " + jobName);
                    }
                }
                if (result == null) {
                    getMonitorExecutorService().schedule(this, getMonitorInterval(), TimeUnit.SECONDS);
                    return;
                }
                switch (result) {
                case BUILDING:
                case REBUILDING: {
                    execution.setStatus(Execution.Status.RUNNING);
                    if (callBack != null) {
                        callBack.onStatus(execution);
                    }
                    getMonitorExecutorService().schedule(this, getMonitorInterval(), TimeUnit.SECONDS);
                    break;
                }
                case FAILURE:
                case UNSTABLE:
                case ABORTED: {
                    execution.setStatus(Execution.Status.FAILED);
                    List<Artifact> artiFacts = jenkinsBuildDetails.getArtifacts();
                    if (artiFacts != null && artiFacts.size() > 0) {
                        for (Artifact arti : artiFacts) {
                            String logFilePattern = execution.getLogFilePattern();
                            if (logFilePattern != null && logFilePattern.trim().length() > 0) {
                                if (arti.getRelativePath().matches(logFilePattern) == false) {
                                    continue;
                                }
                            }
                            try (InputStream input = jenkinsBuildDetails.downloadArtifact(arti)) {
                                String artiLog = IOUtils.toString(input);
                                ReportLog reportLog = new ReportLog(arti.getFileName(), artiLog);
                                execution.getReport().addReportLog(reportLog);
                            }
                        }
                        if (callBack != null) {
                            callBack.onLogChanged(execution);
                        }
                    }
                    if (callBack != null) {
                        callBack.onStatus(execution);
                        callBack.onTerminated(execution);
                    }
                    break;
                }
                case SUCCESS: {
                    execution.setStatus(Execution.Status.SUCCEEDED);
                    List<Artifact> artiFacts = jenkinsBuildDetails.getArtifacts();
                    if (artiFacts != null && artiFacts.size() > 0) {
                        for (Artifact arti : artiFacts) {
                            String logFilePattern = execution.getLogFilePattern();
                            if (logFilePattern != null && logFilePattern.trim().length() > 0) {
                                if (arti.getRelativePath().matches(logFilePattern) == false) {
                                    continue;
                                }
                            }
                            try (InputStream input = jenkinsBuildDetails.downloadArtifact(arti)) {
                                String artiLog = IOUtils.toString(input);
                                ReportLog reportLog = new ReportLog(arti.getFileName(), artiLog);
                                execution.getReport().addReportLog(reportLog);
                            }
                        }
                        if (callBack != null) {
                            callBack.onLogChanged(execution);
                        }
                    }
                    if (callBack != null) {
                        callBack.onStatus(execution);
                        callBack.onTerminated(execution);
                    }
                    break;
                }
                default: {
                    execution.setStatus(Execution.Status.UNKNOWN);
                    if (callBack != null) {
                        callBack.onStatus(execution);
                    }
                    getMonitorExecutorService().schedule(this, getMonitorInterval(), TimeUnit.SECONDS);
                    break;
                }
                }
            } catch (IOException e) {
                execution.setException(e);
                if (callBack != null) {
                    callBack.onException(execution);
                }
                int failed = statusRetrieveFailed.getAndIncrement();
                if (failed >= getMaxRetryTime()) {
                    logger.error("Failed to check Build Detail. Give up!", e);
                    if (callBack != null) {
                        callBack.onTerminated(execution);
                    }
                } else {
                    logger.warn("Failed to check Build Detail. Continue.", e);
                    getMonitorExecutorService().schedule(this, getMonitorInterval(), TimeUnit.SECONDS);
                }
            } catch (Throwable t) {
                logger.error("Failed to Monitor the execution.", t);
                if (callBack != null) {
                    callBack.onTerminated(execution);
                }
            }
        }

    };
    getMonitorExecutorService().schedule(checking, getMonitorInterval(), TimeUnit.SECONDS);
}

From source file:FocusingField.java

License:asdf

public LMAArrays calculateJacobianArraysMulti(double[] fX) {
    // calculate JtJ
    final double[] diff = calcYminusFx(fX);
    final int numPars = this.jacobian.length; // number of parameters to be adjusted
    //       int length=diff.length; // should be the same as this.jacobian[0].length
    final double[][] JtByJmod = new double[numPars][numPars]; //Transposed Jacobian multiplied by Jacobian
    final double[] JtByDiff = new double[numPars];

    final double[] fWeights = this.dataWeights;
    //       final double [][] fJacobian=this.jacobian;
    final AtomicInteger lineAtomic = new AtomicInteger(0);
    final Thread[] threads = newThreadArray(threadsMax);

    for (int ithread = 0; ithread < threads.length; ithread++) {
        threads[ithread] = new Thread() {
            public void run() {
                for (int line = lineAtomic.getAndIncrement(); line < numPars; line = lineAtomic
                        .getAndIncrement()) {
                    double[] sLine = jacobian[line];
                    if (fWeights != null) {
                        sLine = jacobian[line].clone();
                        for (int i = 0; i < sLine.length; i++)
                            sLine[i] *= fWeights[i];
                    }//w w  w . j ava2s .  com
                    for (int line2 = line; line2 < numPars; line2++) {
                        double d = 0;
                        for (int i = 0; i < sLine.length; i++)
                            if (sLine[i] != 0.0) {
                                d += sLine[i] * jacobian[line2][i];
                            }
                        JtByJmod[line][line2] = d;
                    }
                    double d = 0;
                    for (int i = 0; i < sLine.length; i++)
                        if (sLine[i] != 0.0) {
                            d += sLine[i] * diff[i];
                        }
                    JtByDiff[line] = d;
                }
            } // public void run() {
        };
    }
    startAndJoin(threads);
    /*         
           for (int i=0;i<numPars;i++) for (int j=i;j<numPars;j++){
              JtByJmod[i][j]=0.0;
              if (this.dataWeights!=null)
     for (int k=0;k<length;k++) JtByJmod[i][j]+=this.jacobian[i][k]*this.jacobian[j][k]*this.dataWeights[k];
              else
     for (int k=0;k<length;k++) JtByJmod[i][j]+=this.jacobian[i][k]*this.jacobian[j][k];
           }
    */
    for (int i = 0; i < numPars; i++) { // subtract lambda*diagonal , fill the symmetrical half below the diagonal
        for (int j = 0; j < i; j++)
            JtByJmod[i][j] = JtByJmod[j][i]; // it is symmetrical matrix, just copy
    }
    /*       
           for (int i=0;i<numPars;i++) {
              JtByDiff[i]=0.0;
              if (this.dataWeights!=null)
     for (int k=0;k<length;k++) JtByDiff[i]+=this.jacobian[i][k]*diff[k]*this.dataWeights[k];
              else
     for (int k=0;k<length;k++) JtByDiff[i]+=this.jacobian[i][k]*diff[k];
            
           }
    */
    LMAArrays lMAArrays = new LMAArrays();
    lMAArrays.jTByJ = JtByJmod;
    lMAArrays.jTByDiff = JtByDiff;
    return lMAArrays;
}

From source file:FocusingField.java

License:asdf

public double[] createFXandJacobianMulti(final boolean createJacobian) {
    long startTime = System.nanoTime();
    //   final int [] zTxTyMode=fieldFitting.mechanicalFocusingModel.getZTxTyMode();
    final boolean useZTxTy = fieldFitting.mechanicalFocusingModel.getZTxTyMode() != null;
    int numCorrPar = fieldFitting.getNumberOfCorrParameters();
    boolean[] selChannels = fieldFitting.getSelectedChannels();
    final int[] selChanIndices = new int[selChannels.length];
    selChanIndices[0] = 0;/*from w ww.j  a va 2  s  .c  o m*/
    for (int i = 1; i < selChanIndices.length; i++) {
        selChanIndices[i] = selChanIndices[i - 1] + (selChannels[i - 1] ? 1 : 0);
    }
    //   if (zTxTyMode!=null) {
    //      fieldFitting.commitParameterVectorZTxTy(vector);
    //      return;
    //   }

    final int numPars = fieldFitting.getNumberOfParameters(sagittalMaster);
    int numRegPars = fieldFitting.getNumberOfRegularParameters(sagittalMaster);

    final int numSelChn = fieldFitting.getNumberOfChannels();
    final Thread[] threads = newThreadArray(threadsMax);
    final ArrayList<ArrayList<PartialFXJac>> fxList = new ArrayList<ArrayList<PartialFXJac>>();
    for (int ithread = 0; ithread < threads.length; ithread++) {
        fxList.add(new ArrayList<PartialFXJac>());
    }
    // create list of indices of measurements corresponding to new timestamp/sample (up to 6 increment)
    final ArrayList<Integer> measIndicesList = getSetSampleIndices(); // uses dataVector; 
    /*   String prevTimeStamp="";
       double prevPx=-1,prevPy=-1;
            
       final ArrayList<Integer> measIndicesList = new ArrayList<Integer>(dataVector.length/getNumChannels());
       for (int n=0;n<dataVector.length;n++){
          MeasuredSample ms=dataVector[n];
          if (!ms.timestamp.equals(prevTimeStamp) || (ms.px!=prevPx) || (ms.py!=prevPy)){
             measIndicesList.add(new Integer(n));
          }
       }
    */
    final AtomicInteger measIndex = new AtomicInteger(0);
    final AtomicInteger threadIndexAtomic = new AtomicInteger(0);
    final boolean[] centerSelect = correct_measurement_ST ? fieldFitting.getCenterSelect() : null; //falseFalse;
    for (int ithread = 0; ithread < threads.length; ithread++) {

        threads[ithread] = new Thread() {
            public void run() {
                int threadIndex = threadIndexAtomic.getAndIncrement();
                fxList.get(threadIndex).clear(); // not needed
                double[][] derivs;
                double[] blankPars = null;
                if (useZTxTy) {
                    if (createJacobian) {
                        blankPars = new double[numPars];
                        for (int i = 0; i < numPars; i++)
                            blankPars[i] = 0.0;
                    }
                }
                for (int startMeasIndex = measIndex.getAndIncrement(); startMeasIndex < measIndicesList
                        .size(); startMeasIndex = measIndex.getAndIncrement()) {
                    int startMeas = measIndicesList.get(startMeasIndex);
                    int endMeas = (startMeasIndex == (measIndicesList.size() - 1)) ? dataVector.length
                            : measIndicesList.get(startMeasIndex + 1);
                    MeasuredSample ms = dataVector[startMeas];
                    derivs = createJacobian ? (new double[numSelChn][]) : null;
                    double[] subData;
                    if (useZTxTy) {
                        subData = fieldFitting.getValsDerivativesZTxTy(ms.measurementIndex, //-1, // <0 - use mechanicalFocusingModel z, tx, ty
                                ms.sampleIndex, ms.motors, // 3 motor coordinates
                                ms.px, // pixel x
                                ms.py, // pixel y
                                derivs);
                        for (int n = startMeas; n < endMeas; n++) {
                            ms = dataVector[n];
                            int chn = selChanIndices[ms.channel];
                            double[] zTxTyDerivs = null;
                            if (createJacobian && (derivs[chn] != null)) {
                                zTxTyDerivs = blankPars.clone();
                                for (int i = 0; i < derivs[chn].length; i++) {
                                    int parIndex = fieldFitting.getZTMap(ms.measurementIndex, i); //n);
                                    if (parIndex >= 0)
                                        zTxTyDerivs[parIndex] = derivs[chn][i];
                                }
                            }
                            PartialFXJac partialFXJac = new PartialFXJac(n, subData[chn], zTxTyDerivs); // createJacobian?derivs[chn]:null);
                            fxList.get(threadIndex).add(partialFXJac);
                        }
                    } else {
                        subData = fieldFitting.getValsDerivatives(
                                //                     ms.measurementIndex, //-1, // <0 - use mechanicalFocusingModel z, tx, ty
                                ms.sampleIndex, sagittalMaster, ms.motors, // 3 motor coordinates
                                ms.px, // pixel x
                                ms.py, // pixel y
                                derivs);
                        for (int n = startMeas; n < endMeas; n++) {
                            ms = dataVector[n];
                            int chn = selChanIndices[ms.channel];
                            if (createJacobian && (centerSelect != null)) {
                                int np = 0;
                                for (int i = 0; i < 2; i++)
                                    if (centerSelect[i]) {
                                        derivs[chn][np++] -= ms.dPxyc[i]; // subtract, as effect is opposite to fX
                                    }
                            }
                            PartialFXJac partialFXJac = new PartialFXJac(n, subData[chn],
                                    createJacobian ? derivs[chn] : null);
                            fxList.get(threadIndex).add(partialFXJac);
                        }
                    }

                }

            }
        };
    }
    startAndJoin(threads);
    if (debugLevel > 1)
        System.out.println("#1 @ " + IJ.d2s(0.000000001 * (System.nanoTime() - startTime), 5));
    //   Combibe results
    double[] fx = new double[dataVector.length + numCorrPar];
    if (createJacobian) {
        jacobian = new double[numPars][dataVector.length + numCorrPar];
        for (double[] row : jacobian)
            Arrays.fill(row, 0.0);
    }

    for (ArrayList<PartialFXJac> partilaList : fxList) {
        for (PartialFXJac partialFXJac : partilaList) {
            int n = partialFXJac.index;
            fx[n] = partialFXJac.f;
            if (createJacobian) {
                for (int i = 0; i < numPars; i++) {
                    jacobian[i][n] = partialFXJac.jac[i];
                }
            }
        }
    }
    if (debugLevel > 1)
        System.out.println("#2 @ " + IJ.d2s(0.000000001 * (System.nanoTime() - startTime), 5));
    if (createJacobian && !useZTxTy && (fieldFitting.sampleCorrChnParIndex != null)) {
        // add mutual dependence of correction parameters. first - values (fx)
        int index = dataVector.length; // add to the end of vector
        int numSamples = getNumSamples();
        for (int chn = 0; chn < fieldFitting.sampleCorrChnParIndex.length; chn++)
            if (fieldFitting.sampleCorrChnParIndex[chn] != null) {
                for (int np = 0; np < fieldFitting.sampleCorrChnParIndex[chn].length; np++) {
                    int pindex = fieldFitting.sampleCorrChnParIndex[chn][np];
                    if (pindex >= 0) {
                        for (int i = 0; i < numSamples; i++) {
                            double f = 0.0;
                            for (int j = 0; j < numSamples; j++) {
                                f += fieldFitting.sampleCorrVector[pindex + j]
                                        * fieldFitting.sampleCorrCrossWeights[chn][np][i][j];
                            }
                            fx[index] = f;
                            //                                 f+=fieldFitting.sampleCorrVector[pindex+i]
                            if (createJacobian) {
                                for (int j = 0; j < numSamples; j++) {
                                    jacobian[numRegPars + pindex
                                            + j][index] = fieldFitting.sampleCorrCrossWeights[chn][np][i][j];
                                }
                            }
                            index++;
                        }
                    }
                }
            }
    }
    if (debugLevel > 1)
        System.out.println("#3 @ " + IJ.d2s(0.000000001 * (System.nanoTime() - startTime), 5));
    if (createJacobian && (debugLevel > 1)) {
        if (debugPoint >= 0)
            debugJacobianPoint(debugPoint);
        if (debugParameter >= 0)
            debugJacobianParameter(debugParameter);
    }
    if (debugLevel > 1)
        System.out.println("#4 @ " + IJ.d2s(0.000000001 * (System.nanoTime() - startTime), 5));
    return fx;

}