List of usage examples for java.lang IndexOutOfBoundsException toString
public String toString()
From source file:com.genentech.chemistry.openEye.apps.SDFMolSeparator.java
/** * @param args/*from ww w. j a va 2 s .com*/ */ public static void main(String... args) throws IOException { // create command line Options object Options options = new Options(); Option opt = new Option(OPT_INFILE, true, "input file oe-supported Use .sdf|.smi to specify the file type."); opt.setRequired(true); options.addOption(opt); opt = new Option(OPT_OUTFILE, true, "output file oe-supported. Use .sdf|.smi to specify the file type."); opt.setRequired(true); options.addOption(opt); CommandLineParser parser = new PosixParser(); CommandLine cmd = null; try { cmd = parser.parse(options, args); } catch (Exception e) { System.err.println(e.getMessage()); exitWithHelp(options); } args = cmd.getArgs(); if (cmd.hasOption("d")) { System.err.println("Start debugger and press return:"); new BufferedReader(new InputStreamReader(System.in)).readLine(); } String inFile = cmd.getOptionValue(OPT_INFILE); String outFile = cmd.getOptionValue(OPT_OUTFILE); SDFMolSeparator separator = new SDFMolSeparator(outFile); try { separator.run(inFile); } catch (IndexOutOfBoundsException iie) { System.err.println(iie.toString()); exitWithHelp(options); } finally { separator.close(); } }
From source file:com.t2.biofeedback.BioFeedbackService.java
void performServiceCommand(Message msg) { byte[] payload = msg.getData().getByteArray("EXTRA_MESSAGE_PAYLOAD"); if (payload == null) return;/* ww w . j av a 2 s.co m*/ if (deviceManager == null) { Log.e(TAG, "NEW no device manager"); return; } byte sensor; byte command; byte[] btAddress = new byte[6]; String btAddressString; if (payload.length == 7 + 255) { // See ShimmerNonSpineSetupSensor_codec for coding format command = payload[0]; try { for (int i = 0; i < 6; i++) { btAddress[i] = payload[i + 1]; } btAddressString = Util.getBtStringAddress(btAddress); } catch (IndexOutOfBoundsException e) { Log.e(TAG, e.toString()); btAddressString = ""; } if (command == COMMAND_ENABLED) { this.deviceManager.setDeviceEnabled(btAddressString, true); } else { if (command == COMMAND_DISABLED) { this.deviceManager.setDeviceEnabled(btAddressString, false); } else { Log.e(TAG, "performServiceCommand() Command not recognized"); } } } // Now send the updated device list to the activity so it can update it's listview sendDeviceList(); }
From source file:com.t2.biofeedback.BioFeedbackService.java
void performSetupSensor(Message msg) { byte[] payload = msg.getData().getByteArray("EXTRA_MESSAGE_PAYLOAD"); if (payload == null) return;/* w w w. ja v a 2s .co m*/ if (deviceManager == null) { Log.e(TAG, "NEW no device manager"); return; } byte sensor; byte command; byte[] btAddress = new byte[6]; String btAddressString; if (payload.length == 8 + 255) { // See ShimmerNonSpineSetupSensor_codec for coding format sensor = payload[0]; command = payload[1]; try { for (int i = 0; i < 6; i++) { btAddress[i] = payload[i + 2]; } btAddressString = Util.getBtStringAddress(btAddress); } catch (IndexOutOfBoundsException e) { Log.e(TAG, e.toString()); btAddressString = ""; } BioFeedbackDevice[] enabledDevices = deviceManager.getEnabledDevices(); for (BioFeedbackDevice d : enabledDevices) { if (d.isBonded() && d.isConencted()) { if (d instanceof ShimmerDevice) { String s = d.getAddress(); if (d.getAddress().equalsIgnoreCase(btAddressString)) { Log.i(TAG, "Address = " + s); ShimmerDevice dev = (ShimmerDevice) d; dev.setup(sensor, command); } } } } } }
From source file:com.searchcode.app.jobs.repository.IndexGitRepoJob.java
/** * Uses the inbuilt git// w ww. j av a2 s .c o m * TODO this method appears to leak memory like crazy... need to investigate * TODO lots of hairy bits in here need tests to capture issues */ public List<CodeOwner> getBlameInfo(int codeLinesSize, String repoName, String repoLocations, String fileName) { List<CodeOwner> codeOwners = new ArrayList<>(codeLinesSize); try { // The / part is required due to centos bug for version 1.1.1 // This appears to be correct String repoLoc = repoLocations + "/" + repoName + "/.git"; Repository localRepository = new FileRepository(new File(repoLoc)); BlameCommand blamer = new BlameCommand(localRepository); ObjectId commitID = localRepository.resolve("HEAD"); if (commitID == null) { Singleton.getLogger().info("getBlameInfo commitID is null for " + repoLoc + " " + fileName); return codeOwners; } BlameResult blame; // Somewhere in here appears to be wrong... blamer.setStartCommit(commitID); blamer.setFilePath(fileName); blame = blamer.call(); // Hail mary attempt to solve issue on CentOS Attempt to set at all costs if (blame == null) { // This one appears to solve the issue so don't remove it String[] split = fileName.split("/"); blamer.setStartCommit(commitID); if (split.length != 1) { blamer.setFilePath(String.join("/", Arrays.asList(split).subList(1, split.length))); } blame = blamer.call(); } if (blame == null) { String[] split = fileName.split("/"); blamer.setStartCommit(commitID); if (split.length != 1) { blamer.setFilePath("/" + String.join("/", Arrays.asList(split).subList(1, split.length))); } blame = blamer.call(); } if (blame == null) { Singleton.getLogger().info("getBlameInfo blame is null for " + repoLoc + " " + fileName); } if (blame != null) { // Get all the owners their number of commits and most recent commit HashMap<String, CodeOwner> owners = new HashMap<>(); RevCommit commit; PersonIdent authorIdent; try { for (int i = 0; i < codeLinesSize; i++) { commit = blame.getSourceCommit(i); authorIdent = commit.getAuthorIdent(); if (owners.containsKey(authorIdent.getName())) { CodeOwner codeOwner = owners.get(authorIdent.getName()); codeOwner.incrementLines(); int timestamp = codeOwner.getMostRecentUnixCommitTimestamp(); if (commit.getCommitTime() > timestamp) { codeOwner.setMostRecentUnixCommitTimestamp(commit.getCommitTime()); } owners.put(authorIdent.getName(), codeOwner); } else { owners.put(authorIdent.getName(), new CodeOwner(authorIdent.getName(), 1, commit.getCommitTime())); } } } catch (IndexOutOfBoundsException ex) { // Ignore this as its not really a problem or is it? Singleton.getLogger().info( "IndexOutOfBoundsException when trying to get blame for " + repoName + " " + fileName); } codeOwners = new ArrayList<>(owners.values()); } } catch (IOException ex) { Singleton.getLogger().info("IOException getBlameInfo when trying to get blame for " + repoName + " " + fileName + " " + ex.toString()); } catch (GitAPIException ex) { Singleton.getLogger().info("GitAPIException getBlameInfo when trying to get blame for " + repoName + " " + fileName + " " + ex.toString()); } catch (IllegalArgumentException ex) { Singleton.getLogger().info("IllegalArgumentException getBlameInfo when trying to get blame for " + repoName + " " + fileName + " " + ex.toString()); } System.gc(); // Try to clean up return codeOwners; }
From source file:com.example.nachiketvatkar.locateus.BluetoothPairing.java
private void decodeScanRecords(BluetoothDeviceData deviceData) { // based on http://stackoverflow.com/questions/24003777/read-advertisement-packet-in-android final byte[] scanRecord = deviceData.scanRecord; ArrayList<UUID> uuids = new ArrayList<>(); byte[] advertisedData = Arrays.copyOf(scanRecord, scanRecord.length); int offset = 0; deviceData.type = BluetoothDeviceData.kType_Unknown; // Check if is an iBeacon ( 0x02, 0x0x1, a flag byte, 0x1A, 0xFF, manufacturer (2bytes), 0x02, 0x15) final boolean isBeacon = advertisedData[0] == 0x02 && advertisedData[1] == 0x01 && advertisedData[3] == 0x1A && advertisedData[4] == (byte) 0xFF && advertisedData[7] == 0x02 && advertisedData[8] == 0x15; // Check if is an URIBeacon final byte[] kUriBeaconPrefix = { 0x03, 0x03, (byte) 0xD8, (byte) 0xFE }; final boolean isUriBeacon = Arrays.equals(Arrays.copyOf(scanRecord, kUriBeaconPrefix.length), kUriBeaconPrefix) && advertisedData[5] == 0x16 && advertisedData[6] == kUriBeaconPrefix[2] && advertisedData[7] == kUriBeaconPrefix[3]; if (isBeacon) { deviceData.type = BluetoothDeviceData.kType_Beacon; // Read uuid offset = 9;//from w ww. j a v a 2 s . c o m UUID uuid = BleUtils.getUuidFromByteArrayBigEndian(Arrays.copyOfRange(scanRecord, offset, offset + 16)); uuids.add(uuid); offset += 16; // Skip major minor offset += 2 * 2; // major, minor // Read txpower final int txPower = advertisedData[offset++]; deviceData.txPower = txPower; } else if (isUriBeacon) { deviceData.type = BluetoothDeviceData.kType_UriBeacon; // Read txpower final int txPower = advertisedData[9]; deviceData.txPower = txPower; } else { // Read standard advertising packet while (offset < advertisedData.length - 2) { // Length int len = advertisedData[offset++]; if (len == 0) break; // Type int type = advertisedData[offset++]; if (type == 0) break; // Data // Log.d(TAG, "record -> lenght: " + length + " type:" + type + " data" + data); switch (type) { case 0x02: // Partial list of 16-bit UUIDs case 0x03: {// Complete list of 16-bit UUIDs while (len > 1) { int uuid16 = advertisedData[offset++] & 0xFF; uuid16 |= (advertisedData[offset++] << 8); len -= 2; uuids.add(UUID.fromString(String.format("%08x-0000-1000-8000-00805f9b34fb", uuid16))); } break; } case 0x06: // Partial list of 128-bit UUIDs case 0x07: { // Complete list of 128-bit UUIDs while (len >= 16) { try { // Wrap the advertised bits and order them. UUID uuid = BleUtils.getUuidFromByteArraLittleEndian( Arrays.copyOfRange(advertisedData, offset, offset + 16)); uuids.add(uuid); } catch (IndexOutOfBoundsException e) { Log.e(TAG, "BlueToothDeviceFilter.parseUUID: " + e.toString()); } finally { // Move the offset to read the next uuid. offset += 16; len -= 16; } } break; } case 0x0A: { // TX Power final int txPower = advertisedData[offset++]; deviceData.txPower = txPower; break; } default: { offset += (len - 1); break; } } } // Check if Uart is contained in the uuids boolean isUart = false; for (UUID uuid : uuids) { // if (uuid.toString().equalsIgnoreCase(UartInterfaceActivity.UUID_SERVICE)){ // isUart = true; // break; // } } if (isUart) { deviceData.type = BluetoothDeviceData.kType_Uart; } } deviceData.uuids = uuids; }
From source file:com.cs4644.vt.theonering.MainActivity.java
private void decodeScanRecords(BluetoothDeviceData deviceData) { // based on http://stackoverflow.com/questions/24003777/read-advertisement-packet-in-android final byte[] scanRecord = deviceData.scanRecord; ArrayList<UUID> uuids = new ArrayList<>(); byte[] advertisedData = Arrays.copyOf(scanRecord, scanRecord.length); int offset = 0; deviceData.type = BluetoothDeviceData.kType_Unknown; // Check if is an iBeacon ( 0x02, 0x0x1, a flag byte, 0x1A, 0xFF, manufacturer (2bytes), 0x02, 0x15) final boolean isBeacon = advertisedData[0] == 0x02 && advertisedData[1] == 0x01 && advertisedData[3] == 0x1A && advertisedData[4] == (byte) 0xFF && advertisedData[7] == 0x02 && advertisedData[8] == 0x15; // Check if is an URIBeacon final byte[] kUriBeaconPrefix = { 0x03, 0x03, (byte) 0xD8, (byte) 0xFE }; final boolean isUriBeacon = Arrays.equals(Arrays.copyOf(scanRecord, kUriBeaconPrefix.length), kUriBeaconPrefix) && advertisedData[5] == 0x16 && advertisedData[6] == kUriBeaconPrefix[2] && advertisedData[7] == kUriBeaconPrefix[3]; if (isBeacon) { deviceData.type = BluetoothDeviceData.kType_Beacon; // Read uuid offset = 9;//from w w w. java 2 s . co m UUID uuid = BleUtils.getUuidFromByteArrayBigEndian(Arrays.copyOfRange(scanRecord, offset, offset + 16)); uuids.add(uuid); offset += 16; // Skip major minor offset += 2 * 2; // major, minor // Read txpower final int txPower = advertisedData[offset++]; deviceData.txPower = txPower; } else if (isUriBeacon) { deviceData.type = BluetoothDeviceData.kType_UriBeacon; // Read txpower final int txPower = advertisedData[9]; deviceData.txPower = txPower; } else { // Read standard advertising packet while (offset < advertisedData.length - 2) { // Length int len = advertisedData[offset++]; if (len == 0) break; // Type int type = advertisedData[offset++]; if (type == 0) break; // Data // Log.d(TAG, "record -> lenght: " + length + " type:" + type + " data" + data); switch (type) { case 0x02: // Partial list of 16-bit UUIDs case 0x03: {// Complete list of 16-bit UUIDs while (len > 1) { int uuid16 = advertisedData[offset++] & 0xFF; uuid16 |= (advertisedData[offset++] << 8); len -= 2; uuids.add(UUID.fromString(String.format("%08x-0000-1000-8000-00805f9b34fb", uuid16))); } break; } case 0x06: // Partial list of 128-bit UUIDs case 0x07: { // Complete list of 128-bit UUIDs while (len >= 16) { try { // Wrap the advertised bits and order them. UUID uuid = BleUtils.getUuidFromByteArraLittleEndian( Arrays.copyOfRange(advertisedData, offset, offset + 16)); uuids.add(uuid); } catch (IndexOutOfBoundsException e) { Log.e(TAG, "BlueToothDeviceFilter.parseUUID: " + e.toString()); } finally { // Move the offset to read the next uuid. offset += 16; len -= 16; } } break; } case 0x0A: { // TX Power final int txPower = advertisedData[offset++]; deviceData.txPower = txPower; break; } default: { offset += (len - 1); break; } } } // Check if Uart is contained in the uuids boolean isUart = false; for (UUID uuid : uuids) { if (uuid.toString().equalsIgnoreCase(UartInterfaceActivity.UUID_SERVICE)) { isUart = true; break; } } if (isUart) { deviceData.type = BluetoothDeviceData.kType_Uart; } } deviceData.uuids = uuids; }
From source file:org.openintents.safe.CryptoHelper.java
/** * Unencrypt a file previously encrypted with * encryptFileWithSessionKey()./*from w w w . j a v a 2s .c om*/ * * @param is a stream to read from * @param os where to write the decrypted stream * @return True if successful, otherwise false. * @throws Exception * @author Peli */ public boolean decryptStreamWithSessionKey(InputStream is, OutputStream os) throws CryptoHelperException { if (debug) { Log.d(TAG, "decryptStreamWithSessionKey"); } status = false; // assume failure if (password == null) { String msg = "Must call setPassword before running decrypt."; throw new CryptoHelperException(msg); } try { int numReadTotal = 0; int numRead = 0; byte[] byteCipherVersion = new byte[1]; while ((numRead = is.read(byteCipherVersion, numRead, byteCipherVersion.length - numRead)) >= 0 && numReadTotal < byteCipherVersion.length) { if (debug) { Log.d(TAG, "read bytes: " + numRead); } numReadTotal += numRead; } String cipherVersion = new String(byteCipherVersion); byte[] byteCipherSessionKey = null; // Split cipher into session key and text try { if (debug) { Log.d(TAG, "cipherVersion : " + cipherVersion); } if (cipherVersion.equals("A")) { numRead = 0; numReadTotal = 0; byteCipherSessionKey = new byte[48]; // Read the first few bytes that contain the encrypted key while ((numRead = is.read(byteCipherSessionKey, numRead, byteCipherSessionKey.length - numRead)) >= 0 && numReadTotal < byteCipherSessionKey.length) { if (debug) { Log.d(TAG, "read bytes sessionKey: " + numRead); } numReadTotal += numRead; } } else { Log.e(TAG, "Unknown cipher version" + cipherVersion); return false; } } catch (IndexOutOfBoundsException e) { Log.e(TAG, "Invalid ciphertext (with session key)"); return false; } // Decrypt the session key byte[] byteSessionKey = {}; try { pbeCipher.init(Cipher.DECRYPT_MODE, pbeKey, pbeParamSpec); byteSessionKey = pbeCipher.doFinal(byteCipherSessionKey); status = true; } catch (IllegalBlockSizeException e) { Log.e(TAG, "decrypt(): " + e.toString()); } catch (BadPaddingException e) { Log.e(TAG, "decrypt(): " + e.toString()); } catch (InvalidKeyException e) { Log.e(TAG, "decrypt(): " + e.toString()); } catch (InvalidAlgorithmParameterException e) { Log.e(TAG, "decrypt(): " + e.toString()); } // Now decrypt the message Trivium tri = new Trivium(); try { tri.setupKey(Trivium.MODE_DECRYPT, byteSessionKey, 0); tri.setupNonce(byteSessionKey, 10); // Create the byte array to hold the data final int bytesLen = 4096; // buffer length byte[] bytesIn = new byte[bytesLen]; byte[] bytesOut = new byte[bytesLen]; int offset = 0; numRead = 0; while ((numRead = is.read(bytesIn, 0, bytesLen)) >= 0) { tri.process(bytesIn, 0, bytesOut, 0, numRead); os.write(bytesOut, 0, numRead); offset += numRead; } // Ensure all the bytes have been read in if (offset < is.available()) { throw new IOException("Could not completely read file "); } status = true; } catch (ESJException e) { Log.e(TAG, "Error decrypting file", e); } } catch (IOException e) { Log.e(TAG, "IOException", e); } return status; }
From source file:org.openintents.safe.CryptoHelper.java
/** * unencrypt encrypted string previously encrypted with * encryptWithSessionKey()//ww w.j a va 2 s.c o m * * @param ciphertext * @return decrypted String * @throws Exception * @author Peli */ public String decryptWithSessionKey(String ciphertext) throws CryptoHelperException { status = false; // assume failure if (password == null) { String msg = "Must call setPassword before running decrypt."; throw new CryptoHelperException(msg); } if ((ciphertext == null) || (ciphertext == "")) { return ""; } String cipherVersion = null; String cipherSessionKey = null; // Split cipher into session key and text try { cipherVersion = ciphertext.substring(0, 1); if (cipherVersion.equals("A")) { cipherSessionKey = ciphertext.substring(1, 97); // 64 if init(128) had been chosen ciphertext = ciphertext.substring(97); } else { Log.e(TAG, "Unknown cipher version" + cipherVersion); return ""; } } catch (IndexOutOfBoundsException e) { Log.e(TAG, "Invalid ciphertext (with session key)"); return ""; } // Decrypt the session key byte[] byteCipherSessionKey = hexStringToBytes(cipherSessionKey); byte[] byteSessionKey = {}; try { pbeCipher.init(Cipher.DECRYPT_MODE, pbeKey, pbeParamSpec); byteSessionKey = pbeCipher.doFinal(byteCipherSessionKey); status = true; } catch (IllegalBlockSizeException | BadPaddingException | InvalidAlgorithmParameterException | InvalidKeyException e) { Log.e(TAG, "decrypt(): " + e.toString()); } // Convert the session key into a Pbe key String stringSessionKey = new String(byteSessionKey); PBEKeySpec sessionPbeKeySpec = new PBEKeySpec(stringSessionKey.toCharArray()); SecretKey sessionPbeKey = null; try { sessionPbeKey = keyFac.generateSecret(sessionPbeKeySpec); } catch (InvalidKeySpecException e) { Log.e(TAG, "setPassword(): " + e.toString()); } // Use the session key to decrypt the text byte[] byteCiphertext = hexStringToBytes(ciphertext); byte[] plaintext = {}; try { pbeCipher.init(Cipher.DECRYPT_MODE, sessionPbeKey, pbeParamSpec); plaintext = pbeCipher.doFinal(byteCiphertext); status = true; } catch (IllegalBlockSizeException | BadPaddingException | InvalidAlgorithmParameterException | InvalidKeyException e) { Log.e(TAG, "decrypt(): " + e.toString()); } return new String(plaintext); }
From source file:com.adafruit.bluefruit.le.connect.app.MainActivity.java
private void decodeScanRecords(BluetoothDeviceData deviceData) { // based on http://stackoverflow.com/questions/24003777/read-advertisement-packet-in-android final byte[] scanRecord = deviceData.scanRecord; ArrayList<UUID> uuids = new ArrayList<>(); byte[] advertisedData = Arrays.copyOf(scanRecord, scanRecord.length); int offset = 0; deviceData.type = BluetoothDeviceData.kType_Unknown; // Check if is an iBeacon ( 0x02, 0x0x1, a flag byte, 0x1A, 0xFF, manufacturer (2bytes), 0x02, 0x15) final boolean isBeacon = advertisedData[0] == 0x02 && advertisedData[1] == 0x01 && advertisedData[3] == 0x1A && advertisedData[4] == (byte) 0xFF && advertisedData[7] == 0x02 && advertisedData[8] == 0x15; // Check if is an URIBeacon final byte[] kUriBeaconPrefix = { 0x03, 0x03, (byte) 0xD8, (byte) 0xFE }; final boolean isUriBeacon = Arrays.equals(Arrays.copyOf(scanRecord, kUriBeaconPrefix.length), kUriBeaconPrefix) && advertisedData[5] == 0x16 && advertisedData[6] == kUriBeaconPrefix[2] && advertisedData[7] == kUriBeaconPrefix[3]; if (isBeacon) { deviceData.type = BluetoothDeviceData.kType_Beacon; // Read uuid offset = 9;//from w w w . j av a 2s .c o m UUID uuid = BleUtils.getUuidFromByteArrayBigEndian(Arrays.copyOfRange(scanRecord, offset, offset + 16)); uuids.add(uuid); offset += 16; // Skip major minor offset += 2 * 2; // major, minor // Read txpower final int txPower = advertisedData[offset++]; deviceData.txPower = txPower; } else if (isUriBeacon) { deviceData.type = BluetoothDeviceData.kType_UriBeacon; // Read txpower final int txPower = advertisedData[9]; deviceData.txPower = txPower; } else { // Read standard advertising packet while (offset < advertisedData.length - 2) { // Length int len = advertisedData[offset++]; if (len == 0) break; // Type int type = advertisedData[offset++]; if (type == 0) break; // Data // Log.d(TAG, "record -> lenght: " + length + " type:" + type + " data" + data); switch (type) { case 0x02: // Partial list of 16-bit UUIDs case 0x03: { // Complete list of 16-bit UUIDs while (len > 1) { int uuid16 = advertisedData[offset++] & 0xFF; uuid16 |= (advertisedData[offset++] << 8); len -= 2; uuids.add(UUID.fromString(String.format("%08x-0000-1000-8000-00805f9b34fb", uuid16))); } break; } case 0x06: // Partial list of 128-bit UUIDs case 0x07: { // Complete list of 128-bit UUIDs while (len >= 16) { try { // Wrap the advertised bits and order them. UUID uuid = BleUtils.getUuidFromByteArraLittleEndian( Arrays.copyOfRange(advertisedData, offset, offset + 16)); uuids.add(uuid); } catch (IndexOutOfBoundsException e) { Log.e(TAG, "BlueToothDeviceFilter.parseUUID: " + e.toString()); } finally { // Move the offset to read the next uuid. offset += 16; len -= 16; } } break; } case 0x09: { byte[] nameBytes = new byte[len - 1]; for (int i = 0; i < len - 1; i++) { nameBytes[i] = advertisedData[offset++]; } String name = null; try { name = new String(nameBytes, "utf-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } deviceData.advertisedName = name; break; } case 0x0A: { // TX Power final int txPower = advertisedData[offset++]; deviceData.txPower = txPower; break; } default: { offset += (len - 1); break; } } } // Check if Uart is contained in the uuids boolean isUart = false; for (UUID uuid : uuids) { if (uuid.toString().equalsIgnoreCase(UartInterfaceActivity.UUID_SERVICE)) { isUart = true; break; } } if (isUart) { deviceData.type = BluetoothDeviceData.kType_Uart; } } deviceData.uuids = uuids; }
From source file:ffx.algorithms.RotamerOptimization.java
/** * Calculates the distance matrix; residue-residue distance is defined as * the shortest atom-atom distance in any possible rotamer-rotamer pair if * the residues are neighbors (central atom-central atom distances are * within a cutoff); else, distances are set to a default of * Double.MAX_VALUE./*from www . j a v a2 s . com*/ * * The intent of using a neighbor list is to avoid tediously searching * rotamer- rotamer pairs when two residues are so far apart we will never * need the exact distance. We use the distance matrix for adding residues * to the sliding window and determining whether to set 3-body energy to * 0.0. If the central atoms are too distant from each other, we can safely * assume no atoms will ever be close enough for addition to sliding window * or to cause explicit calculation of 3-body energy. */ private void distanceMatrix() { distanceMatrix = new double[numResidues - 1][][][]; long numDistances = 0L; for (int i = 0; i < (numResidues - 1); i++) { Residue residuei = allResiduesArray[i]; int lengthRi; try { if (checkIfForced(residuei)) { lengthRi = 1; } else { lengthRi = residuei.getRotamers(library).length; } } catch (IndexOutOfBoundsException ex) { if (useForcedResidues) { logger.warning(ex.toString()); } else { logIfMaster(String.format(" Non-forced Residue i %s has null rotamers.", residuei.toString()), Level.WARNING); } continue; } distanceMatrix[i] = new double[lengthRi][][]; for (int ri = 0; ri < lengthRi; ri++) { distanceMatrix[i][ri] = new double[numResidues][]; for (int j = (i + 1); j < numResidues; j++) { Residue residuej = allResiduesArray[j]; int lengthRj; try { if (checkIfForced(residuej)) { lengthRj = 1; } else { lengthRj = residuej.getRotamers(library).length; } } catch (IndexOutOfBoundsException ex) { if (useForcedResidues) { logger.warning(ex.toString()); } else { logIfMaster(String.format(" Residue j %s has null rotamers.", residuej.toString())); } continue; } distanceMatrix[i][ri][j] = new double[lengthRj]; numDistances += lengthRj; if (!lazyMatrix) { fill(distanceMatrix[i][ri][j], Double.MAX_VALUE); } else { fill(distanceMatrix[i][ri][j], -1.0); } } } } logger.info(String.format(" Number of pairwise distances: %d", numDistances)); if (!lazyMatrix) { //double orig[][][] = storeCoordinates(allResiduesList); ResidueState[] orig = ResidueState.storeAllCoordinates(allResiduesList); int nMultiRes = 0; /** * Build a list that contains one atom from each Residues: CA from * amino acids, C1 from nucleic acids, or the first atom otherwise. */ Atom atoms[] = new Atom[numResidues]; for (int i = 0; i < numResidues; i++) { Residue residuei = allResiduesArray[i]; atoms[i] = residuei.getReferenceAtom(); if (residuei instanceof MultiResidue) { ++nMultiRes; } } /** * Use of the pre-existing ParallelTeam causes a conflict when * MultiResidues must re-init the force field. Temporary solution * for sequence optimization: if > 1 residue optimized, run on only * one thread. */ int nThreads = 1; if (molecularAssembly.getPotentialEnergy().getParallelTeam() != null) { nThreads = (nMultiRes > 1) ? 1 : molecularAssembly.getPotentialEnergy().getParallelTeam().getThreadCount(); } else { // Suggested: nThreads = (nMultiRes > 1) ? 1 : ParallelTeam.getDefaultThreadCount(); nThreads = 16; } ParallelTeam parallelTeam = new ParallelTeam(nThreads); Crystal crystal = molecularAssembly.getCrystal(); int nSymm = crystal.spaceGroup.getNumberOfSymOps(); logger.info("\n Computing Residue Distance Matrix"); NeighborList neighborList = new NeighborList(null, crystal, atoms, distance + 25.0, 0.0, parallelTeam); // Expand coordinates double xyz[][] = new double[nSymm][3 * numResidues]; double in[] = new double[3]; double out[] = new double[3]; for (int iSymOp = 0; iSymOp < nSymm; iSymOp++) { SymOp symOp = crystal.spaceGroup.getSymOp(iSymOp); for (int i = 0; i < numResidues; i++) { int i3 = i * 3; int iX = i3 + 0; int iY = i3 + 1; int iZ = i3 + 2; Atom atom = atoms[i]; in[0] = atom.getX(); in[1] = atom.getY(); in[2] = atom.getZ(); crystal.applySymOp(in, out, symOp); xyz[iSymOp][iX] = out[0]; xyz[iSymOp][iY] = out[1]; xyz[iSymOp][iZ] = out[2]; } } // Build the residue neighbor-list. int lists[][][] = new int[nSymm][numResidues][]; boolean use[] = new boolean[numResidues]; fill(use, true); boolean forceRebuild = true; boolean printLists = false; long neighborTime = -System.nanoTime(); neighborList.buildList(xyz, lists, use, forceRebuild, printLists); neighborTime += System.nanoTime(); logger.info(String.format(" Built residue neighbor list: %8.3f sec", neighborTime * 1.0e-9)); DistanceRegion distanceRegion = new DistanceRegion(parallelTeam.getThreadCount(), numResidues, crystal, lists, neighborList.getPairwiseSchedule()); long parallelTime = -System.nanoTime(); try { parallelTeam.execute(distanceRegion); } catch (Exception e) { String message = " Exception compting residue distance matrix."; logger.log(Level.SEVERE, message, e); } parallelTime += System.nanoTime(); logger.info( String.format(" Pairwise distance matrix: %8.3f sec\n", parallelTime * 1.0e-9)); ResidueState.revertAllCoordinates(allResiduesList, orig); try { parallelTeam.shutdown(); } catch (Exception ex) { logger.warning(String.format(" Exception shutting down parallel team for the distance matrix: %s", ex.toString())); } } }