List of usage examples for java.util Collections synchronizedList
public static <T> List<T> synchronizedList(List<T> list)
From source file:org.hawkular.metrics.core.service.MetricsServiceITest.java
@Test public void shouldReceiveInsertedDataNotifications() throws Exception { String tenantId = "shouldReceiveInsertedDataNotifications"; ImmutableList<MetricType<?>> metricTypes = ImmutableList.of(GAUGE, COUNTER, AVAILABILITY); AvailabilityType[] availabilityTypes = AvailabilityType.values(); int numberOfPoints = 10; List<Metric<?>> actual = Collections.synchronizedList(new ArrayList<>()); CountDownLatch latch = new CountDownLatch(metricTypes.size() * numberOfPoints); metricsService.insertedDataEvents().filter(metric -> metric.getMetricId().getTenantId().equals(tenantId)) .subscribe(metric -> {//from w w w . j av a 2 s .co m actual.add(metric); latch.countDown(); }); List<Metric<?>> expected = new ArrayList<>(); for (MetricType<?> metricType : metricTypes) { for (int i = 0; i < numberOfPoints; i++) { if (metricType == GAUGE) { DataPoint<Double> dataPoint = new DataPoint<>((long) i, (double) i); MetricId<Double> metricId = new MetricId<>(tenantId, GAUGE, "gauge"); Metric<Double> metric = new Metric<>(metricId, ImmutableList.of(dataPoint)); metricsService.addDataPoints(GAUGE, Observable.just(metric)).subscribe(); expected.add(metric); } else if (metricType == COUNTER) { DataPoint<Long> dataPoint = new DataPoint<>((long) i, (long) i); MetricId<Long> metricId = new MetricId<>(tenantId, COUNTER, "counter"); Metric<Long> metric = new Metric<>(metricId, ImmutableList.of(dataPoint)); metricsService.addDataPoints(COUNTER, Observable.just(metric)).subscribe(); expected.add(metric); } else if (metricType == AVAILABILITY) { AvailabilityType availabilityType = availabilityTypes[i % availabilityTypes.length]; DataPoint<AvailabilityType> dataPoint = new DataPoint<>((long) i, availabilityType); MetricId<AvailabilityType> metricId = new MetricId<>(tenantId, AVAILABILITY, "avail"); Metric<AvailabilityType> metric = new Metric<>(metricId, ImmutableList.of(dataPoint)); metricsService.addDataPoints(AVAILABILITY, Observable.just(metric)).subscribe(); expected.add(metric); } else { fail("Unexpected metric type: " + metricType); } } } assertTrue(latch.await(1, MINUTES), "Did not receive all notifications"); assertEquals(actual.size(), expected.size()); assertTrue(actual.containsAll(expected)); }
From source file:org.apache.hadoop.hive.ql.metadata.Hive.java
/** * Load a directory into a Hive Table. - Alters existing content of table with * the contents of loadPath. - If table does not exist - an exception is * thrown - files in loadPath are moved into Hive. But the directory itself is * not removed.// w w w . j a v a2 s . c o m * * @param loadPath * Directory containing files to load into Table * @param tableName * name of table to be loaded. * @param replace * if true - replace files in the table, otherwise add files to table * @param isSrcLocal * If the source directory is LOCAL * @param isSkewedStoreAsSubdir * if list bucketing enabled * @param hasFollowingStatsTask * if there is any following stats task * @param isAcid true if this is an ACID based write */ public void loadTable(Path loadPath, String tableName, boolean replace, boolean isSrcLocal, boolean isSkewedStoreAsSubdir, boolean isAcid, boolean hasFollowingStatsTask) throws HiveException { List<Path> newFiles = null; Table tbl = getTable(tableName); HiveConf sessionConf = SessionState.getSessionConf(); if (conf.getBoolVar(ConfVars.FIRE_EVENTS_FOR_DML) && !tbl.isTemporary()) { newFiles = Collections.synchronizedList(new ArrayList<Path>()); } if (replace) { Path tableDest = tbl.getPath(); boolean isAutopurge = "true".equalsIgnoreCase(tbl.getProperty("auto.purge")); replaceFiles(tableDest, loadPath, tableDest, tableDest, sessionConf, isSrcLocal, isAutopurge, newFiles); } else { FileSystem fs; try { fs = tbl.getDataLocation().getFileSystem(sessionConf); copyFiles(sessionConf, loadPath, tbl.getPath(), fs, isSrcLocal, isAcid, newFiles); } catch (IOException e) { throw new HiveException("addFiles: filesystem error in check phase", e); } } if (!this.getConf().getBoolVar(HiveConf.ConfVars.HIVESTATSAUTOGATHER)) { StatsSetupConst.setBasicStatsState(tbl.getParameters(), StatsSetupConst.FALSE); } //column stats will be inaccurate StatsSetupConst.clearColumnStatsState(tbl.getParameters()); try { if (isSkewedStoreAsSubdir) { SkewedInfo skewedInfo = tbl.getSkewedInfo(); // Construct list bucketing location mappings from sub-directory name. Map<List<String>, String> skewedColValueLocationMaps = constructListBucketingLocationMap( tbl.getPath(), skewedInfo); // Add list bucketing location mappings. skewedInfo.setSkewedColValueLocationMaps(skewedColValueLocationMaps); } } catch (IOException e) { LOG.error(StringUtils.stringifyException(e)); throw new HiveException(e); } EnvironmentContext environmentContext = null; if (hasFollowingStatsTask) { environmentContext = new EnvironmentContext(); environmentContext.putToProperties(StatsSetupConst.DO_NOT_UPDATE_STATS, StatsSetupConst.TRUE); } try { alterTable(tableName, tbl, environmentContext); } catch (InvalidOperationException e) { throw new HiveException(e); } fireInsertEvent(tbl, null, replace, newFiles); }
From source file:net.sf.ehcache.Cache.java
private List createNewCacheExtensionsList() { return Collections.synchronizedList(new ArrayList()); }
From source file:com.emc.atmos.api.test.AtmosApiClientTest.java
@Test public void testMultiThreadedBufferedWriter() throws Exception { int threadCount = 20; ThreadPoolExecutor executor = new ThreadPoolExecutor(threadCount, threadCount, 5000, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>()); // test with String List<Throwable> errorList = Collections.synchronizedList(new ArrayList<Throwable>()); for (int i = 0; i < threadCount; i++) { executor.execute(/*from www . j a va 2s . c om*/ new ObjectTestThread<String>("Test thread " + i, "text/plain", String.class, errorList)); } do { Thread.sleep(500); } while (executor.getActiveCount() > 0); if (!errorList.isEmpty()) { for (Throwable t : errorList) t.printStackTrace(); Assert.fail("At least one thread failed"); } // test with JAXB bean try { for (int i = 0; i < threadCount; i++) { executor.execute(new ObjectTestThread<AccessTokenPolicy>( createTestTokenPolicy("Test thread " + i, "x.x.x." + i), "text/xml", AccessTokenPolicy.class, errorList)); } do { Thread.sleep(500); } while (executor.getActiveCount() > 0); } finally { executor.shutdown(); } if (!errorList.isEmpty()) { for (Throwable t : errorList) t.printStackTrace(); Assert.fail("At least one thread failed"); } }
From source file:org.pentaho.di.trans.step.BaseStep.java
/** * Sets the step listeners.// w ww .j a va 2s . co m * * @param stepListeners the stepListeners to set */ public void setStepListeners(List<StepListener> stepListeners) { this.stepListeners = Collections.synchronizedList(stepListeners); }
From source file:ffx.algorithms.RotamerOptimization.java
/** * Breaks down a structure into a number of overlapping boxes for * optimization./* w w w.jav a2 s .com*/ * * @return Potential energy of final structure. */ private double boxOptimization(ArrayList<Residue> residueList) { this.usingBoxOptimization = true; long beginTime = -System.nanoTime(); Residue residues[] = residueList.toArray(new Residue[residueList.size()]); boolean firstCellSaved = false; /* * A new dummy Crystal will be constructed for an aperiodic system. The * purpose is to avoid using the overly large dummy Crystal used for * Ewald purposes. Atoms are not and should not be moved into the dummy * Crystal boundaries; to check if an Atom is inside a cell, use an * array of coordinates adjusted to be 0 < coordinate < 1.0. */ Crystal crystal = generateSuperbox(residueList); // Cells indexed by x*(YZ divisions) + y*(Z divisions) + z. int totalCells = getTotalCellCount(crystal); // Also initializes cell count if using -bB if (boxStart > totalCells - 1) { logger.severe(String.format( " FFX shutting down: Box optimization start is out of range of total boxes: %d > %d", (boxStart + 1), totalCells)); } if (boxEnd > totalCells - 1) { boxEnd = totalCells - 1; logIfMaster(" Final box out of range: reset to last possible box."); } else if (boxEnd < 0) { boxEnd = totalCells - 1; } BoxOptCell[] cells = loadCells(crystal, residues); int numCells = cells.length; logIfMaster(String.format(" Optimizing boxes %d to %d", (boxStart + 1), (boxEnd + 1))); /*int restartCell = -1; if (parallelEnergies && loadEnergyRestart) { restartCell = loadEnergyRestartIterations(energyRestartFile); if (restartCell > -1) { logIfMaster(String.format(" Optimization restarting from file at cell #%d", restartCell)); } }*/ for (int i = 0; i < numCells; i++) { /*if (restartCell > -1 && i < restartCell) { continue; }*/ BoxOptCell celli = cells[i]; ArrayList<Residue> residuesList = celli.getResiduesAsList(); int[] cellIndices = celli.getXYZIndex(); logIfMaster(String.format("\n Iteration %d of the box optimization.", (i + 1))); logIfMaster(String.format(" Cell index (linear): %d", (celli.getLinearIndex() + 1))); logIfMaster(String.format(" Cell xyz indices: x = %d, y = %d, z = %d", cellIndices[0] + 1, cellIndices[1] + 1, cellIndices[2] + 1)); int nResidues = residuesList.size(); if (nResidues > 0) { // SDL additions for writing/loading box-based restart files. readyForSingles = false; selfsDone = false; readyForPairs = false; pairsDone = false; readyForTrimers = false; trimersDone = false; energiesToWrite = Collections.synchronizedList(new ArrayList<String>()); receiveThread = new ReceiveThread(residuesList.toArray(new Residue[1])); receiveThread.start(); if (master && writeEnergyRestart && printFiles) { if (energyWriterThread != null) { int waiting = 0; while (energyWriterThread.getState() != java.lang.Thread.State.TERMINATED) { try { if (waiting++ > 20) { logger.log(Level.SEVERE, " ReceiveThread/EnergyWriterThread from previous box locked up."); } logIfMaster( " Waiting for previous iteration's communication threads to shut down... "); Thread.sleep(10000); } catch (InterruptedException ex) { } } } energyWriterThread = new EnergyWriterThread(receiveThread, i + 1, cellIndices); energyWriterThread.start(); } if (loadEnergyRestart) { boxLoadIndex = i + 1; boxLoadCellIndices = new int[3]; boxLoadCellIndices[0] = cellIndices[0]; boxLoadCellIndices[1] = cellIndices[1]; boxLoadCellIndices[2] = cellIndices[2]; } long boxTime = -System.nanoTime(); Residue firstResidue = residuesList.get(0); Residue lastResidue = residuesList.get(nResidues - 1); if (firstResidue != lastResidue) { logIfMaster( String.format(" Residues %s ... %s", firstResidue.toString(), lastResidue.toString())); } else { logIfMaster(String.format(" Residue %s", firstResidue.toString())); } if (revert) { ResidueState[] coordinates = ResidueState.storeAllCoordinates(residuesList); // x is an array of coordinates for the entire molecular assembly. // If x has not yet been constructed, construct it. if (x == null) { Atom atoms[] = molecularAssembly.getAtomArray(); int nAtoms = atoms.length; x = new double[nAtoms * 3]; } double startingEnergy = currentEnergy(residuesList); globalUsingEliminations(residuesList); double finalEnergy = currentEnergy(residuesList); if (startingEnergy <= finalEnergy) { logger.warning( "Optimization did not yield a better energy. Reverting to orginal coordinates."); ResidueState.revertAllCoordinates(residuesList, coordinates); } long currentTime = System.nanoTime(); boxTime += currentTime; logIfMaster(String.format(" Time elapsed for this iteration: %11.3f sec", boxTime * 1.0E-9)); logIfMaster( String.format(" Overall time elapsed: %11.3f sec", (currentTime + beginTime) * 1.0E-9)); } else { globalUsingEliminations(residuesList); long currentTime = System.nanoTime(); boxTime += currentTime; logIfMaster(String.format(" Time elapsed for this iteration: %11.3f sec", boxTime * 1.0E-9)); logIfMaster( String.format(" Overall time elapsed: %11.3f sec", (currentTime + beginTime) * 1.0E-9)); } if (master && printFiles) { String filename = FilenameUtils.removeExtension(molecularAssembly.getFile().getAbsolutePath()) + ".partial"; File file = new File(filename); if (firstCellSaved) { file.delete(); } // Don't write a file if it's the final iteration. if (i == (numCells - 1)) { continue; } PDBFilter windowFilter = new PDBFilter(file, molecularAssembly, null, null); try { windowFilter.writeFile(file, false); if (firstResidue != lastResidue) { logIfMaster(String.format(" File with residues %s ... %s in window written.", firstResidue.toString(), lastResidue.toString())); } else { logIfMaster(String.format(" File with residue %s in window written.", firstResidue.toString())); } firstCellSaved = true; } catch (Exception e) { logger.warning(String.format("Exception writing to file: %s", file.getName())); } } /*for (Residue residue : residueList) { if (residue instanceof MultiResidue) { ((MultiResidue) residue).setDefaultResidue(); residue.reInitOriginalAtomList(); } }*/ } else { logIfMaster(String.format(" Empty box: no residues found.")); } } return 0.0; }
From source file:org.pentaho.di.trans.Trans.java
/** * Sets the list of transformation listeners. * * @param transListeners/*w w w. ja v a2 s . com*/ * the transListeners to set */ public void setTransListeners(List<TransListener> transListeners) { this.transListeners = Collections.synchronizedList(transListeners); }
From source file:org.pentaho.di.trans.Trans.java
/** * Sets the list of stop-event listeners for the transformation. * * @param transStoppedListeners/*from ww w .ja v a2s .com*/ * the list of stop-event listeners to set */ public void setTransStoppedListeners(List<TransStoppedListener> transStoppedListeners) { this.transStoppedListeners = Collections.synchronizedList(transStoppedListeners); }
From source file:ffx.algorithms.RotamerOptimization.java
/** * Turn off non-bonded contributions from all residues except for one. * Compute the self-energy for each residue relative to the backbone * contribution.//from w w w . j av a 2 s . com * * @param residues A list of residues that we undergo rotamer optimization. * @return template energy */ private double rotamerEnergies(Residue residues[]) { if (residues == null) { logger.warning(" Attempt to compute rotamer energies for an empty array of residues."); return 0.0; } int nResidues = residues.length; Atom atoms[] = molecularAssembly.getAtomArray(); int nAtoms = atoms.length; /** * Initialize all atoms to be used. */ for (int i = 0; i < nAtoms; i++) { atoms[i].setUse(true); } if (parallelEnergies) { if (!usingBoxOptimization) { energiesToWrite = Collections.synchronizedList(new ArrayList<String>()); receiveThread = new ReceiveThread(residues); receiveThread.start(); if (master && writeEnergyRestart && printFiles) { energyWriterThread = new EnergyWriterThread(receiveThread); energyWriterThread.start(); } } int loaded = 0; if (loadEnergyRestart) { if (usingBoxOptimization) { loaded = loadEnergyRestart(energyRestartFile, residues, boxLoadIndex, boxLoadCellIndices); } else { loaded = loadEnergyRestart(energyRestartFile, residues); } } SinglesEnergyRegion singlesRegion = new SinglesEnergyRegion(energyWorkerTeam.getThreadCount(), residues); PairsEnergyRegion pairsRegion = new PairsEnergyRegion(energyWorkerTeam.getThreadCount(), residues); TriplesEnergyRegion triplesRegion = new TriplesEnergyRegion(energyWorkerTeam.getThreadCount(), residues); QuadsEnergyRegion quadsRegion = new QuadsEnergyRegion(energyWorkerTeam.getThreadCount(), residues); try { if (loaded < 1) { jobMapSingles.clear(); // allocate selfEnergy int singleJobIndex = 0; selfEnergy = new double[nResidues][]; for (int i = 0; i < nResidues; i++) { Residue resi = residues[i]; Rotamer roti[] = resi.getRotamers(library); selfEnergy[i] = new double[roti.length]; for (int ri = 0; ri < roti.length; ri++) { if (!check(i, ri)) { //logIfMaster(String.format("(sdl %d) singleJob %d: %d %d", BOXNUM, singleJobIndex, i, ri)); Integer selfJob[] = { i, ri }; if (decomposeOriginal && ri != 0) { continue; } jobMapSingles.put(singleJobIndex++, selfJob); } } } } // broadcast that this proc is done with startup and allocation; ready for singles boolean thisProcReady = true; BooleanBuf thisProcReadyBuf = BooleanBuf.buffer(thisProcReady); multicastBuf(thisProcReadyBuf); // launch parallel singles calculation while (!readyForSingles) { Thread.sleep(POLLING_FREQUENCY); } energyWorkerTeam.execute(singlesRegion); if (loaded < 2) { jobMapPairs.clear(); // allocate twoBodyEnergy and create jobs int pairJobIndex = 0; twoBodyEnergy = new double[nResidues][][][]; for (int i = 0; i < nResidues; i++) { Residue resi = residues[i]; Rotamer roti[] = resi.getRotamers(library); twoBodyEnergy[i] = new double[roti.length][][]; for (int ri = 0; ri < roti.length; ri++) { if (check(i, ri)) { continue; } twoBodyEnergy[i][ri] = new double[nResidues][]; for (int j = i + 1; j < nResidues; j++) { Residue resj = residues[j]; Rotamer rotj[] = resj.getRotamers(library); twoBodyEnergy[i][ri][j] = new double[rotj.length]; for (int rj = 0; rj < rotj.length; rj++) { /*if (check(j, rj) || check(i, ri, j, rj)) { continue; }*/ if (checkToJ(i, ri, j, rj)) { continue; } //logIfMaster(String.format("(sdl %d) pairJob %d: %d %d %d %d", BOXNUM, pairJobIndex, i, ri, j, rj)); Integer pairJob[] = { i, ri, j, rj }; if (decomposeOriginal && (ri != 0 || rj != 0)) { continue; } jobMapPairs.put(pairJobIndex++, pairJob); } } } } } // broadcast that this proc is done with pruning and allocation; ready for pairs multicastBuf(thisProcReadyBuf); // launch parallel twoBody calculation while (!readyForPairs) { Thread.sleep(POLLING_FREQUENCY); } energyWorkerTeam.execute(pairsRegion); if (threeBodyTerm) { if (loaded < 3) { jobMapTrimers.clear(); // allocate threeBodyEnergy and create jobs int trimerJobIndex = 0; threeBodyEnergy = new double[nResidues][][][][][]; for (int i = 0; i < nResidues; i++) { Residue resi = residues[i]; Rotamer roti[] = resi.getRotamers(library); threeBodyEnergy[i] = new double[roti.length][][][][]; for (int ri = 0; ri < roti.length; ri++) { if (check(i, ri)) { continue; } threeBodyEnergy[i][ri] = new double[nResidues][][][]; for (int j = i + 1; j < nResidues; j++) { Residue resj = residues[j]; Rotamer rotj[] = resj.getRotamers(library); threeBodyEnergy[i][ri][j] = new double[rotj.length][][]; for (int rj = 0; rj < rotj.length; rj++) { /*if (check(j, rj) || check(i, ri, j, rj)) { continue; }*/ if (checkToJ(i, ri, j, rj)) { continue; } threeBodyEnergy[i][ri][j][rj] = new double[nResidues][]; for (int k = j + 1; k < nResidues; k++) { Residue resk = residues[k]; Rotamer rotk[] = resk.getRotamers(library); threeBodyEnergy[i][ri][j][rj][k] = new double[rotk.length]; for (int rk = 0; rk < rotk.length; rk++) { /*if (check(k, rk) || check(i, ri, k, rk) || check(j, rj, k, rk) || check(i, ri, j, rj, k, rk)) { continue; }*/ if (checkToK(i, ri, j, rj, k, rk)) { continue; } //logIfMaster(String.format("(sdl %d) trimerJob %d: %d %d %d %d %d %d", BOXNUM, trimerJobIndex, i, ri, j, rj, k, rk)); Integer trimerJob[] = { i, ri, j, rj, k, rk }; if (decomposeOriginal && (ri != 0 || rj != 0 || rk != 0)) { continue; } jobMapTrimers.put(trimerJobIndex++, trimerJob); } } } } } } } // broadcast that this proc is done with pruning and allocation; ready for trimers multicastBuf(thisProcReadyBuf); // launch parallel threeBody calculation while (!readyForTrimers) { Thread.sleep(POLLING_FREQUENCY); } energyWorkerTeam.execute(triplesRegion); } if (computeQuads) { logger.info(" Creating quad jobs..."); jobMapQuads.clear(); boolean maxedOut = false; // create quad jobs (no memory allocation) int quadJobIndex = 0; for (int i = 0; i < nResidues; i++) { Residue resi = residues[i]; Rotamer roti[] = resi.getRotamers(library); for (int ri = 0; ri < roti.length; ri++) { if (check(i, ri)) { continue; } for (int j = i + 1; j < nResidues; j++) { Residue resj = residues[j]; Rotamer rotj[] = resj.getRotamers(library); for (int rj = 0; rj < rotj.length; rj++) { /*if (check(j, rj) || check(i, ri, j, rj)) { continue; }*/ if (checkToJ(i, ri, j, rj)) { continue; } for (int k = j + 1; k < nResidues; k++) { Residue resk = residues[k]; Rotamer rotk[] = resk.getRotamers(library); for (int rk = 0; rk < rotk.length; rk++) { /*if (check(k, rk) || check(i, ri, k, rk) || check(j, rj, k, rk) || check(i, ri, j, rj, k, rk)) { continue; }*/ if (checkToK(i, ri, j, rj, k, rk)) { continue; } for (int l = k + 1; l < nResidues; l++) { Residue resl = residues[l]; Rotamer rotl[] = resl.getRotamers(library); for (int rl = 0; rl < rotl.length; rl++) { /*if (check(l, rl) || check(i, ri, l, rl) || check(j, rj, l, rl) || check(k, rk, l, rl) || check(i, ri, j, rj, l, rl) || check(i, ri, k, rk, l, rl) || check(j, rj, k, rk, l, rl)) { continue; }*/ if (checkToL(i, ri, j, rj, k, rk, l, rl)) { continue; } Integer quadJob[] = { i, ri, j, rj, k, rk, l, rl }; if (decomposeOriginal && (ri != 0 || rj != 0 || rk != 0 || rl != 0)) { continue; } jobMapQuads.put(quadJobIndex++, quadJob); if (jobMapQuads.size() > quadMaxout) { maxedOut = true; break; } } if (maxedOut) { break; } } if (maxedOut) { break; } } if (maxedOut) { break; } } if (maxedOut) { break; } } if (maxedOut) { break; } } if (maxedOut) { break; } } if (maxedOut) { break; } } // broadcast that this proc is done with pruning and allocation; ready for quads // logger.info(String.format(" Proc %d broadcasting ready for quads.", world.rank())); multicastBuf(thisProcReadyBuf); // launch parallel threeBody calculation int waiting = 0; while (!readyForQuads) { Thread.sleep(POLLING_FREQUENCY); } logger.info(String.format(" Running quads: %d jobs.", jobMapQuads.size())); energyWorkerTeam.execute(quadsRegion); } } catch (Exception ex) { String message = " Exception computing rotamer energies in parallel."; logger.log(Level.SEVERE, message, ex); } finally { // stop receive and energyWriter threads // receiveThread.die(); } // Turn on all atoms. for (int i = 0; i < atoms.length; i++) { atoms[i].setUse(true); } // Print the energy with all rotamers in their default conformation. if (verboseEnergies && master) { double defaultEnergy = currentEnergy(residues); logger.info( String.format(" Energy of the system with rotamers in their default conformation: %16.8f", defaultEnergy)); } return backboneEnergy; } // endif(parallelEnergies) // TODO: deprecate the rest of the rotamerEnergies() method; the parallel form should work (better) in all scenarios // Store coordinates: will be useful for nucleic acids. ArrayList<Residue> currentResidueList = new ArrayList<>(); currentResidueList.addAll(Arrays.asList(residues)); ResidueState[] origCoordinates = ResidueState.storeAllCoordinates(currentResidueList); //double[][][] originalAtomicCoordinates = storeCoordinates(currentResidueList); for (int i = 0; i < nResidues; i++) { Residue residue = residues[i]; Rotamer rotamers[] = residue.getRotamers(library); /* * Place each AA residue into its zeroth rotamer. * * The default state of NA residues will be original coordinates. * These original coordinates are usually BUT NOT ALWAYS default PDB * coordinates. The reason for this is that the zeroth rotamer for * nucleic acids is frequently a very poor baseline, so one gets * enormous backbone and self energies. * * This would not affect the rigor of the DEE algorithm, but it * makes it difficult to tell when the program is going berserk and * throwing crazy energies. * * The primary exception: if increment is smaller than window size, * some NA residues will be in rotamers assigned by the prior window. * This is still a fairly reasonable baseline. */ switch (residue.getResidueType()) { case NA: break; case AA: default: RotamerLibrary.applyRotamer(residue, rotamers[0]); break; } // RotamerLibrary.applyRotamer(residue, rotamers[0]); // Turn off all side-chain atoms that will be optimized. turnOffAtoms(residue); } /** * Initialize all atoms to be used. */ boolean useOrigCoordsRot = library.getUsingOrigCoordsRotamer(); // Compute the backbone energy. List<Residue> rList = new ArrayList<>(Collections.nCopies(4, null)); try { backboneEnergy = currentEnergy(rList, false); } catch (ArithmeticException ex) { logger.severe(String.format("FFX shutting down: error in calculation of backbone energy %s", ex.getMessage())); } logger.info(String.format(" Backbone energy: %16.8f\n", backboneEnergy)); // Compute the self-energy for each rotamer of each residue selfEnergy = new double[nResidues][]; for (int i = 0; i < nResidues; i++) { Residue residue = residues[i]; rList.set(0, residue); Rotamer rotamers[] = residue.getRotamers(library); int nrot = rotamers.length; // Create space for this residue's rotamer self-energies. selfEnergy[i] = new double[nrot]; // Turn on this residue's side-chain atoms turnOnAtoms(residue); // Loop over rotamers computing self-energies. double minEnergy = Double.MAX_VALUE; for (int ri = 0; ri < nrot; ri++) { if (pruneClashes && check(i, ri) && !(useOrigCoordsRot && ri == 0)) { continue; } Rotamer rotamer = rotamers[ri]; RotamerLibrary.applyRotamer(residue, rotamer); selfEnergy[i][ri] = currentEnergy(rList) - backboneEnergy; logger.info(String.format(" Self-energy %s %d: %16.8f", residue, ri, self(i, ri))); if (algorithmListener != null) { algorithmListener.algorithmUpdate(molecularAssembly); } if (self(i, ri) < minEnergy) { minEnergy = self(i, ri); } } if (pruneClashes) { for (int ri = 0; ri < nrot; ri++) { if (residue.getResidueType() == NA) { if (!check(i, ri) && (self(i, ri) > (minEnergy + (clashThreshold * pruningFactor * singletonNAPruningFactor)))) { logger.info(String.format(" Clash for rotamer %s %d: %16.8f >> %16.8f", residue, ri, self(i, ri), minEnergy)); eliminateRotamer(residues, i, ri, print); } } else if (!check(i, ri) && (self(i, ri) > (minEnergy + clashThreshold))) { // don't prune orig-coords rotamers if (!(useOrigCoordsRot && ri == 0)) { logger.info(String.format(" Clash for rotamer %s %d: %16.8f >> %16.8f", residue, ri, self(i, ri), minEnergy)); eliminateRotamer(residues, i, ri, print); } } } } // Reset the residue to its default conformation. if (residue.getResidueType() == NA) { residue.revertState(origCoordinates[i]); //revertSingleResidueCoordinates(residue, originalAtomicCoordinates[i]); } else { RotamerLibrary.applyRotamer(residue, rotamers[0]); } // Turn off the side-chain turnOffAtoms(residue); } // Compute the pair-energy for each pair of rotamers twoBodyEnergy = new double[nResidues][][][]; for (int i = 0; i < nResidues - 1; i++) { Residue residuei = residues[i]; rList.set(0, residuei); Rotamer rotamersi[] = residuei.getRotamers(library); int indexI = allResiduesList.indexOf(residuei); // Turn on residue i turnOnAtoms(residuei); int ni = rotamersi.length; twoBodyEnergy[i] = new double[ni][][]; for (int ri = 0; ri < ni; ri++) { if (pruneClashes && check(i, ri) && !(useOrigCoordsRot && ri == 0)) { continue; } Rotamer rotameri = rotamersi[ri]; RotamerLibrary.applyRotamer(residuei, rotameri); twoBodyEnergy[i][ri] = new double[nResidues][]; for (int j = i + 1; j < nResidues; j++) { Residue residuej = residues[j]; rList.set(1, residuej); Rotamer rotamersj[] = residuej.getRotamers(library); int indexJ = allResiduesList.indexOf(residuej); turnOnAtoms(residuej); // Loop over residue j's rotamers and compute pairwise energies. int nj = rotamersj.length; twoBodyEnergy[i][ri][j] = new double[nj]; for (int rj = 0; rj < nj; rj++) { // don't prune orig-coords rotamers if (pruneClashes && (check(j, rj) || check(i, ri, j, rj)) && !(useOrigCoordsRot && ri == 0 && rj == 0)) { continue; } Rotamer rotamerj = rotamersj[rj]; RotamerLibrary.applyRotamer(residuej, rotamerj); if (distanceMatrix != null) { double dist = checkDistanceMatrix(indexI, ri, indexJ, rj); if (dist < superpositionThreshold) { twoBodyEnergy[i][ri][j][rj] = 1.0E100; logger.info(String.format( " Pair energy %s %d, %s %d: set to 1.0E100 at distance %13.6f Ang < %5.3f Ang", residuei, ri, residuej, rj, dist, superpositionThreshold)); } else { twoBodyEnergy[i][ri][j][rj] = currentEnergy(rList) - self(i, ri) - self(j, rj) - backboneEnergy; logger.info( String.format(" Pair energy %s %d, %s %d: %16.8f at distance %10.3f Ang", residuei, ri, residuej, rj, pair(i, ri, j, rj), dist)); } } else { twoBodyEnergy[i][ri][j][rj] = currentEnergy(rList) - self(i, ri) - self(j, rj) - backboneEnergy; logger.info(String.format(" Pair energy %s %d, %s %d: %16.8f.", residuei, ri, residuej, rj, pair(i, ri, j, rj))); } if (algorithmListener != null) { algorithmListener.algorithmUpdate(molecularAssembly); } } // Reset the residue to its default conformation. if (residuej.getResidueType() == NA) { residuej.revertState(origCoordinates[j]); //revertSingleResidueCoordinates(residuej, originalAtomicCoordinates[j]); } else { RotamerLibrary.applyRotamer(residuej, rotamersj[0]); } // RotamerLibrary.applyRotamer(residuej, rotamersj[0]); turnOffAtoms(residuej); } } // Reset the residue to its default conformation. if (residuei.getResidueType() == NA) { residuei.revertState(origCoordinates[i]); //revertSingleResidueCoordinates(residuei, originalAtomicCoordinates[i]); } else { RotamerLibrary.applyRotamer(residuei, rotamersi[0]); } turnOffAtoms(residuei); } if (prunePairClashes) { prunePairClashes(residues); } // Prune each rotamer that clashes with all rotamers from a 2nd residue. /*if (prunePairClashes) { for (int i = 0; i < nResidues - 1; i++) { Residue resi = residues[i]; Rotamer[] roti = resi.getRotamers(library); int ni = roti.length; for (int j = i + 1; j < nResidues; j++) { Residue resj = residues[j]; Rotamer[] rotj = resj.getRotamers(library); int nj = rotj.length; double minPair = Double.MAX_VALUE; for (int ri = 0; ri < ni; ri++) { if (check(i, ri)) { continue; } for (int rj = 0; rj < nj; rj++) { if (check(j, rj)) { continue; } if (minPair > (pair(i, ri, j, rj) + self(i, ri) + self(j, rj))) { minPair = (pair(i, ri, j, rj) + self(i, ri) + self(j, rj)); } } } // Check for elimination of any rotamer ri. for (int ri = 0; ri < ni; ri++) { if (check(i, ri)) { continue; } double eliminate = Double.MAX_VALUE; for (int rj = 0; rj < nj; rj++) { if (check(j, rj)) { continue; } if ((pair(i, ri, j, rj) + self(i, ri) + self(j, rj)) < eliminate) { eliminate = (pair(i, ri, j, rj) + self(i, ri) + self(j, rj)); } } // Prune based on clash threshold and the appropriate // pruning factor (1.0 for AA pairs, pF for NA pairs, // arithmetic mean for AA-NA pairs). if (resi.getResidueType() == NA && resj.getResidueType() == NA) { if (eliminate > (minPair + (pairClashThreshold * pruningFactor))) { logger.info(String.format( " Pruning rotamer %s %d that clashes with all %s rotamers %16.8f >> %16.8f.", resi, ri, resj, eliminate, minPair + (pairClashThreshold * pruningFactor))); eliminateRotamer(residues, i, ri, print); } } else if (resi.getResidueType() == NA || resj.getResidueType() == NA) { if (eliminate > (minPair + (pairClashThreshold * pairHalfPruningFactor))) { logger.info(String.format( " Pruning rotamer %s %d that clashes with all %s rotamers %16.8f >> %16.8f.", resi, ri, resj, eliminate, minPair + (pairClashThreshold * pairHalfPruningFactor))); eliminateRotamer(residues, i, ri, print); } } else { if (eliminate > (minPair + pairClashThreshold)) { // don't prune orig-coords rotamers if (!(useOrigCoordsRot && ri == 0)) { logger.info(String.format( " Pruning rotamer %s %d that clashes with all %s rotamers %16.8f >> %16.8f.", resi, ri, resj, eliminate, minPair + pairClashThreshold)); eliminateRotamer(residues, i, ri, print); } } } } // Check for elimination of any rotamer rj. for (int rj = 0; rj < nj; rj++) { if (check(j, rj)) { continue; } double eliminate = Double.MAX_VALUE; for (int ri = 0; ri < ni; ri++) { if (check(i, ri)) { continue; } if ((pair(i, ri, j, rj) + self(i, ri) + self(j, rj)) < eliminate) { eliminate = (pair(i, ri, j, rj) + self(i, ri) + self(j, rj)); } } if (resi.getResidueType() == NA && resj.getResidueType() == NA) { if (eliminate > (minPair + (pairClashThreshold * pruningFactor))) { logger.info(String.format( " Pruning rotamer %s %d that clashes with all %s rotamers %16.8f >> %16.8f.", resj, rj, resi, eliminate, minPair + (pairClashThreshold * pruningFactor))); eliminateRotamer(residues, j, rj, print); } } else if (resi.getResidueType() == NA || resj.getResidueType() == NA) { if (eliminate > (minPair + (pairClashThreshold * pairHalfPruningFactor))) { logger.info(String.format( " Pruning rotamer %s %d that clashes with all %s rotamers %16.8f >> %16.8f.", resj, rj, resi, eliminate, minPair + (pairClashThreshold * pairHalfPruningFactor))); eliminateRotamer(residues, j, rj, print); } } else { if (eliminate > (minPair + pairClashThreshold)) { // don't prune orig-coords rotamers if (!(useOrigCoordsRot && rj == 0)) { logger.info(String.format( " Pruning rotamer %s %d that clashes with all %s rotamers %16.8f >> %16.8f.", resj, rj, resi, eliminate, minPair + pairClashThreshold)); eliminateRotamer(residues, j, rj, print); } } } } } } } */ // Compute the trimer-energy for each pair of rotamers if (threeBodyTerm) { double[][][][] localDistanceMatrix = new double[nResidues][][][]; if (distance <= 0) { logger.info(" Calculating local distance matrix using non-eliminated rotamers."); localSequentialDistanceMatrix(residues, localDistanceMatrix); } threeBodyEnergy = new double[nResidues][][][][][]; for (int i = 0; i < nResidues - 2; i++) { Residue residuei = residues[i]; rList.set(0, residuei); Rotamer rotamersi[] = residuei.getRotamers(library); turnOnAtoms(residuei); int ni = rotamersi.length; threeBodyEnergy[i] = new double[ni][][][][]; int indexOfI = allResiduesList.indexOf(residuei); for (int ri = 0; ri < ni; ri++) { if (pruneClashes && check(i, ri) && !(ri == 0 && useOrigCoordsRot)) { continue; } Rotamer rotameri = rotamersi[ri]; RotamerLibrary.applyRotamer(residuei, rotameri); //int npairs = residues.length - (i + 1); // TODO: reduce memory use. threeBodyEnergy[i][ri] = new double[nResidues][][][]; for (int j = i + 1; j < nResidues - 1; j++) { Residue residuej = residues[j]; rList.set(1, residuej); Rotamer rotamersj[] = residuej.getRotamers(library); turnOnAtoms(residuej); // Loop over residue j's rotamers and compute pair-wise energies. int nj = rotamersj.length; threeBodyEnergy[i][ri][j] = new double[nj][][]; int indexOfJ = allResiduesList.indexOf(residuej); for (int rj = 0; rj < nj; rj++) { if ((pruneClashes && (check(j, rj)) || (prunePairClashes && check(i, ri, j, rj))) && !(useOrigCoordsRot && (ri == 0 && rj == 0))) { continue; } Rotamer rotamerj = rotamersj[rj]; RotamerLibrary.applyRotamer(residuej, rotamerj); threeBodyEnergy[i][ri][j][rj] = new double[nResidues][]; for (int k = j + 1; k < nResidues; k++) { Residue residuek = residues[k]; rList.set(2, residuek); Rotamer rotamersk[] = residuek.getRotamers(library); turnOnAtoms(residuek); int nk = rotamersk.length; threeBodyEnergy[i][ri][j][rj][k] = new double[nk]; int indexOfK = allResiduesList.indexOf(residuek); for (int rk = 0; rk < nk; rk++) { if ((pruneClashes && (check(k, rk)) || (prunePairClashes && check(i, ri, k, rk)) || (prunePairClashes && check(j, rj, k, rk))) && !(useOrigCoordsRot && (ri == 0 && rj == 0 && rk == 0))) { continue; } double dij; double dik; double djk; if (distance > 0) { /* * Distance matrix is asymmetric (it will have 4-6, but * not 6-4 stored). The present implementation sorts * windows beforehand, but this double-checks to ensure * the proper address in distanceMatrix is being called. */ dij = checkDistanceMatrix(indexOfI, ri, indexOfJ, rj); dik = checkDistanceMatrix(indexOfI, ri, indexOfK, rk); djk = checkDistanceMatrix(indexOfJ, rj, indexOfK, rk); /* if (indexOfI > indexOfJ) { dij = distanceMatrix[indexOfJ][rj][indexOfI][ri]; } else { dij = distanceMatrix[indexOfI][ri][indexOfJ][rj]; } if (indexOfI > indexOfK) { dik = distanceMatrix[indexOfK][rk][indexOfI][ri]; } else { dik = distanceMatrix[indexOfI][ri][indexOfK][rk]; } if (indexOfJ > indexOfK) { djk = distanceMatrix[indexOfK][rk][indexOfJ][rj]; } else { djk = distanceMatrix[indexOfJ][rj][indexOfK][rk]; } */ } else { dij = localDistanceMatrix[i][ri][j][rj]; dik = localDistanceMatrix[i][ri][k][rk]; djk = localDistanceMatrix[j][rj][k][rk]; } double dist = Math.min(dij, Math.min(dik, djk)); if (!threeBodyCutoff || (dist < threeBodyCutoffDist)) { if (dist < superpositionThreshold) { threeBodyEnergy[i][ri][j][rj][k][rk] = 1.0E100; logger.info(String.format( " Trimer energy %s %d, %s %d, %s %d: set to 1.0E100 at %13.6f Ang < %5.3f Ang.", residuei, ri, residuej, rj, residuek, rk, dist, superpositionThreshold)); } else { Rotamer rotamerk = rotamersk[rk]; RotamerLibrary.applyRotamer(residuek, rotamerk); threeBodyEnergy[i][ri][j][rj][k][rk] = currentEnergy(rList) - self(i, ri) - self(j, rj) - self(k, rk) - pair(i, ri, j, rj) - pair(i, ri, k, rk) - pair(j, rj, k, rk) - backboneEnergy; logger.info(String.format( " Trimer energy %s %d, %s %d, %s %d: %16.8f at %10.3f Ang.", residuei, ri, residuej, rj, residuek, rk, threeBodyEnergy[i][ri][j][rj][k][rk], dist)); if (algorithmListener != null) { algorithmListener.algorithmUpdate(molecularAssembly); } } } else { logger.info(String.format( " Trimer energy %s %d, %s %d, %s %d: %16.8f at %10.3f Ang.", residuei, ri, residuej, rj, residuek, rk, 0.0, threeBodyCutoffDist)); } } // Reset the residue to its default conformation. if (residuek.getResidueType() == NA) { residuek.revertState(origCoordinates[k]); //revertSingleResidueCoordinates(residuek, originalAtomicCoordinates[k]); } else { RotamerLibrary.applyRotamer(residuek, rotamersk[0]); } turnOffAtoms(residuek); } } // Reset the residue to its default conformation. if (residuej.getResidueType() == NA) { residuej.revertState(origCoordinates[j]); //revertSingleResidueCoordinates(residuej, originalAtomicCoordinates[j]); } else { RotamerLibrary.applyRotamer(residuej, rotamersj[0]); } turnOffAtoms(residuej); } } // Reset the residue to its default conformation. if (residuei.getResidueType() == NA) { residuei.revertState(origCoordinates[i]); //revertSingleResidueCoordinates(residuei, originalAtomicCoordinates[i]); } else { RotamerLibrary.applyRotamer(residuei, rotamersi[0]); } turnOffAtoms(residuei); } } // Turn on all atoms. for (int i = 0; i < nAtoms; i++) { atoms[i].setUse(true); } // Print the energy with all rotamers in their default conformation. if (verboseEnergies) { double defaultEnergy = currentEnergy(residues); logger.info(String.format(" Energy of the system with rotamers in their default conformation: %16.8f", defaultEnergy)); } return backboneEnergy; }
From source file:base.BasePlayer.Main.java
static void setChromDrop(String dir) { try {//w ww . j ava2 s. co m if (!new File(genomeDir.getCanonicalPath() + "/" + dir).exists() || dir.length() == 0) { /*String[] empty = {""}; chromModel = new DefaultComboBoxModel<String>(empty); chromosomeDropdown = new SteppedComboBox(chromModel); */ if (chromModel != null) { chromModel.removeAllElements(); chromosomeDropdown.removeAllItems(); chromosomeDropdown.revalidate(); chromosomeDropdown.repaint(); Main.searchTable.clear(); if (Main.drawCanvas.splits.size() > 0) { Main.drawCanvas.splits.get(0).clearGenes(); } Main.chromDraw.updateExons = true; Main.chromDraw.repaint(); } else { String[] empty = { "" }; chromModel = new DefaultComboBoxModel<String>(empty); chromosomeDropdown = new SteppedComboBox(chromModel); chromosomeDropdown.revalidate(); chromosomeDropdown.repaint(); } } else { File chromindex = null; selectedGenome = dir; File defdir = new File(genomeDir.getCanonicalPath() + "/" + dir); File[] files = defdir.listFiles(); if (files == null) { return; } String chromtemp = ""; chromnamevector = Collections.synchronizedList(new ArrayList<String>()); // boolean faifound = false; for (int i = 0; i < files.length; i++) { if (files[i].isDirectory()) { continue; } if (files[i].getName().contains(".gz")) { continue; } else if (files[i].getName().contains(".fai")) { chromindex = new File(defdir.getCanonicalPath() + "/" + files[i].getName()); // faifound = true; } else if (files[i].getName().contains(".fa")) { chromtemp = defdir.getCanonicalPath() + "/" + files[i].getName(); } } if (chromtemp.equals("")) { String[] empty = { "" }; chromModel = new DefaultComboBoxModel<String>(empty); chromosomeDropdown = new SteppedComboBox(chromModel); chromosomeDropdown.revalidate(); chromosomeDropdown.repaint(); return; } if (referenceFile != null) { referenceFile.close(); } referenceFile = new RandomAccessFile(chromtemp, "r"); ref = new File(chromtemp); BufferedReader reader = new BufferedReader(new FileReader(chromindex)); String line; String[] split; ChromDraw.chromPos = new HashMap<String, Integer>(); chromIndex = new Hashtable<String, Long[]>(); textlength = 0; while ((line = reader.readLine()) != null) { split = line.split("\t"); chromnamevector.add(split[0]); Long[] add = { Long.parseLong(split[2]), Long.parseLong(split[1]), Long.parseLong(split[3]) }; if (split[0].equals("MT")) { ChromDraw.chromPos.put("M", Integer.parseInt(split[1])); chromIndex.put("M", add); } chromIndex.put(split[0], add); if (split[0].length() > textlength) { textlength = split[0].length(); } ChromDraw.chromPos.put(split[0], Integer.parseInt(split[1])); } reader.close(); MethodLibrary.ChromSorter sorter = new MethodLibrary.ChromSorter(); Collections.sort(chromnamevector, sorter); chromnames = new String[chromnamevector.size()]; if (chromnamevector.get(0).contains("chr")) { refchrom = "chr"; } else { refchrom = ""; } for (int i = 0; i < chromnames.length; i++) { chromnames[i] = chromnamevector.get(i).replace(refchrom, ""); } chromModel = new DefaultComboBoxModel<String>(chromnames); if (chromosomeDropdown == null) { chromosomeDropdown = new SteppedComboBox(chromModel); } else { chromosomeDropdown.setModel(chromModel); } clicked = false; refDropdown.setSelectedItem(dir); clicked = true; clickedAnno = false; setAnnotationDrop(dir); if (defaultAnnotation.length() == 0) { geneDropdown.setSelectedIndex(0); } else { geneDropdown.setSelectedItem(defaultAnnotation); } clickedAnno = true; int letterlength = chromosomeDropdown.getFontMetrics(chromosomeDropdown.getFont()).stringWidth("E"); chromosomeDropdown.setPopupWidth(textlength * letterlength + 25); chromosomeDropdown.revalidate(); chromosomeDropdown.repaint(); refDropdown.setToolTipText(refDropdown.getSelectedItem().toString()); geneDropdown.setToolTipText(geneDropdown.getSelectedItem().toString()); } } catch (Exception e) { e.printStackTrace(); } }