source/000755 000000000001165162413600057715ustar source/.classpath000644 000000004601165151334200077500ustar source/.project000644 000000005571144714247600074540ustar JGromacs org.eclipse.jdt.core.javabuilder org.eclipse.jdt.core.javanature source/copyright.txt000644 000000023631153322446400105450ustar JGromacs v1.0. is written by Marton Munz and Philip C Biggin Copyright (c) University of Oxford, United Kingdom visit http://sbcb.bioch.ox.ac.uk/jgromacs/ JGromacs v1.0 is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. JGromacs v1.0. is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with JGromacs v1.0. If not, see . JGromacs v1.0. includes the Java linear algebra package JAMA which has the following Copyright Notice: JAMA is a cooperative product of The MathWorks and the National Institute of Standards and Technology (NIST) which has been released to the public domain. Neither The MathWorks nor NIST assumes any responsibility whatsoever for its use by other parties, and makes no guarantees, expressed or implied, about its quality, reliability, or any other characteristic. source/jama/000755 000000000001165162413600067015ustar source/jama/CholeskyDecomposition.java000644 000000131751144672355400140770ustar package jama; /** Cholesky Decomposition.

For a symmetric, positive definite matrix A, the Cholesky decomposition is an lower triangular matrix L so that A = L*L'.

If the matrix is not symmetric or positive definite, the constructor returns a partial decomposition and sets an internal flag that may be queried by the isSPD() method. */ public class CholeskyDecomposition implements java.io.Serializable { /* ------------------------ Class variables * ------------------------ */ /** Array for internal storage of decomposition. @serial internal array storage. */ private double[][] L; /** Row and column dimension (square matrix). @serial matrix dimension. */ private int n; /** Symmetric and positive definite flag. @serial is symmetric and positive definite flag. */ private boolean isspd; /* ------------------------ Constructor * ------------------------ */ /** Cholesky algorithm for symmetric and positive definite matrix. @param A Square, symmetric matrix. @return Structure to access L and isspd flag. */ public CholeskyDecomposition (Matrix Arg) { // Initialize. double[][] A = Arg.getArray(); n = Arg.getRowDimension(); L = new double[n][n]; isspd = (Arg.getColumnDimension() == n); // Main loop. for (int j = 0; j < n; j++) { double[] Lrowj = L[j]; double d = 0.0; for (int k = 0; k < j; k++) { double[] Lrowk = L[k]; double s = 0.0; for (int i = 0; i < k; i++) { s += Lrowk[i]*Lrowj[i]; } Lrowj[k] = s = (A[j][k] - s)/L[k][k]; d = d + s*s; isspd = isspd & (A[k][j] == A[j][k]); } d = A[j][j] - d; isspd = isspd & (d > 0.0); L[j][j] = Math.sqrt(Math.max(d,0.0)); for (int k = j+1; k < n; k++) { L[j][k] = 0.0; } } } /* ------------------------ Temporary, experimental code. * ------------------------ *\ \** Right Triangular Cholesky Decomposition.

For a symmetric, positive definite matrix A, the Right Cholesky decomposition is an upper triangular matrix R so that A = R'*R. This constructor computes R with the Fortran inspired column oriented algorithm used in LINPACK and MATLAB. In Java, we suspect a row oriented, lower triangular decomposition is faster. We have temporarily included this constructor here until timing experiments confirm this suspicion. *\ \** Array for internal storage of right triangular decomposition. **\ private transient double[][] R; \** Cholesky algorithm for symmetric and positive definite matrix. @param A Square, symmetric matrix. @param rightflag Actual value ignored. @return Structure to access R and isspd flag. *\ public CholeskyDecomposition (Matrix Arg, int rightflag) { // Initialize. double[][] A = Arg.getArray(); n = Arg.getColumnDimension(); R = new double[n][n]; isspd = (Arg.getColumnDimension() == n); // Main loop. for (int j = 0; j < n; j++) { double d = 0.0; for (int k = 0; k < j; k++) { double s = A[k][j]; for (int i = 0; i < k; i++) { s = s - R[i][k]*R[i][j]; } R[k][j] = s = s/R[k][k]; d = d + s*s; isspd = isspd & (A[k][j] == A[j][k]); } d = A[j][j] - d; isspd = isspd & (d > 0.0); R[j][j] = Math.sqrt(Math.max(d,0.0)); for (int k = j+1; k < n; k++) { R[k][j] = 0.0; } } } \** Return upper triangular factor. @return R *\ public Matrix getR () { return new Matrix(R,n,n); } \* ------------------------ End of temporary code. * ------------------------ */ /* ------------------------ Public Methods * ------------------------ */ /** Is the matrix symmetric and positive definite? @return true if A is symmetric and positive definite. */ public boolean isSPD () { return isspd; } /** Return triangular factor. @return L */ public Matrix getL () { return new Matrix(L,n,n); } /** Solve A*X = B @param B A Matrix with as many rows as A and any number of columns. @return X so that L*L'*X = B @exception IllegalArgumentException Matrix row dimensions must agree. @exception RuntimeException Matrix is not symmetric positive definite. */ public Matrix solve (Matrix B) { if (B.getRowDimension() != n) { throw new IllegalArgumentException("Matrix row dimensions must agree."); } if (!isspd) { throw new RuntimeException("Matrix is not symmetric positive definite."); } // Copy right hand side. double[][] X = B.getArrayCopy(); int nx = B.getColumnDimension(); // Solve L*Y = B; for (int k = 0; k < n; k++) { for (int j = 0; j < nx; j++) { for (int i = 0; i < k ; i++) { X[k][j] -= X[i][j]*L[k][i]; } X[k][j] /= L[k][k]; } } // Solve L'*X = Y; for (int k = n-1; k >= 0; k--) { for (int j = 0; j < nx; j++) { for (int i = k+1; i < n ; i++) { X[k][j] -= X[i][j]*L[i][k]; } X[k][j] /= L[k][k]; } } return new Matrix(X,n,nx); } } source/jama/EigenvalueDecomposition.java000644 000000661701144672364600144070ustar package jama; import jama.util.*; /** Eigenvalues and eigenvectors of a real matrix.

If A is symmetric, then A = V*D*V' where the eigenvalue matrix D is diagonal and the eigenvector matrix V is orthogonal. I.e. A = V.times(D.times(V.transpose())) and V.times(V.transpose()) equals the identity matrix.

If A is not symmetric, then the eigenvalue matrix D is block diagonal with the real eigenvalues in 1-by-1 blocks and any complex eigenvalues, lambda + i*mu, in 2-by-2 blocks, [lambda, mu; -mu, lambda]. The columns of V represent the eigenvectors in the sense that A*V = V*D, i.e. A.times(V) equals V.times(D). The matrix V may be badly conditioned, or even singular, so the validity of the equation A = V*D*inverse(V) depends upon V.cond(). **/ public class EigenvalueDecomposition implements java.io.Serializable { /* ------------------------ Class variables * ------------------------ */ /** Row and column dimension (square matrix). @serial matrix dimension. */ private int n; /** Symmetry flag. @serial internal symmetry flag. */ private boolean issymmetric; /** Arrays for internal storage of eigenvalues. @serial internal storage of eigenvalues. */ private double[] d, e; /** Array for internal storage of eigenvectors. @serial internal storage of eigenvectors. */ private double[][] V; /** Array for internal storage of nonsymmetric Hessenberg form. @serial internal storage of nonsymmetric Hessenberg form. */ private double[][] H; /** Working storage for nonsymmetric algorithm. @serial working storage for nonsymmetric algorithm. */ private double[] ort; /* ------------------------ Private Methods * ------------------------ */ // Symmetric Householder reduction to tridiagonal form. private void tred2 () { // This is derived from the Algol procedures tred2 by // Bowdler, Martin, Reinsch, and Wilkinson, Handbook for // Auto. Comp., Vol.ii-Linear Algebra, and the corresponding // Fortran subroutine in EISPACK. for (int j = 0; j < n; j++) { d[j] = V[n-1][j]; } // Householder reduction to tridiagonal form. for (int i = n-1; i > 0; i--) { // Scale to avoid under/overflow. double scale = 0.0; double h = 0.0; for (int k = 0; k < i; k++) { scale = scale + Math.abs(d[k]); } if (scale == 0.0) { e[i] = d[i-1]; for (int j = 0; j < i; j++) { d[j] = V[i-1][j]; V[i][j] = 0.0; V[j][i] = 0.0; } } else { // Generate Householder vector. for (int k = 0; k < i; k++) { d[k] /= scale; h += d[k] * d[k]; } double f = d[i-1]; double g = Math.sqrt(h); if (f > 0) { g = -g; } e[i] = scale * g; h = h - f * g; d[i-1] = f - g; for (int j = 0; j < i; j++) { e[j] = 0.0; } // Apply similarity transformation to remaining columns. for (int j = 0; j < i; j++) { f = d[j]; V[j][i] = f; g = e[j] + V[j][j] * f; for (int k = j+1; k <= i-1; k++) { g += V[k][j] * d[k]; e[k] += V[k][j] * f; } e[j] = g; } f = 0.0; for (int j = 0; j < i; j++) { e[j] /= h; f += e[j] * d[j]; } double hh = f / (h + h); for (int j = 0; j < i; j++) { e[j] -= hh * d[j]; } for (int j = 0; j < i; j++) { f = d[j]; g = e[j]; for (int k = j; k <= i-1; k++) { V[k][j] -= (f * e[k] + g * d[k]); } d[j] = V[i-1][j]; V[i][j] = 0.0; } } d[i] = h; } // Accumulate transformations. for (int i = 0; i < n-1; i++) { V[n-1][i] = V[i][i]; V[i][i] = 1.0; double h = d[i+1]; if (h != 0.0) { for (int k = 0; k <= i; k++) { d[k] = V[k][i+1] / h; } for (int j = 0; j <= i; j++) { double g = 0.0; for (int k = 0; k <= i; k++) { g += V[k][i+1] * V[k][j]; } for (int k = 0; k <= i; k++) { V[k][j] -= g * d[k]; } } } for (int k = 0; k <= i; k++) { V[k][i+1] = 0.0; } } for (int j = 0; j < n; j++) { d[j] = V[n-1][j]; V[n-1][j] = 0.0; } V[n-1][n-1] = 1.0; e[0] = 0.0; } // Symmetric tridiagonal QL algorithm. private void tql2 () { // This is derived from the Algol procedures tql2, by // Bowdler, Martin, Reinsch, and Wilkinson, Handbook for // Auto. Comp., Vol.ii-Linear Algebra, and the corresponding // Fortran subroutine in EISPACK. for (int i = 1; i < n; i++) { e[i-1] = e[i]; } e[n-1] = 0.0; double f = 0.0; double tst1 = 0.0; double eps = Math.pow(2.0,-52.0); for (int l = 0; l < n; l++) { // Find small subdiagonal element tst1 = Math.max(tst1,Math.abs(d[l]) + Math.abs(e[l])); int m = l; while (m < n) { if (Math.abs(e[m]) <= eps*tst1) { break; } m++; } // If m == l, d[l] is an eigenvalue, // otherwise, iterate. if (m > l) { int iter = 0; do { iter = iter + 1; // (Could check iteration count here.) // Compute implicit shift double g = d[l]; double p = (d[l+1] - g) / (2.0 * e[l]); double r = Maths.hypot(p,1.0); if (p < 0) { r = -r; } d[l] = e[l] / (p + r); d[l+1] = e[l] * (p + r); double dl1 = d[l+1]; double h = g - d[l]; for (int i = l+2; i < n; i++) { d[i] -= h; } f = f + h; // Implicit QL transformation. p = d[m]; double c = 1.0; double c2 = c; double c3 = c; double el1 = e[l+1]; double s = 0.0; double s2 = 0.0; for (int i = m-1; i >= l; i--) { c3 = c2; c2 = c; s2 = s; g = c * e[i]; h = c * p; r = Maths.hypot(p,e[i]); e[i+1] = s * r; s = e[i] / r; c = p / r; p = c * d[i] - s * g; d[i+1] = h + s * (c * g + s * d[i]); // Accumulate transformation. for (int k = 0; k < n; k++) { h = V[k][i+1]; V[k][i+1] = s * V[k][i] + c * h; V[k][i] = c * V[k][i] - s * h; } } p = -s * s2 * c3 * el1 * e[l] / dl1; e[l] = s * p; d[l] = c * p; // Check for convergence. } while (Math.abs(e[l]) > eps*tst1); } d[l] = d[l] + f; e[l] = 0.0; } // Sort eigenvalues and corresponding vectors. for (int i = 0; i < n-1; i++) { int k = i; double p = d[i]; for (int j = i+1; j < n; j++) { if (d[j] < p) { k = j; p = d[j]; } } if (k != i) { d[k] = d[i]; d[i] = p; for (int j = 0; j < n; j++) { p = V[j][i]; V[j][i] = V[j][k]; V[j][k] = p; } } } } // Nonsymmetric reduction to Hessenberg form. private void orthes () { // This is derived from the Algol procedures orthes and ortran, // by Martin and Wilkinson, Handbook for Auto. Comp., // Vol.ii-Linear Algebra, and the corresponding // Fortran subroutines in EISPACK. int low = 0; int high = n-1; for (int m = low+1; m <= high-1; m++) { // Scale column. double scale = 0.0; for (int i = m; i <= high; i++) { scale = scale + Math.abs(H[i][m-1]); } if (scale != 0.0) { // Compute Householder transformation. double h = 0.0; for (int i = high; i >= m; i--) { ort[i] = H[i][m-1]/scale; h += ort[i] * ort[i]; } double g = Math.sqrt(h); if (ort[m] > 0) { g = -g; } h = h - ort[m] * g; ort[m] = ort[m] - g; // Apply Householder similarity transformation // H = (I-u*u'/h)*H*(I-u*u')/h) for (int j = m; j < n; j++) { double f = 0.0; for (int i = high; i >= m; i--) { f += ort[i]*H[i][j]; } f = f/h; for (int i = m; i <= high; i++) { H[i][j] -= f*ort[i]; } } for (int i = 0; i <= high; i++) { double f = 0.0; for (int j = high; j >= m; j--) { f += ort[j]*H[i][j]; } f = f/h; for (int j = m; j <= high; j++) { H[i][j] -= f*ort[j]; } } ort[m] = scale*ort[m]; H[m][m-1] = scale*g; } } // Accumulate transformations (Algol's ortran). for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { V[i][j] = (i == j ? 1.0 : 0.0); } } for (int m = high-1; m >= low+1; m--) { if (H[m][m-1] != 0.0) { for (int i = m+1; i <= high; i++) { ort[i] = H[i][m-1]; } for (int j = m; j <= high; j++) { double g = 0.0; for (int i = m; i <= high; i++) { g += ort[i] * V[i][j]; } // Double division avoids possible underflow g = (g / ort[m]) / H[m][m-1]; for (int i = m; i <= high; i++) { V[i][j] += g * ort[i]; } } } } } // Complex scalar division. private transient double cdivr, cdivi; private void cdiv(double xr, double xi, double yr, double yi) { double r,d; if (Math.abs(yr) > Math.abs(yi)) { r = yi/yr; d = yr + r*yi; cdivr = (xr + r*xi)/d; cdivi = (xi - r*xr)/d; } else { r = yr/yi; d = yi + r*yr; cdivr = (r*xr + xi)/d; cdivi = (r*xi - xr)/d; } } // Nonsymmetric reduction from Hessenberg to real Schur form. private void hqr2 () { // This is derived from the Algol procedure hqr2, // by Martin and Wilkinson, Handbook for Auto. Comp., // Vol.ii-Linear Algebra, and the corresponding // Fortran subroutine in EISPACK. // Initialize int nn = this.n; int n = nn-1; int low = 0; int high = nn-1; double eps = Math.pow(2.0,-52.0); double exshift = 0.0; double p=0,q=0,r=0,s=0,z=0,t,w,x,y; // Store roots isolated by balanc and compute matrix norm double norm = 0.0; for (int i = 0; i < nn; i++) { if (i < low | i > high) { d[i] = H[i][i]; e[i] = 0.0; } for (int j = Math.max(i-1,0); j < nn; j++) { norm = norm + Math.abs(H[i][j]); } } // Outer loop over eigenvalue index int iter = 0; while (n >= low) { // Look for single small sub-diagonal element int l = n; while (l > low) { s = Math.abs(H[l-1][l-1]) + Math.abs(H[l][l]); if (s == 0.0) { s = norm; } if (Math.abs(H[l][l-1]) < eps * s) { break; } l--; } // Check for convergence // One root found if (l == n) { H[n][n] = H[n][n] + exshift; d[n] = H[n][n]; e[n] = 0.0; n--; iter = 0; // Two roots found } else if (l == n-1) { w = H[n][n-1] * H[n-1][n]; p = (H[n-1][n-1] - H[n][n]) / 2.0; q = p * p + w; z = Math.sqrt(Math.abs(q)); H[n][n] = H[n][n] + exshift; H[n-1][n-1] = H[n-1][n-1] + exshift; x = H[n][n]; // Real pair if (q >= 0) { if (p >= 0) { z = p + z; } else { z = p - z; } d[n-1] = x + z; d[n] = d[n-1]; if (z != 0.0) { d[n] = x - w / z; } e[n-1] = 0.0; e[n] = 0.0; x = H[n][n-1]; s = Math.abs(x) + Math.abs(z); p = x / s; q = z / s; r = Math.sqrt(p * p+q * q); p = p / r; q = q / r; // Row modification for (int j = n-1; j < nn; j++) { z = H[n-1][j]; H[n-1][j] = q * z + p * H[n][j]; H[n][j] = q * H[n][j] - p * z; } // Column modification for (int i = 0; i <= n; i++) { z = H[i][n-1]; H[i][n-1] = q * z + p * H[i][n]; H[i][n] = q * H[i][n] - p * z; } // Accumulate transformations for (int i = low; i <= high; i++) { z = V[i][n-1]; V[i][n-1] = q * z + p * V[i][n]; V[i][n] = q * V[i][n] - p * z; } // Complex pair } else { d[n-1] = x + p; d[n] = x + p; e[n-1] = z; e[n] = -z; } n = n - 2; iter = 0; // No convergence yet } else { // Form shift x = H[n][n]; y = 0.0; w = 0.0; if (l < n) { y = H[n-1][n-1]; w = H[n][n-1] * H[n-1][n]; } // Wilkinson's original ad hoc shift if (iter == 10) { exshift += x; for (int i = low; i <= n; i++) { H[i][i] -= x; } s = Math.abs(H[n][n-1]) + Math.abs(H[n-1][n-2]); x = y = 0.75 * s; w = -0.4375 * s * s; } // MATLAB's new ad hoc shift if (iter == 30) { s = (y - x) / 2.0; s = s * s + w; if (s > 0) { s = Math.sqrt(s); if (y < x) { s = -s; } s = x - w / ((y - x) / 2.0 + s); for (int i = low; i <= n; i++) { H[i][i] -= s; } exshift += s; x = y = w = 0.964; } } iter = iter + 1; // (Could check iteration count here.) // Look for two consecutive small sub-diagonal elements int m = n-2; while (m >= l) { z = H[m][m]; r = x - z; s = y - z; p = (r * s - w) / H[m+1][m] + H[m][m+1]; q = H[m+1][m+1] - z - r - s; r = H[m+2][m+1]; s = Math.abs(p) + Math.abs(q) + Math.abs(r); p = p / s; q = q / s; r = r / s; if (m == l) { break; } if (Math.abs(H[m][m-1]) * (Math.abs(q) + Math.abs(r)) < eps * (Math.abs(p) * (Math.abs(H[m-1][m-1]) + Math.abs(z) + Math.abs(H[m+1][m+1])))) { break; } m--; } for (int i = m+2; i <= n; i++) { H[i][i-2] = 0.0; if (i > m+2) { H[i][i-3] = 0.0; } } // Double QR step involving rows l:n and columns m:n for (int k = m; k <= n-1; k++) { boolean notlast = (k != n-1); if (k != m) { p = H[k][k-1]; q = H[k+1][k-1]; r = (notlast ? H[k+2][k-1] : 0.0); x = Math.abs(p) + Math.abs(q) + Math.abs(r); if (x != 0.0) { p = p / x; q = q / x; r = r / x; } } if (x == 0.0) { break; } s = Math.sqrt(p * p + q * q + r * r); if (p < 0) { s = -s; } if (s != 0) { if (k != m) { H[k][k-1] = -s * x; } else if (l != m) { H[k][k-1] = -H[k][k-1]; } p = p + s; x = p / s; y = q / s; z = r / s; q = q / p; r = r / p; // Row modification for (int j = k; j < nn; j++) { p = H[k][j] + q * H[k+1][j]; if (notlast) { p = p + r * H[k+2][j]; H[k+2][j] = H[k+2][j] - p * z; } H[k][j] = H[k][j] - p * x; H[k+1][j] = H[k+1][j] - p * y; } // Column modification for (int i = 0; i <= Math.min(n,k+3); i++) { p = x * H[i][k] + y * H[i][k+1]; if (notlast) { p = p + z * H[i][k+2]; H[i][k+2] = H[i][k+2] - p * r; } H[i][k] = H[i][k] - p; H[i][k+1] = H[i][k+1] - p * q; } // Accumulate transformations for (int i = low; i <= high; i++) { p = x * V[i][k] + y * V[i][k+1]; if (notlast) { p = p + z * V[i][k+2]; V[i][k+2] = V[i][k+2] - p * r; } V[i][k] = V[i][k] - p; V[i][k+1] = V[i][k+1] - p * q; } } // (s != 0) } // k loop } // check convergence } // while (n >= low) // Backsubstitute to find vectors of upper triangular form if (norm == 0.0) { return; } for (n = nn-1; n >= 0; n--) { p = d[n]; q = e[n]; // Real vector if (q == 0) { int l = n; H[n][n] = 1.0; for (int i = n-1; i >= 0; i--) { w = H[i][i] - p; r = 0.0; for (int j = l; j <= n; j++) { r = r + H[i][j] * H[j][n]; } if (e[i] < 0.0) { z = w; s = r; } else { l = i; if (e[i] == 0.0) { if (w != 0.0) { H[i][n] = -r / w; } else { H[i][n] = -r / (eps * norm); } // Solve real equations } else { x = H[i][i+1]; y = H[i+1][i]; q = (d[i] - p) * (d[i] - p) + e[i] * e[i]; t = (x * s - z * r) / q; H[i][n] = t; if (Math.abs(x) > Math.abs(z)) { H[i+1][n] = (-r - w * t) / x; } else { H[i+1][n] = (-s - y * t) / z; } } // Overflow control t = Math.abs(H[i][n]); if ((eps * t) * t > 1) { for (int j = i; j <= n; j++) { H[j][n] = H[j][n] / t; } } } } // Complex vector } else if (q < 0) { int l = n-1; // Last vector component imaginary so matrix is triangular if (Math.abs(H[n][n-1]) > Math.abs(H[n-1][n])) { H[n-1][n-1] = q / H[n][n-1]; H[n-1][n] = -(H[n][n] - p) / H[n][n-1]; } else { cdiv(0.0,-H[n-1][n],H[n-1][n-1]-p,q); H[n-1][n-1] = cdivr; H[n-1][n] = cdivi; } H[n][n-1] = 0.0; H[n][n] = 1.0; for (int i = n-2; i >= 0; i--) { double ra,sa,vr,vi; ra = 0.0; sa = 0.0; for (int j = l; j <= n; j++) { ra = ra + H[i][j] * H[j][n-1]; sa = sa + H[i][j] * H[j][n]; } w = H[i][i] - p; if (e[i] < 0.0) { z = w; r = ra; s = sa; } else { l = i; if (e[i] == 0) { cdiv(-ra,-sa,w,q); H[i][n-1] = cdivr; H[i][n] = cdivi; } else { // Solve complex equations x = H[i][i+1]; y = H[i+1][i]; vr = (d[i] - p) * (d[i] - p) + e[i] * e[i] - q * q; vi = (d[i] - p) * 2.0 * q; if (vr == 0.0 & vi == 0.0) { vr = eps * norm * (Math.abs(w) + Math.abs(q) + Math.abs(x) + Math.abs(y) + Math.abs(z)); } cdiv(x*r-z*ra+q*sa,x*s-z*sa-q*ra,vr,vi); H[i][n-1] = cdivr; H[i][n] = cdivi; if (Math.abs(x) > (Math.abs(z) + Math.abs(q))) { H[i+1][n-1] = (-ra - w * H[i][n-1] + q * H[i][n]) / x; H[i+1][n] = (-sa - w * H[i][n] - q * H[i][n-1]) / x; } else { cdiv(-r-y*H[i][n-1],-s-y*H[i][n],z,q); H[i+1][n-1] = cdivr; H[i+1][n] = cdivi; } } // Overflow control t = Math.max(Math.abs(H[i][n-1]),Math.abs(H[i][n])); if ((eps * t) * t > 1) { for (int j = i; j <= n; j++) { H[j][n-1] = H[j][n-1] / t; H[j][n] = H[j][n] / t; } } } } } } // Vectors of isolated roots for (int i = 0; i < nn; i++) { if (i < low | i > high) { for (int j = i; j < nn; j++) { V[i][j] = H[i][j]; } } } // Back transformation to get eigenvectors of original matrix for (int j = nn-1; j >= low; j--) { for (int i = low; i <= high; i++) { z = 0.0; for (int k = low; k <= Math.min(j,high); k++) { z = z + V[i][k] * H[k][j]; } V[i][j] = z; } } } /* ------------------------ Constructor * ------------------------ */ /** Check for symmetry, then construct the eigenvalue decomposition @param A Square matrix @return Structure to access D and V. */ public EigenvalueDecomposition (Matrix Arg) { double[][] A = Arg.getArray(); n = Arg.getColumnDimension(); V = new double[n][n]; d = new double[n]; e = new double[n]; issymmetric = true; for (int j = 0; (j < n) & issymmetric; j++) { for (int i = 0; (i < n) & issymmetric; i++) { issymmetric = (A[i][j] == A[j][i]); } } if (issymmetric) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { V[i][j] = A[i][j]; } } // Tridiagonalize. tred2(); // Diagonalize. tql2(); } else { H = new double[n][n]; ort = new double[n]; for (int j = 0; j < n; j++) { for (int i = 0; i < n; i++) { H[i][j] = A[i][j]; } } // Reduce to Hessenberg form. orthes(); // Reduce Hessenberg to real Schur form. hqr2(); } } /* ------------------------ Public Methods * ------------------------ */ /** Return the eigenvector matrix @return V */ public Matrix getV () { return new Matrix(V,n,n); } /** Return the real parts of the eigenvalues @return real(diag(D)) */ public double[] getRealEigenvalues () { return d; } /** Return the imaginary parts of the eigenvalues @return imag(diag(D)) */ public double[] getImagEigenvalues () { return e; } /** Return the block diagonal eigenvalue matrix @return D */ public Matrix getD () { Matrix X = new Matrix(n,n); double[][] D = X.getArray(); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { D[i][j] = 0.0; } D[i][i] = d[i]; if (e[i] > 0) { D[i][i+1] = e[i]; } else if (e[i] < 0) { D[i][i-1] = e[i]; } } return X; } } source/jama/LUDecomposition.java000644 000000204431144672360000126220ustar package jama; /** LU Decomposition.

For an m-by-n matrix A with m >= n, the LU decomposition is an m-by-n unit lower triangular matrix L, an n-by-n upper triangular matrix U, and a permutation vector piv of length m so that A(piv,:) = L*U. If m < n, then L is m-by-m and U is m-by-n.

The LU decompostion with pivoting always exists, even if the matrix is singular, so the constructor will never fail. The primary use of the LU decomposition is in the solution of square systems of simultaneous linear equations. This will fail if isNonsingular() returns false. */ public class LUDecomposition implements java.io.Serializable { /* ------------------------ Class variables * ------------------------ */ /** Array for internal storage of decomposition. @serial internal array storage. */ private double[][] LU; /** Row and column dimensions, and pivot sign. @serial column dimension. @serial row dimension. @serial pivot sign. */ private int m, n, pivsign; /** Internal storage of pivot vector. @serial pivot vector. */ private int[] piv; /* ------------------------ Constructor * ------------------------ */ /** LU Decomposition @param A Rectangular matrix @return Structure to access L, U and piv. */ public LUDecomposition (Matrix A) { // Use a "left-looking", dot-product, Crout/Doolittle algorithm. LU = A.getArrayCopy(); m = A.getRowDimension(); n = A.getColumnDimension(); piv = new int[m]; for (int i = 0; i < m; i++) { piv[i] = i; } pivsign = 1; double[] LUrowi; double[] LUcolj = new double[m]; // Outer loop. for (int j = 0; j < n; j++) { // Make a copy of the j-th column to localize references. for (int i = 0; i < m; i++) { LUcolj[i] = LU[i][j]; } // Apply previous transformations. for (int i = 0; i < m; i++) { LUrowi = LU[i]; // Most of the time is spent in the following dot product. int kmax = Math.min(i,j); double s = 0.0; for (int k = 0; k < kmax; k++) { s += LUrowi[k]*LUcolj[k]; } LUrowi[j] = LUcolj[i] -= s; } // Find pivot and exchange if necessary. int p = j; for (int i = j+1; i < m; i++) { if (Math.abs(LUcolj[i]) > Math.abs(LUcolj[p])) { p = i; } } if (p != j) { for (int k = 0; k < n; k++) { double t = LU[p][k]; LU[p][k] = LU[j][k]; LU[j][k] = t; } int k = piv[p]; piv[p] = piv[j]; piv[j] = k; pivsign = -pivsign; } // Compute multipliers. if (j < m & LU[j][j] != 0.0) { for (int i = j+1; i < m; i++) { LU[i][j] /= LU[j][j]; } } } } /* ------------------------ Temporary, experimental code. ------------------------ *\ \** LU Decomposition, computed by Gaussian elimination.

This constructor computes L and U with the "daxpy"-based elimination algorithm used in LINPACK and MATLAB. In Java, we suspect the dot-product, Crout algorithm will be faster. We have temporarily included this constructor until timing experiments confirm this suspicion.

@param A Rectangular matrix @param linpackflag Use Gaussian elimination. Actual value ignored. @return Structure to access L, U and piv. *\ public LUDecomposition (Matrix A, int linpackflag) { // Initialize. LU = A.getArrayCopy(); m = A.getRowDimension(); n = A.getColumnDimension(); piv = new int[m]; for (int i = 0; i < m; i++) { piv[i] = i; } pivsign = 1; // Main loop. for (int k = 0; k < n; k++) { // Find pivot. int p = k; for (int i = k+1; i < m; i++) { if (Math.abs(LU[i][k]) > Math.abs(LU[p][k])) { p = i; } } // Exchange if necessary. if (p != k) { for (int j = 0; j < n; j++) { double t = LU[p][j]; LU[p][j] = LU[k][j]; LU[k][j] = t; } int t = piv[p]; piv[p] = piv[k]; piv[k] = t; pivsign = -pivsign; } // Compute multipliers and eliminate k-th column. if (LU[k][k] != 0.0) { for (int i = k+1; i < m; i++) { LU[i][k] /= LU[k][k]; for (int j = k+1; j < n; j++) { LU[i][j] -= LU[i][k]*LU[k][j]; } } } } } \* ------------------------ End of temporary code. * ------------------------ */ /* ------------------------ Public Methods * ------------------------ */ /** Is the matrix nonsingular? @return true if U, and hence A, is nonsingular. */ public boolean isNonsingular () { for (int j = 0; j < n; j++) { if (LU[j][j] == 0) return false; } return true; } /** Return lower triangular factor @return L */ public Matrix getL () { Matrix X = new Matrix(m,n); double[][] L = X.getArray(); for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (i > j) { L[i][j] = LU[i][j]; } else if (i == j) { L[i][j] = 1.0; } else { L[i][j] = 0.0; } } } return X; } /** Return upper triangular factor @return U */ public Matrix getU () { Matrix X = new Matrix(n,n); double[][] U = X.getArray(); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (i <= j) { U[i][j] = LU[i][j]; } else { U[i][j] = 0.0; } } } return X; } /** Return pivot permutation vector @return piv */ public int[] getPivot () { int[] p = new int[m]; for (int i = 0; i < m; i++) { p[i] = piv[i]; } return p; } /** Return pivot permutation vector as a one-dimensional double array @return (double) piv */ public double[] getDoublePivot () { double[] vals = new double[m]; for (int i = 0; i < m; i++) { vals[i] = (double) piv[i]; } return vals; } /** Determinant @return det(A) @exception IllegalArgumentException Matrix must be square */ public double det () { if (m != n) { throw new IllegalArgumentException("Matrix must be square."); } double d = (double) pivsign; for (int j = 0; j < n; j++) { d *= LU[j][j]; } return d; } /** Solve A*X = B @param B A Matrix with as many rows as A and any number of columns. @return X so that L*U*X = B(piv,:) @exception IllegalArgumentException Matrix row dimensions must agree. @exception RuntimeException Matrix is singular. */ public Matrix solve (Matrix B) { if (B.getRowDimension() != m) { throw new IllegalArgumentException("Matrix row dimensions must agree."); } if (!this.isNonsingular()) { throw new RuntimeException("Matrix is singular."); } // Copy right hand side with pivoting int nx = B.getColumnDimension(); Matrix Xmat = B.getMatrix(piv,0,nx-1); double[][] X = Xmat.getArray(); // Solve L*Y = B(piv,:) for (int k = 0; k < n; k++) { for (int i = k+1; i < n; i++) { for (int j = 0; j < nx; j++) { X[i][j] -= X[k][j]*LU[i][k]; } } } // Solve U*X = Y; for (int k = n-1; k >= 0; k--) { for (int j = 0; j < nx; j++) { X[k][j] /= LU[k][k]; } for (int i = 0; i < k; i++) { for (int j = 0; j < nx; j++) { X[i][j] -= X[k][j]*LU[i][k]; } } } return Xmat; } } source/jama/Matrix.java000644 000000722201144672362400110170ustar package jama; import java.text.NumberFormat; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.util.Locale; import java.text.FieldPosition; import java.io.PrintWriter; import java.io.BufferedReader; import java.io.StreamTokenizer; import jama.util.*; /** Jama = Java Matrix class.

The Java Matrix Class provides the fundamental operations of numerical linear algebra. Various constructors create Matrices from two dimensional arrays of double precision floating point numbers. Various "gets" and "sets" provide access to submatrices and matrix elements. Several methods implement basic matrix arithmetic, including matrix addition and multiplication, matrix norms, and element-by-element array operations. Methods for reading and printing matrices are also included. All the operations in this version of the Matrix Class involve real matrices. Complex matrices may be handled in a future version.

Five fundamental matrix decompositions, which consist of pairs or triples of matrices, permutation vectors, and the like, produce results in five decomposition classes. These decompositions are accessed by the Matrix class to compute solutions of simultaneous linear equations, determinants, inverses and other matrix functions. The five decompositions are:

Example of use:

Solve a linear system A x = b and compute the residual norm, ||b - A x||.

      double[][] vals = {{1.,2.,3},{4.,5.,6.},{7.,8.,10.}};
      Matrix A = new Matrix(vals);
      Matrix b = Matrix.random(3,1);
      Matrix x = A.solve(b);
      Matrix r = A.times(x).minus(b);
      double rnorm = r.normInf();
@author The MathWorks, Inc. and the National Institute of Standards and Technology. @version 5 August 1998 */ public class Matrix implements Cloneable, java.io.Serializable { /* ------------------------ Class variables * ------------------------ */ /** Array for internal storage of elements. @serial internal array storage. */ private double[][] A; /** Row and column dimensions. @serial row dimension. @serial column dimension. */ private int m, n; /* ------------------------ Constructors * ------------------------ */ /** Construct an m-by-n matrix of zeros. @param m Number of rows. @param n Number of colums. */ public Matrix (int m, int n) { this.m = m; this.n = n; A = new double[m][n]; } /** Construct an m-by-n constant matrix. @param m Number of rows. @param n Number of colums. @param s Fill the matrix with this scalar value. */ public Matrix (int m, int n, double s) { this.m = m; this.n = n; A = new double[m][n]; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { A[i][j] = s; } } } /** Construct a matrix from a 2-D array. @param A Two-dimensional array of doubles. @exception IllegalArgumentException All rows must have the same length @see #constructWithCopy */ public Matrix (double[][] A) { m = A.length; n = A[0].length; for (int i = 0; i < m; i++) { if (A[i].length != n) { throw new IllegalArgumentException("All rows must have the same length."); } } this.A = A; } /** Construct a matrix quickly without checking arguments. @param A Two-dimensional array of doubles. @param m Number of rows. @param n Number of colums. */ public Matrix (double[][] A, int m, int n) { this.A = A; this.m = m; this.n = n; } /** Construct a matrix from a one-dimensional packed array @param vals One-dimensional array of doubles, packed by columns (ala Fortran). @param m Number of rows. @exception IllegalArgumentException Array length must be a multiple of m. */ public Matrix (double vals[], int m) { this.m = m; n = (m != 0 ? vals.length/m : 0); if (m*n != vals.length) { throw new IllegalArgumentException("Array length must be a multiple of m."); } A = new double[m][n]; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { A[i][j] = vals[i+j*m]; } } } /* ------------------------ Public Methods * ------------------------ */ /** Construct a matrix from a copy of a 2-D array. @param A Two-dimensional array of doubles. @exception IllegalArgumentException All rows must have the same length */ public static Matrix constructWithCopy(double[][] A) { int m = A.length; int n = A[0].length; Matrix X = new Matrix(m,n); double[][] C = X.getArray(); for (int i = 0; i < m; i++) { if (A[i].length != n) { throw new IllegalArgumentException ("All rows must have the same length."); } for (int j = 0; j < n; j++) { C[i][j] = A[i][j]; } } return X; } /** Make a deep copy of a matrix */ public Matrix copy () { Matrix X = new Matrix(m,n); double[][] C = X.getArray(); for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { C[i][j] = A[i][j]; } } return X; } /** Clone the Matrix object. */ public Object clone () { return this.copy(); } /** Access the internal two-dimensional array. @return Pointer to the two-dimensional array of matrix elements. */ public double[][] getArray () { return A; } /** Copy the internal two-dimensional array. @return Two-dimensional array copy of matrix elements. */ public double[][] getArrayCopy () { double[][] C = new double[m][n]; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { C[i][j] = A[i][j]; } } return C; } /** Make a one-dimensional column packed copy of the internal array. @return Matrix elements packed in a one-dimensional array by columns. */ public double[] getColumnPackedCopy () { double[] vals = new double[m*n]; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { vals[i+j*m] = A[i][j]; } } return vals; } /** Make a one-dimensional row packed copy of the internal array. @return Matrix elements packed in a one-dimensional array by rows. */ public double[] getRowPackedCopy () { double[] vals = new double[m*n]; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { vals[i*n+j] = A[i][j]; } } return vals; } /** Get row dimension. @return m, the number of rows. */ public int getRowDimension () { return m; } /** Get column dimension. @return n, the number of columns. */ public int getColumnDimension () { return n; } /** Get a single element. @param i Row index. @param j Column index. @return A(i,j) @exception ArrayIndexOutOfBoundsException */ public double get (int i, int j) { return A[i][j]; } /** Get a submatrix. @param i0 Initial row index @param i1 Final row index @param j0 Initial column index @param j1 Final column index @return A(i0:i1,j0:j1) @exception ArrayIndexOutOfBoundsException Submatrix indices */ public Matrix getMatrix (int i0, int i1, int j0, int j1) { Matrix X = new Matrix(i1-i0+1,j1-j0+1); double[][] B = X.getArray(); try { for (int i = i0; i <= i1; i++) { for (int j = j0; j <= j1; j++) { B[i-i0][j-j0] = A[i][j]; } } } catch(ArrayIndexOutOfBoundsException e) { throw new ArrayIndexOutOfBoundsException("Submatrix indices"); } return X; } /** Get a submatrix. @param r Array of row indices. @param c Array of column indices. @return A(r(:),c(:)) @exception ArrayIndexOutOfBoundsException Submatrix indices */ public Matrix getMatrix (int[] r, int[] c) { Matrix X = new Matrix(r.length,c.length); double[][] B = X.getArray(); try { for (int i = 0; i < r.length; i++) { for (int j = 0; j < c.length; j++) { B[i][j] = A[r[i]][c[j]]; } } } catch(ArrayIndexOutOfBoundsException e) { throw new ArrayIndexOutOfBoundsException("Submatrix indices"); } return X; } /** Get a submatrix. @param i0 Initial row index @param i1 Final row index @param c Array of column indices. @return A(i0:i1,c(:)) @exception ArrayIndexOutOfBoundsException Submatrix indices */ public Matrix getMatrix (int i0, int i1, int[] c) { Matrix X = new Matrix(i1-i0+1,c.length); double[][] B = X.getArray(); try { for (int i = i0; i <= i1; i++) { for (int j = 0; j < c.length; j++) { B[i-i0][j] = A[i][c[j]]; } } } catch(ArrayIndexOutOfBoundsException e) { throw new ArrayIndexOutOfBoundsException("Submatrix indices"); } return X; } /** Get a submatrix. @param r Array of row indices. @param i0 Initial column index @param i1 Final column index @return A(r(:),j0:j1) @exception ArrayIndexOutOfBoundsException Submatrix indices */ public Matrix getMatrix (int[] r, int j0, int j1) { Matrix X = new Matrix(r.length,j1-j0+1); double[][] B = X.getArray(); try { for (int i = 0; i < r.length; i++) { for (int j = j0; j <= j1; j++) { B[i][j-j0] = A[r[i]][j]; } } } catch(ArrayIndexOutOfBoundsException e) { throw new ArrayIndexOutOfBoundsException("Submatrix indices"); } return X; } /** Set a single element. @param i Row index. @param j Column index. @param s A(i,j). @exception ArrayIndexOutOfBoundsException */ public void set (int i, int j, double s) { A[i][j] = s; } /** Set a submatrix. @param i0 Initial row index @param i1 Final row index @param j0 Initial column index @param j1 Final column index @param X A(i0:i1,j0:j1) @exception ArrayIndexOutOfBoundsException Submatrix indices */ public void setMatrix (int i0, int i1, int j0, int j1, Matrix X) { try { for (int i = i0; i <= i1; i++) { for (int j = j0; j <= j1; j++) { A[i][j] = X.get(i-i0,j-j0); } } } catch(ArrayIndexOutOfBoundsException e) { throw new ArrayIndexOutOfBoundsException("Submatrix indices"); } } /** Set a submatrix. @param r Array of row indices. @param c Array of column indices. @param X A(r(:),c(:)) @exception ArrayIndexOutOfBoundsException Submatrix indices */ public void setMatrix (int[] r, int[] c, Matrix X) { try { for (int i = 0; i < r.length; i++) { for (int j = 0; j < c.length; j++) { A[r[i]][c[j]] = X.get(i,j); } } } catch(ArrayIndexOutOfBoundsException e) { throw new ArrayIndexOutOfBoundsException("Submatrix indices"); } } /** Set a submatrix. @param r Array of row indices. @param j0 Initial column index @param j1 Final column index @param X A(r(:),j0:j1) @exception ArrayIndexOutOfBoundsException Submatrix indices */ public void setMatrix (int[] r, int j0, int j1, Matrix X) { try { for (int i = 0; i < r.length; i++) { for (int j = j0; j <= j1; j++) { A[r[i]][j] = X.get(i,j-j0); } } } catch(ArrayIndexOutOfBoundsException e) { throw new ArrayIndexOutOfBoundsException("Submatrix indices"); } } /** Set a submatrix. @param i0 Initial row index @param i1 Final row index @param c Array of column indices. @param X A(i0:i1,c(:)) @exception ArrayIndexOutOfBoundsException Submatrix indices */ public void setMatrix (int i0, int i1, int[] c, Matrix X) { try { for (int i = i0; i <= i1; i++) { for (int j = 0; j < c.length; j++) { A[i][c[j]] = X.get(i-i0,j); } } } catch(ArrayIndexOutOfBoundsException e) { throw new ArrayIndexOutOfBoundsException("Submatrix indices"); } } /** Matrix transpose. @return A' */ public Matrix transpose () { Matrix X = new Matrix(n,m); double[][] C = X.getArray(); for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { C[j][i] = A[i][j]; } } return X; } /** One norm @return maximum column sum. */ public double norm1 () { double f = 0; for (int j = 0; j < n; j++) { double s = 0; for (int i = 0; i < m; i++) { s += Math.abs(A[i][j]); } f = Math.max(f,s); } return f; } /** Two norm @return maximum singular value. */ public double norm2 () { return (new SingularValueDecomposition(this).norm2()); } /** Infinity norm @return maximum row sum. */ public double normInf () { double f = 0; for (int i = 0; i < m; i++) { double s = 0; for (int j = 0; j < n; j++) { s += Math.abs(A[i][j]); } f = Math.max(f,s); } return f; } /** Frobenius norm @return sqrt of sum of squares of all elements. */ public double normF () { double f = 0; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { f = Maths.hypot(f,A[i][j]); } } return f; } /** Unary minus @return -A */ public Matrix uminus () { Matrix X = new Matrix(m,n); double[][] C = X.getArray(); for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { C[i][j] = -A[i][j]; } } return X; } /** C = A + B @param B another matrix @return A + B */ public Matrix plus (Matrix B) { checkMatrixDimensions(B); Matrix X = new Matrix(m,n); double[][] C = X.getArray(); for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { C[i][j] = A[i][j] + B.A[i][j]; } } return X; } /** A = A + B @param B another matrix @return A + B */ public Matrix plusEquals (Matrix B) { checkMatrixDimensions(B); for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { A[i][j] = A[i][j] + B.A[i][j]; } } return this; } /** C = A - B @param B another matrix @return A - B */ public Matrix minus (Matrix B) { checkMatrixDimensions(B); Matrix X = new Matrix(m,n); double[][] C = X.getArray(); for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { C[i][j] = A[i][j] - B.A[i][j]; } } return X; } /** A = A - B @param B another matrix @return A - B */ public Matrix minusEquals (Matrix B) { checkMatrixDimensions(B); for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { A[i][j] = A[i][j] - B.A[i][j]; } } return this; } /** Element-by-element multiplication, C = A.*B @param B another matrix @return A.*B */ public Matrix arrayTimes (Matrix B) { checkMatrixDimensions(B); Matrix X = new Matrix(m,n); double[][] C = X.getArray(); for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { C[i][j] = A[i][j] * B.A[i][j]; } } return X; } /** Element-by-element multiplication in place, A = A.*B @param B another matrix @return A.*B */ public Matrix arrayTimesEquals (Matrix B) { checkMatrixDimensions(B); for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { A[i][j] = A[i][j] * B.A[i][j]; } } return this; } /** Element-by-element right division, C = A./B @param B another matrix @return A./B */ public Matrix arrayRightDivide (Matrix B) { checkMatrixDimensions(B); Matrix X = new Matrix(m,n); double[][] C = X.getArray(); for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { C[i][j] = A[i][j] / B.A[i][j]; } } return X; } /** Element-by-element right division in place, A = A./B @param B another matrix @return A./B */ public Matrix arrayRightDivideEquals (Matrix B) { checkMatrixDimensions(B); for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { A[i][j] = A[i][j] / B.A[i][j]; } } return this; } /** Element-by-element left division, C = A.\B @param B another matrix @return A.\B */ public Matrix arrayLeftDivide (Matrix B) { checkMatrixDimensions(B); Matrix X = new Matrix(m,n); double[][] C = X.getArray(); for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { C[i][j] = B.A[i][j] / A[i][j]; } } return X; } /** Element-by-element left division in place, A = A.\B @param B another matrix @return A.\B */ public Matrix arrayLeftDivideEquals (Matrix B) { checkMatrixDimensions(B); for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { A[i][j] = B.A[i][j] / A[i][j]; } } return this; } /** Multiply a matrix by a scalar, C = s*A @param s scalar @return s*A */ public Matrix times (double s) { Matrix X = new Matrix(m,n); double[][] C = X.getArray(); for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { C[i][j] = s*A[i][j]; } } return X; } /** Multiply a matrix by a scalar in place, A = s*A @param s scalar @return replace A by s*A */ public Matrix timesEquals (double s) { for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { A[i][j] = s*A[i][j]; } } return this; } /** Linear algebraic matrix multiplication, A * B @param B another matrix @return Matrix product, A * B @exception IllegalArgumentException Matrix inner dimensions must agree. */ public Matrix times (Matrix B) { if (B.m != n) { throw new IllegalArgumentException("Matrix inner dimensions must agree."); } Matrix X = new Matrix(m,B.n); double[][] C = X.getArray(); double[] Bcolj = new double[n]; for (int j = 0; j < B.n; j++) { for (int k = 0; k < n; k++) { Bcolj[k] = B.A[k][j]; } for (int i = 0; i < m; i++) { double[] Arowi = A[i]; double s = 0; for (int k = 0; k < n; k++) { s += Arowi[k]*Bcolj[k]; } C[i][j] = s; } } return X; } /** LU Decomposition @return LUDecomposition @see LUDecomposition */ public LUDecomposition lu () { return new LUDecomposition(this); } /** QR Decomposition @return QRDecomposition @see QRDecomposition */ public QRDecomposition qr () { return new QRDecomposition(this); } /** Cholesky Decomposition @return CholeskyDecomposition @see CholeskyDecomposition */ public CholeskyDecomposition chol () { return new CholeskyDecomposition(this); } /** Singular Value Decomposition @return SingularValueDecomposition @see SingularValueDecomposition */ public SingularValueDecomposition svd () { return new SingularValueDecomposition(this); } /** Eigenvalue Decomposition @return EigenvalueDecomposition @see EigenvalueDecomposition */ public EigenvalueDecomposition eig () { return new EigenvalueDecomposition(this); } /** Solve A*X = B @param B right hand side @return solution if A is square, least squares solution otherwise */ public Matrix solve (Matrix B) { return (m == n ? (new LUDecomposition(this)).solve(B) : (new QRDecomposition(this)).solve(B)); } /** Solve X*A = B, which is also A'*X' = B' @param B right hand side @return solution if A is square, least squares solution otherwise. */ public Matrix solveTranspose (Matrix B) { return transpose().solve(B.transpose()); } /** Matrix inverse or pseudoinverse @return inverse(A) if A is square, pseudoinverse otherwise. */ public Matrix inverse () { return solve(identity(m,m)); } /** Matrix determinant @return determinant */ public double det () { return new LUDecomposition(this).det(); } /** Matrix rank @return effective numerical rank, obtained from SVD. */ public int rank () { return new SingularValueDecomposition(this).rank(); } /** Matrix condition (2 norm) @return ratio of largest to smallest singular value. */ public double cond () { return new SingularValueDecomposition(this).cond(); } /** Matrix trace. @return sum of the diagonal elements. */ public double trace () { double t = 0; for (int i = 0; i < Math.min(m,n); i++) { t += A[i][i]; } return t; } /** Generate matrix with random elements @param m Number of rows. @param n Number of colums. @return An m-by-n matrix with uniformly distributed random elements. */ public static Matrix random (int m, int n) { Matrix A = new Matrix(m,n); double[][] X = A.getArray(); for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { X[i][j] = Math.random(); } } return A; } /** Generate identity matrix @param m Number of rows. @param n Number of colums. @return An m-by-n matrix with ones on the diagonal and zeros elsewhere. */ public static Matrix identity (int m, int n) { Matrix A = new Matrix(m,n); double[][] X = A.getArray(); for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { X[i][j] = (i == j ? 1.0 : 0.0); } } return A; } /** Print the matrix to stdout. Line the elements up in columns * with a Fortran-like 'Fw.d' style format. @param w Column width. @param d Number of digits after the decimal. */ public void print (int w, int d) { print(new PrintWriter(System.out,true),w,d); } /** Print the matrix to the output stream. Line the elements up in * columns with a Fortran-like 'Fw.d' style format. @param output Output stream. @param w Column width. @param d Number of digits after the decimal. */ public void print (PrintWriter output, int w, int d) { DecimalFormat format = new DecimalFormat(); format.setDecimalFormatSymbols(new DecimalFormatSymbols(Locale.US)); format.setMinimumIntegerDigits(1); format.setMaximumFractionDigits(d); format.setMinimumFractionDigits(d); format.setGroupingUsed(false); print(output,format,w+2); } /** Print the matrix to stdout. Line the elements up in columns. * Use the format object, and right justify within columns of width * characters. * Note that is the matrix is to be read back in, you probably will want * to use a NumberFormat that is set to US Locale. @param format A Formatting object for individual elements. @param width Field width for each column. @see java.text.DecimalFormat#setDecimalFormatSymbols */ public void print (NumberFormat format, int width) { print(new PrintWriter(System.out,true),format,width); } // DecimalFormat is a little disappointing coming from Fortran or C's printf. // Since it doesn't pad on the left, the elements will come out different // widths. Consequently, we'll pass the desired column width in as an // argument and do the extra padding ourselves. /** Print the matrix to the output stream. Line the elements up in columns. * Use the format object, and right justify within columns of width * characters. * Note that is the matrix is to be read back in, you probably will want * to use a NumberFormat that is set to US Locale. @param output the output stream. @param format A formatting object to format the matrix elements @param width Column width. @see java.text.DecimalFormat#setDecimalFormatSymbols */ public void print (PrintWriter output, NumberFormat format, int width) { output.println(); // start on new line. for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { String s = format.format(A[i][j]); // format the number int padding = Math.max(1,width-s.length()); // At _least_ 1 space for (int k = 0; k < padding; k++) output.print(' '); output.print(s); } output.println(); } output.println(); // end with blank line. } /** Read a matrix from a stream. The format is the same the print method, * so printed matrices can be read back in (provided they were printed using * US Locale). Elements are separated by * whitespace, all the elements for each row appear on a single line, * the last row is followed by a blank line. @param input the input stream. */ public static Matrix read (BufferedReader input) throws java.io.IOException { StreamTokenizer tokenizer= new StreamTokenizer(input); // Although StreamTokenizer will parse numbers, it doesn't recognize // scientific notation (E or D); however, Double.valueOf does. // The strategy here is to disable StreamTokenizer's number parsing. // We'll only get whitespace delimited words, EOL's and EOF's. // These words should all be numbers, for Double.valueOf to parse. tokenizer.resetSyntax(); tokenizer.wordChars(0,255); tokenizer.whitespaceChars(0, ' '); tokenizer.eolIsSignificant(true); java.util.Vector v = new java.util.Vector(); // Ignore initial empty lines while (tokenizer.nextToken() == StreamTokenizer.TT_EOL); if (tokenizer.ttype == StreamTokenizer.TT_EOF) throw new java.io.IOException("Unexpected EOF on matrix read."); do { v.addElement(Double.valueOf(tokenizer.sval)); // Read & store 1st row. } while (tokenizer.nextToken() == StreamTokenizer.TT_WORD); int n = v.size(); // Now we've got the number of columns! double row[] = new double[n]; for (int j=0; j= n) throw new java.io.IOException ("Row " + v.size() + " is too long."); row[j++] = Double.valueOf(tokenizer.sval).doubleValue(); } while (tokenizer.nextToken() == StreamTokenizer.TT_WORD); if (j < n) throw new java.io.IOException ("Row " + v.size() + " is too short."); } int m = v.size(); // Now we've got the number of rows. double[][] A = new double[m][]; v.copyInto(A); // copy the rows out of the vector return new Matrix(A); } /* ------------------------ Private Methods * ------------------------ */ /** Check if size(A) == size(B) **/ private void checkMatrixDimensions (Matrix B) { if (B.m != m || B.n != n) { throw new IllegalArgumentException("Matrix dimensions must agree."); } } } source/jama/QRDecomposition.java000644 000000136501144672361400126330ustar package jama; import jama.util.*; /** QR Decomposition.

For an m-by-n matrix A with m >= n, the QR decomposition is an m-by-n orthogonal matrix Q and an n-by-n upper triangular matrix R so that A = Q*R.

The QR decompostion always exists, even if the matrix does not have full rank, so the constructor will never fail. The primary use of the QR decomposition is in the least squares solution of nonsquare systems of simultaneous linear equations. This will fail if isFullRank() returns false. */ public class QRDecomposition implements java.io.Serializable { /* ------------------------ Class variables * ------------------------ */ /** Array for internal storage of decomposition. @serial internal array storage. */ private double[][] QR; /** Row and column dimensions. @serial column dimension. @serial row dimension. */ private int m, n; /** Array for internal storage of diagonal of R. @serial diagonal of R. */ private double[] Rdiag; /* ------------------------ Constructor * ------------------------ */ /** QR Decomposition, computed by Householder reflections. @param A Rectangular matrix @return Structure to access R and the Householder vectors and compute Q. */ public QRDecomposition (Matrix A) { // Initialize. QR = A.getArrayCopy(); m = A.getRowDimension(); n = A.getColumnDimension(); Rdiag = new double[n]; // Main loop. for (int k = 0; k < n; k++) { // Compute 2-norm of k-th column without under/overflow. double nrm = 0; for (int i = k; i < m; i++) { nrm = Maths.hypot(nrm,QR[i][k]); } if (nrm != 0.0) { // Form k-th Householder vector. if (QR[k][k] < 0) { nrm = -nrm; } for (int i = k; i < m; i++) { QR[i][k] /= nrm; } QR[k][k] += 1.0; // Apply transformation to remaining columns. for (int j = k+1; j < n; j++) { double s = 0.0; for (int i = k; i < m; i++) { s += QR[i][k]*QR[i][j]; } s = -s/QR[k][k]; for (int i = k; i < m; i++) { QR[i][j] += s*QR[i][k]; } } } Rdiag[k] = -nrm; } } /* ------------------------ Public Methods * ------------------------ */ /** Is the matrix full rank? @return true if R, and hence A, has full rank. */ public boolean isFullRank () { for (int j = 0; j < n; j++) { if (Rdiag[j] == 0) return false; } return true; } /** Return the Householder vectors @return Lower trapezoidal matrix whose columns define the reflections */ public Matrix getH () { Matrix X = new Matrix(m,n); double[][] H = X.getArray(); for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (i >= j) { H[i][j] = QR[i][j]; } else { H[i][j] = 0.0; } } } return X; } /** Return the upper triangular factor @return R */ public Matrix getR () { Matrix X = new Matrix(n,n); double[][] R = X.getArray(); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (i < j) { R[i][j] = QR[i][j]; } else if (i == j) { R[i][j] = Rdiag[i]; } else { R[i][j] = 0.0; } } } return X; } /** Generate and return the (economy-sized) orthogonal factor @return Q */ public Matrix getQ () { Matrix X = new Matrix(m,n); double[][] Q = X.getArray(); for (int k = n-1; k >= 0; k--) { for (int i = 0; i < m; i++) { Q[i][k] = 0.0; } Q[k][k] = 1.0; for (int j = k; j < n; j++) { if (QR[k][k] != 0) { double s = 0.0; for (int i = k; i < m; i++) { s += QR[i][k]*Q[i][j]; } s = -s/QR[k][k]; for (int i = k; i < m; i++) { Q[i][j] += s*QR[i][k]; } } } } return X; } /** Least squares solution of A*X = B @param B A Matrix with as many rows as A and any number of columns. @return X that minimizes the two norm of Q*R*X-B. @exception IllegalArgumentException Matrix row dimensions must agree. @exception RuntimeException Matrix is rank deficient. */ public Matrix solve (Matrix B) { if (B.getRowDimension() != m) { throw new IllegalArgumentException("Matrix row dimensions must agree."); } if (!this.isFullRank()) { throw new RuntimeException("Matrix is rank deficient."); } // Copy right hand side int nx = B.getColumnDimension(); double[][] X = B.getArrayCopy(); // Compute Y = transpose(Q)*B for (int k = 0; k < n; k++) { for (int j = 0; j < nx; j++) { double s = 0.0; for (int i = k; i < m; i++) { s += QR[i][k]*X[i][j]; } s = -s/QR[k][k]; for (int i = k; i < m; i++) { X[i][j] += s*QR[i][k]; } } } // Solve R*X = Y; for (int k = n-1; k >= 0; k--) { for (int j = 0; j < nx; j++) { X[k][j] /= Rdiag[k]; } for (int i = 0; i < k; i++) { for (int j = 0; j < nx; j++) { X[i][j] -= X[k][j]*QR[i][k]; } } } return (new Matrix(X,n,nx).getMatrix(0,n-1,0,nx-1)); } } source/jama/SingularValueDecomposition.java000644 000000374421164063346600151000ustar package jama; import jama.util.*; /** Singular Value Decomposition.

For an m-by-n matrix A with m >= n, the singular value decomposition is an m-by-n orthogonal matrix U, an n-by-n diagonal matrix S, and an n-by-n orthogonal matrix V so that A = U*S*V'.

The singular values, sigma[k] = S[k][k], are ordered so that sigma[0] >= sigma[1] >= ... >= sigma[n-1].

The singular value decompostion always exists, so the constructor will never fail. The matrix condition number and the effective numerical rank can be computed from this decomposition. */ public class SingularValueDecomposition implements java.io.Serializable { /* ------------------------ Class variables * ------------------------ */ /** Arrays for internal storage of U and V. @serial internal storage of U. @serial internal storage of V. */ private double[][] U, V; /** Array for internal storage of singular values. @serial internal storage of singular values. */ private double[] s; /** Row and column dimensions. @serial row dimension. @serial column dimension. */ private int m, n; /* ------------------------ Constructor * ------------------------ */ /** Construct the singular value decomposition @param A Rectangular matrix @return Structure to access U, S and V. */ public SingularValueDecomposition (Matrix Arg) { // Derived from LINPACK code. // Initialize. double[][] A = Arg.getArrayCopy(); m = Arg.getRowDimension(); n = Arg.getColumnDimension(); /* Apparently the failing cases are only a proper subset of (m= n"); } */ int nu = Math.min(m,n); s = new double [Math.min(m+1,n)]; U = new double [m][nu]; V = new double [n][n]; double[] e = new double [n]; double[] work = new double [m]; boolean wantu = true; boolean wantv = true; // Reduce A to bidiagonal form, storing the diagonal elements // in s and the super-diagonal elements in e. int nct = Math.min(m-1,n); int nrt = Math.max(0,Math.min(n-2,m)); for (int k = 0; k < Math.max(nct,nrt); k++) { if (k < nct) { // Compute the transformation for the k-th column and // place the k-th diagonal in s[k]. // Compute 2-norm of k-th column without under/overflow. s[k] = 0; for (int i = k; i < m; i++) { s[k] = Maths.hypot(s[k],A[i][k]); } if (s[k] != 0.0) { if (A[k][k] < 0.0) { s[k] = -s[k]; } for (int i = k; i < m; i++) { A[i][k] /= s[k]; } A[k][k] += 1.0; } s[k] = -s[k]; } for (int j = k+1; j < n; j++) { if ((k < nct) & (s[k] != 0.0)) { // Apply the transformation. double t = 0; for (int i = k; i < m; i++) { t += A[i][k]*A[i][j]; } t = -t/A[k][k]; for (int i = k; i < m; i++) { A[i][j] += t*A[i][k]; } } // Place the k-th row of A into e for the // subsequent calculation of the row transformation. e[j] = A[k][j]; } if (wantu & (k < nct)) { // Place the transformation in U for subsequent back // multiplication. for (int i = k; i < m; i++) { U[i][k] = A[i][k]; } } if (k < nrt) { // Compute the k-th row transformation and place the // k-th super-diagonal in e[k]. // Compute 2-norm without under/overflow. e[k] = 0; for (int i = k+1; i < n; i++) { e[k] = Maths.hypot(e[k],e[i]); } if (e[k] != 0.0) { if (e[k+1] < 0.0) { e[k] = -e[k]; } for (int i = k+1; i < n; i++) { e[i] /= e[k]; } e[k+1] += 1.0; } e[k] = -e[k]; if ((k+1 < m) & (e[k] != 0.0)) { // Apply the transformation. for (int i = k+1; i < m; i++) { work[i] = 0.0; } for (int j = k+1; j < n; j++) { for (int i = k+1; i < m; i++) { work[i] += e[j]*A[i][j]; } } for (int j = k+1; j < n; j++) { double t = -e[j]/e[k+1]; for (int i = k+1; i < m; i++) { A[i][j] += t*work[i]; } } } if (wantv) { // Place the transformation in V for subsequent // back multiplication. for (int i = k+1; i < n; i++) { V[i][k] = e[i]; } } } } // Set up the final bidiagonal matrix or order p. int p = Math.min(n,m+1); if (nct < n) { s[nct] = A[nct][nct]; } if (m < p) { s[p-1] = 0.0; } if (nrt+1 < p) { e[nrt] = A[nrt][p-1]; } e[p-1] = 0.0; // If required, generate U. if (wantu) { for (int j = nct; j < nu; j++) { for (int i = 0; i < m; i++) { U[i][j] = 0.0; } U[j][j] = 1.0; } for (int k = nct-1; k >= 0; k--) { if (s[k] != 0.0) { for (int j = k+1; j < nu; j++) { double t = 0; for (int i = k; i < m; i++) { t += U[i][k]*U[i][j]; } t = -t/U[k][k]; for (int i = k; i < m; i++) { U[i][j] += t*U[i][k]; } } for (int i = k; i < m; i++ ) { U[i][k] = -U[i][k]; } U[k][k] = 1.0 + U[k][k]; for (int i = 0; i < k-1; i++) { U[i][k] = 0.0; } } else { for (int i = 0; i < m; i++) { U[i][k] = 0.0; } U[k][k] = 1.0; } } } // If required, generate V. if (wantv) { for (int k = n-1; k >= 0; k--) { if ((k < nrt) & (e[k] != 0.0)) { for (int j = k+1; j < nu; j++) { double t = 0; for (int i = k+1; i < n; i++) { t += V[i][k]*V[i][j]; } t = -t/V[k+1][k]; for (int i = k+1; i < n; i++) { V[i][j] += t*V[i][k]; } } } for (int i = 0; i < n; i++) { V[i][k] = 0.0; } V[k][k] = 1.0; } } // Main iteration loop for the singular values. int pp = p-1; int iter = 0; double eps = Math.pow(2.0,-52.0); double tiny = Math.pow(2.0,-966.0); while (p > 0) { int k,kase; // Here is where a test for too many iterations would go. // This section of the program inspects for // negligible elements in the s and e arrays. On // completion the variables kase and k are set as follows. // kase = 1 if s(p) and e[k-1] are negligible and k

= -1; k--) { if (k == -1) { break; } if (Math.abs(e[k]) <= tiny + eps*(Math.abs(s[k]) + Math.abs(s[k+1]))) { e[k] = 0.0; break; } } if (k == p-2) { kase = 4; } else { int ks; for (ks = p-1; ks >= k; ks--) { if (ks == k) { break; } double t = (ks != p ? Math.abs(e[ks]) : 0.) + (ks != k+1 ? Math.abs(e[ks-1]) : 0.); if (Math.abs(s[ks]) <= tiny + eps*t) { s[ks] = 0.0; break; } } if (ks == k) { kase = 3; } else if (ks == p-1) { kase = 1; } else { kase = 2; k = ks; } } k++; // Perform the task indicated by kase. switch (kase) { // Deflate negligible s(p). case 1: { double f = e[p-2]; e[p-2] = 0.0; for (int j = p-2; j >= k; j--) { double t = Maths.hypot(s[j],f); double cs = s[j]/t; double sn = f/t; s[j] = t; if (j != k) { f = -sn*e[j-1]; e[j-1] = cs*e[j-1]; } if (wantv) { for (int i = 0; i < n; i++) { t = cs*V[i][j] + sn*V[i][p-1]; V[i][p-1] = -sn*V[i][j] + cs*V[i][p-1]; V[i][j] = t; } } } } break; // Split at negligible s(k). case 2: { double f = e[k-1]; e[k-1] = 0.0; for (int j = k; j < p; j++) { double t = Maths.hypot(s[j],f); double cs = s[j]/t; double sn = f/t; s[j] = t; f = -sn*e[j]; e[j] = cs*e[j]; if (wantu) { for (int i = 0; i < m; i++) { t = cs*U[i][j] + sn*U[i][k-1]; U[i][k-1] = -sn*U[i][j] + cs*U[i][k-1]; U[i][j] = t; } } } } break; // Perform one qr step. case 3: { // Calculate the shift. double scale = Math.max(Math.max(Math.max(Math.max( Math.abs(s[p-1]),Math.abs(s[p-2])),Math.abs(e[p-2])), Math.abs(s[k])),Math.abs(e[k])); double sp = s[p-1]/scale; double spm1 = s[p-2]/scale; double epm1 = e[p-2]/scale; double sk = s[k]/scale; double ek = e[k]/scale; double b = ((spm1 + sp)*(spm1 - sp) + epm1*epm1)/2.0; double c = (sp*epm1)*(sp*epm1); double shift = 0.0; if ((b != 0.0) | (c != 0.0)) { shift = Math.sqrt(b*b + c); if (b < 0.0) { shift = -shift; } shift = c/(b + shift); } double f = (sk + sp)*(sk - sp) + shift; double g = sk*ek; // Chase zeros. for (int j = k; j < p-1; j++) { double t = Maths.hypot(f,g); double cs = f/t; double sn = g/t; if (j != k) { e[j-1] = t; } f = cs*s[j] + sn*e[j]; e[j] = cs*e[j] - sn*s[j]; g = sn*s[j+1]; s[j+1] = cs*s[j+1]; if (wantv) { for (int i = 0; i < n; i++) { t = cs*V[i][j] + sn*V[i][j+1]; V[i][j+1] = -sn*V[i][j] + cs*V[i][j+1]; V[i][j] = t; } } t = Maths.hypot(f,g); cs = f/t; sn = g/t; s[j] = t; f = cs*e[j] + sn*s[j+1]; s[j+1] = -sn*e[j] + cs*s[j+1]; g = sn*e[j+1]; e[j+1] = cs*e[j+1]; if (wantu && (j < m-1)) { for (int i = 0; i < m; i++) { t = cs*U[i][j] + sn*U[i][j+1]; U[i][j+1] = -sn*U[i][j] + cs*U[i][j+1]; U[i][j] = t; } } } e[p-2] = f; iter = iter + 1; } break; // Convergence. case 4: { // Make the singular values positive. if (s[k] <= 0.0) { s[k] = (s[k] < 0.0 ? -s[k] : 0.0); if (wantv) { for (int i = 0; i <= pp; i++) { V[i][k] = -V[i][k]; } } } // Order the singular values. while (k < pp) { if (s[k] >= s[k+1]) { break; } double t = s[k]; s[k] = s[k+1]; s[k+1] = t; if (wantv && (k < n-1)) { for (int i = 0; i < n; i++) { t = V[i][k+1]; V[i][k+1] = V[i][k]; V[i][k] = t; } } if (wantu && (k < m-1)) { for (int i = 0; i < m; i++) { t = U[i][k+1]; U[i][k+1] = U[i][k]; U[i][k] = t; } } k++; } iter = 0; p--; } break; } } } /* ------------------------ Public Methods * ------------------------ */ /** Return the left singular vectors @return U */ public Matrix getU () { return new Matrix(U,m,Math.min(m+1,n)); } /** Return the right singular vectors @return V */ public Matrix getV () { return new Matrix(V,n,n); } /** Return the one-dimensional array of singular values @return diagonal of S. */ public double[] getSingularValues () { return s; } /** Return the diagonal matrix of singular values @return S */ public Matrix getS () { Matrix X = new Matrix(n,n); double[][] S = X.getArray(); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { S[i][j] = 0.0; } S[i][i] = this.s[i]; } return X; } /** Two norm @return max(S) */ public double norm2 () { return s[0]; } /** Two norm condition number @return max(S)/min(S) */ public double cond () { return s[0]/s[Math.min(m,n)-1]; } /** Effective numerical matrix rank @return Number of nonnegligible singular values. */ public int rank () { double eps = Math.pow(2.0,-52.0); double tol = Math.max(m,n)*s[0]*eps; int r = 0; for (int i = 0; i < s.length; i++) { if (s[i] > tol) { r++; } } return r; } } source/jama/util/000755 000000000001165162413600076565ustar source/jama/util/Maths.java000644 000000007061144672363600116070ustar package jama.util; public class Maths { /** sqrt(a^2 + b^2) without under/overflow. **/ public static double hypot(double a, double b) { double r; if (Math.abs(a) > Math.abs(b)) { r = b/a; r = Math.abs(a)*Math.sqrt(1+r*r); } else if (b != 0) { r = a/b; r = Math.abs(b)*Math.sqrt(1+r*r); } else { r = 0.0; } return r; } } source/jgromacs/000755 000000000001165162413600075765ustar source/jgromacs/analysis/000755 000000000001165162413600114215ustar source/jgromacs/analysis/Angles.java000644 000000451741164704005600135060ustar /** * * Written by Márton Münz and Philip C Biggin * Copyright (c) University of Oxford, United Kingdom * Visit http://sbcb.bioch.ox.ac.uk/jgromacs/ * * This source code file is part of JGromacs v1.0. * * JGromacs v1.0 is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * JGromacs v1.0. is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with JGromacs v1.0. If not, see . * */ package jgromacs.analysis; import java.util.ArrayList; import jama.Matrix; import jgromacs.data.Angle; import jgromacs.data.Point3D; import jgromacs.data.Residue; import jgromacs.data.Structure; import jgromacs.data.Trajectory; /** * Collection of methods for analysing angles * */ public class Angles { /** * Calculates the angle between two vectors * @param v1 first vector * @param v2 second vector * @return angle between vectors */ public static Angle getAngleBetweenVectors(Point3D v1, Point3D v2){ double inner = v1.innerProduct(v2); double lengths = v1.length()*v2.length(); double angleInRad = Math.acos(inner/lengths); Angle ret = new Angle(); ret.setInRadians(angleInRad); return ret; } /** * Calculates the angle between two planes defined by points A, B, C and points B, C, D * @param A point A * @param B point B * @param C point C * @param D point D * @return angle between planes */ public static Angle getAngleBetweenPlanes(Point3D A, Point3D B, Point3D C, Point3D D){ Point3D normal1 = getNormalVectorOfPlane(B, A, C); Point3D normal2 = getNormalVectorOfPlane(C, B, D); return getAngleBetweenVectors(normal1, normal2); } /** * Calculates the normal vector of a plane defined by the C,A and C,B vectors * @param C point C * @param A point A * @param B point B * @return normal vector */ private static Point3D getNormalVectorOfPlane(Point3D C, Point3D A, Point3D B){ Point3D v1 = A.minus(C); Point3D v2 = B.minus(C); return v1.crossProduct(v2); } /** * Calculates dihedral angle Phi of residue #i of a structure * @param s structure * @return dihedral angle Phi */ public static Angle getDihedralPhi(Structure s, int i){ if (i<=0) return new Angle(); Residue res = s.getResidue(i); Residue resMinus = s.getResidue(i-1); Point3D A = resMinus.getCTerminalCarbon().getCoordinates(); Point3D B = res.getNTerminalNitrogen().getCoordinates(); Point3D C = res.getAlphaCarbon().getCoordinates(); Point3D D = res.getCTerminalCarbon().getCoordinates(); Point3D b1 = B.minus(A); Point3D b2 = C.minus(B); Point3D b3 = D.minus(C); double x = (b1.multiplyByScalar(b2.length())).innerProduct(b2.crossProduct(b3)); double y = (b1.crossProduct(b2)).innerProduct(b2.crossProduct(b3)); double angle = Math.atan2(x, y); Angle ret = new Angle(); ret.setInRadians(angle); return ret; } /** * Calculates dihedral angle Psi of residue #i of a structure * @param s structure * @return dihedral angle Psi */ public static Angle getDihedralPsi(Structure s, int i){ if (i>=s.getNumberOfResidues()) return new Angle(); Residue res = s.getResidue(i); Residue resPlus = s.getResidue(i+1); Point3D A = res.getNTerminalNitrogen().getCoordinates(); Point3D B = res.getAlphaCarbon().getCoordinates(); Point3D C = res.getCTerminalCarbon().getCoordinates(); Point3D D = resPlus.getNTerminalNitrogen().getCoordinates(); Point3D b1 = B.minus(A); Point3D b2 = C.minus(B); Point3D b3 = D.minus(C); double x = (b1.multiplyByScalar(b2.length())).innerProduct(b2.crossProduct(b3)); double y = (b1.crossProduct(b2)).innerProduct(b2.crossProduct(b3)); double angle = Math.atan2(x, y); Angle ret = new Angle(); ret.setInRadians(angle); return ret; } /** * Calculates dihedral angle Omega of residue #i of a structure * @param s structure * @return dihedral angle Omega */ public static Angle getDihedralOmega(Structure s, int i){ if (i>=s.getNumberOfResidues()) return new Angle(); Residue res = s.getResidue(i); Residue resPlus = s.getResidue(i+1); Point3D A = res.getAlphaCarbon().getCoordinates(); Point3D B = res.getCTerminalCarbon().getCoordinates(); Point3D C = resPlus.getNTerminalNitrogen().getCoordinates(); Point3D D = resPlus.getAlphaCarbon().getCoordinates(); Point3D b1 = B.minus(A); Point3D b2 = C.minus(B); Point3D b3 = D.minus(C); double x = (b1.multiplyByScalar(b2.length())).innerProduct(b2.crossProduct(b3)); double y = (b1.crossProduct(b2)).innerProduct(b2.crossProduct(b3)); double angle = Math.atan2(x, y); Angle ret = new Angle(); ret.setInRadians(angle); return ret; } /** * Calculates side chain dihedral angle Chi1 of residue #i of a structure * The residue can be ARG,ASN,ASP,CYS,GLN,GLU,HIS,ILE,LEU,LYS,MET,PHE,PRO,SER,THR,TRP,TYR or VAL * @param s structure * @return dihedral angle Chi1 */ public static Angle getDihedralChi1(Structure s, int i){ Residue res = s.getResidue(i); String code = res.getResidueType().get3LetterCode().toUpperCase(); if (code.equals("ALA")||code.equals("GLY")) return null; Point3D A = res.getNTerminalNitrogen().getCoordinates(); Point3D B = res.getAlphaCarbon().getCoordinates(); Point3D C = res.getBetaCarbon().getCoordinates(); Point3D D = new Point3D(); if (code.equals("ARG")) D = res.getGammaCarbon().getCoordinates(); else if (code.equals("ASN")) D = res.getGammaCarbon().getCoordinates(); else if (code.equals("ASP")) D = res.getGammaCarbon().getCoordinates(); else if (code.equals("CYS")) D = res.getAtomByName("SG").getCoordinates(); else if (code.equals("GLN")) D = res.getGammaCarbon().getCoordinates(); else if (code.equals("GLU")) D = res.getGammaCarbon().getCoordinates(); else if (code.equals("HIS")) D = res.getGammaCarbon().getCoordinates(); else if (code.equals("ILE")) D = res.getAtomByName("CG1").getCoordinates(); else if (code.equals("LEU")) D = res.getGammaCarbon().getCoordinates(); else if (code.equals("LYS")) D = res.getGammaCarbon().getCoordinates(); else if (code.equals("MET")) D = res.getGammaCarbon().getCoordinates(); else if (code.equals("PHE")) D = res.getGammaCarbon().getCoordinates(); else if (code.equals("PRO")) D = res.getGammaCarbon().getCoordinates(); else if (code.equals("SER")) D = res.getAtomByName("OG").getCoordinates(); else if (code.equals("THR")) D = res.getAtomByName("OG1").getCoordinates(); else if (code.equals("TRP")) D = res.getGammaCarbon().getCoordinates(); else if (code.equals("TYR")) D = res.getGammaCarbon().getCoordinates(); else if (code.equals("VAL")) D = res.getAtomByName("CG1").getCoordinates(); else return null; Point3D b1 = B.minus(A); Point3D b2 = C.minus(B); Point3D b3 = D.minus(C); double x = (b1.multiplyByScalar(b2.length())).innerProduct(b2.crossProduct(b3)); double y = (b1.crossProduct(b2)).innerProduct(b2.crossProduct(b3)); double angle = Math.atan2(x, y); Angle ret = new Angle(); ret.setInRadians(angle); return ret; } /** * Calculates side chain dihedral angle Chi2 of residue #i of a structure * The residue can only be ARG,ASN,ASP,GLN,GLU,HIS,ILE,LEU,LYS,MET,PHE,PRO,TRP or TYR * @param s structure * @return dihedral angle Chi2 */ public static Angle getDihedralChi2(Structure s, int i){ Residue res = s.getResidue(i); String code = res.getResidueType().get3LetterCode().toUpperCase(); if (code.equals("ALA")||code.equals("GLY")||code.equals("CYS")||code.equals("SER")||code.equals("THR")||code.equals("VAL")) return null; Point3D A = res.getAlphaCarbon().getCoordinates(); Point3D B = res.getBetaCarbon().getCoordinates(); Point3D C; if (code.equals("ILE")) C = res.getAtomByName("CG1").getCoordinates(); else C = res.getGammaCarbon().getCoordinates(); Point3D D = new Point3D(); if (code.equals("ARG")) D = res.getDeltaCarbon().getCoordinates(); if (code.equals("ASN")) D = res.getAtomByName("OD1").getCoordinates(); if (code.equals("ASP")) D = res.getAtomByName("OD1").getCoordinates(); if (code.equals("GLN")) D = res.getDeltaCarbon().getCoordinates(); if (code.equals("GLU")) D = res.getDeltaCarbon().getCoordinates(); if (code.equals("HIS")) D = res.getAtomByName("ND1").getCoordinates(); if (code.equals("ILE")) D = res.getDeltaCarbon().getCoordinates(); if (code.equals("LEU")) D = res.getAtomByName("CD1").getCoordinates(); if (code.equals("LYS")) D = res.getDeltaCarbon().getCoordinates(); if (code.equals("MET")) D = res.getAtomByName("SD").getCoordinates(); if (code.equals("PHE")) D = res.getAtomByName("CD1").getCoordinates(); if (code.equals("PRO")) D = res.getDeltaCarbon().getCoordinates(); if (code.equals("TRP")) D = res.getAtomByName("CD1").getCoordinates(); if (code.equals("TYR")) D = res.getAtomByName("CD1").getCoordinates(); Point3D b1 = B.minus(A); Point3D b2 = C.minus(B); Point3D b3 = D.minus(C); double x = (b1.multiplyByScalar(b2.length())).innerProduct(b2.crossProduct(b3)); double y = (b1.crossProduct(b2)).innerProduct(b2.crossProduct(b3)); double angle = Math.atan2(x, y); Angle ret = new Angle(); ret.setInRadians(angle); return ret; } /** * Calculates side chain dihedral angle Chi3 of residue #i of a structure * The residue can only be ARG,GLN,GLU,LYS or MET * @param s structure * @return dihedral angle Chi3 */ public static Angle getDihedralChi3(Structure s, int i){ Residue res = s.getResidue(i); String code = res.getResidueType().get3LetterCode().toUpperCase(); if (!(code.equals("ARG")||code.equals("GLN")||code.equals("GLU")||code.equals("LYS")||code.equals("MET"))) return null; Point3D A = res.getBetaCarbon().getCoordinates(); Point3D B = res.getGammaCarbon().getCoordinates(); Point3D C = new Point3D(); Point3D D = new Point3D(); if (code.equals("ARG")) { C = res.getDeltaCarbon().getCoordinates(); D = res.getAtomByName("NE").getCoordinates(); } if (code.equals("GLN")) { C = res.getDeltaCarbon().getCoordinates(); D = res.getAtomByName("OE1").getCoordinates(); } if (code.equals("GLU")) { C = res.getDeltaCarbon().getCoordinates(); D = res.getAtomByName("OE1").getCoordinates(); } if (code.equals("LYS")) { C = res.getDeltaCarbon().getCoordinates(); D = res.getAtomByName("CE").getCoordinates(); } if (code.equals("MET")) { C = res.getAtomByName("SD").getCoordinates(); D = res.getAtomByName("CE").getCoordinates(); } Point3D b1 = B.minus(A); Point3D b2 = C.minus(B); Point3D b3 = D.minus(C); double x = (b1.multiplyByScalar(b2.length())).innerProduct(b2.crossProduct(b3)); double y = (b1.crossProduct(b2)).innerProduct(b2.crossProduct(b3)); double angle = Math.atan2(x, y); Angle ret = new Angle(); ret.setInRadians(angle); return ret; } /** * Calculates side chain dihedral angle Chi4 of residue #i of a structure * The residue can only be ARG or LYS * @param s structure * @return dihedral angle Chi4 */ public static Angle getDihedralChi4(Structure s, int i){ Residue res = s.getResidue(i); String code = res.getResidueType().get3LetterCode().toUpperCase(); if (!(code.equals("ARG")||code.equals("LYS"))) return null; Point3D A = res.getGammaCarbon().getCoordinates(); Point3D B = res.getDeltaCarbon().getCoordinates(); Point3D C = new Point3D(); Point3D D = new Point3D(); if (code.equals("ARG")) { C = res.getAtomByName("NE").getCoordinates(); D = res.getAtomByName("CZ").getCoordinates(); } if (code.equals("LYS")) { C = res.getAtomByName("CE").getCoordinates(); D = res.getAtomByName("NZ").getCoordinates(); } Point3D b1 = B.minus(A); Point3D b2 = C.minus(B); Point3D b3 = D.minus(C); double x = (b1.multiplyByScalar(b2.length())).innerProduct(b2.crossProduct(b3)); double y = (b1.crossProduct(b2)).innerProduct(b2.crossProduct(b3)); double angle = Math.atan2(x, y); Angle ret = new Angle(); ret.setInRadians(angle); return ret; } /** * Calculates side chain dihedral angle Chi5 of residue #i of a structure * The residue can only be ARG * @param s structure * @return dihedral angle Chi5 */ public static Angle getDihedralChi5(Structure s, int i){ Residue res = s.getResidue(i); String code = res.getResidueType().get3LetterCode().toUpperCase(); if (code.equals("ARG")){ Point3D A = res.getDeltaCarbon().getCoordinates(); Point3D B = res.getAtomByName("NE").getCoordinates(); Point3D C = res.getAtomByName("CZ").getCoordinates(); Point3D D = res.getAtomByName("NH1").getCoordinates(); Point3D b1 = B.minus(A); Point3D b2 = C.minus(B); Point3D b3 = D.minus(C); double x = (b1.multiplyByScalar(b2.length())).innerProduct(b2.crossProduct(b3)); double y = (b1.crossProduct(b2)).innerProduct(b2.crossProduct(b3)); double angle = Math.atan2(x, y); Angle ret = new Angle(); ret.setInRadians(angle); return ret; } else return null; } /** * Calculates the time series of dihedral angle Phi of residue #i over a trajectory * @param t trajectory * @return time series of Phi */ public static ArrayList getDihedralPhiTimeSeries(Trajectory t, int i){ ArrayList ret = new ArrayList(); for (int k = 0; k < t.getNumberOfFrames(); k++) { Structure frame = t.getFrameAsStructure(k); ret.add(getDihedralPhi(frame, i)); } return ret; } /** * Calculates the time series of dihedral angle Psi of residue #i over a trajectory * @param t trajectory * @return time series of Psi */ public static ArrayList getDihedralPsiTimeSeries(Trajectory t, int i){ ArrayList ret = new ArrayList(); for (int k = 0; k < t.getNumberOfFrames(); k++) { Structure frame = t.getFrameAsStructure(k); ret.add(getDihedralPsi(frame, i)); } return ret; } /** * Calculates the time series of dihedral angle Omega of residue #i over a trajectory * @param t trajectory * @return time series of Omega */ public static ArrayList getDihedralOmegaTimeSeries(Trajectory t, int i){ ArrayList ret = new ArrayList(); for (int k = 0; k < t.getNumberOfFrames(); k++) { Structure frame = t.getFrameAsStructure(k); ret.add(getDihedralOmega(frame, i)); } return ret; } /** * Calculates the time series of dihedral angle Chi1 of residue #i over a trajectory * The residue can be ARG,ASN,ASP,CYS,GLN,GLU,HIS,ILE,LEU,LYS,MET,PHE,PRO,SER,THR,TRP,TYR or VAL * @param t trajectory * @return time series of Chi1 */ public static ArrayList getDihedralChi1TimeSeries(Trajectory t, int i){ ArrayList ret = new ArrayList(); for (int k = 0; k < t.getNumberOfFrames(); k++) { Structure frame = t.getFrameAsStructure(k); ret.add(getDihedralChi1(frame, i)); } return ret; } /** * Calculates the time series of dihedral angle Chi2 of residue #i over a trajectory * The residue can only be ARG,ASN,ASP,GLN,GLU,HIS,ILE,LEU,LYS,MET,PHE,PRO,TRP or TYR * @param t trajectory * @return time series of Chi2 */ public static ArrayList getDihedralChi2TimeSeries(Trajectory t, int i){ ArrayList ret = new ArrayList(); for (int k = 0; k < t.getNumberOfFrames(); k++) { Structure frame = t.getFrameAsStructure(k); ret.add(getDihedralChi2(frame, i)); } return ret; } /** * Calculates the time series of dihedral angle Chi3 of residue #i over a trajectory * The residue can only be ARG,GLN,GLU,LYS or MET * @param t trajectory * @return time series of Chi3 */ public static ArrayList getDihedralChi3TimeSeries(Trajectory t, int i){ ArrayList ret = new ArrayList(); for (int k = 0; k < t.getNumberOfFrames(); k++) { Structure frame = t.getFrameAsStructure(k); ret.add(getDihedralChi3(frame, i)); } return ret; } /** * Calculates the time series of dihedral angle Chi4 of residue #i over a trajectory * The residue can only be ARG or LYS * @param t trajectory * @return time series of Chi4 */ public static ArrayList getDihedralChi4TimeSeries(Trajectory t, int i){ ArrayList ret = new ArrayList(); for (int k = 0; k < t.getNumberOfFrames(); k++) { Structure frame = t.getFrameAsStructure(k); ret.add(getDihedralChi4(frame, i)); } return ret; } /** * Calculates the time series of dihedral angle Chi5 of residue #i over a trajectory * The residue can only be ARG * @param t trajectory * @return time series of Chi5 */ public static ArrayList getDihedralChi5TimeSeries(Trajectory t, int i){ ArrayList ret = new ArrayList(); for (int k = 0; k < t.getNumberOfFrames(); k++) { Structure frame = t.getFrameAsStructure(k); ret.add(getDihedralChi5(frame, i)); } return ret; } /** * Calculates the time series of torsion angle over a trajectory defined by four atoms * @param t trajectory * @param atom1 index of first atom * @param atom2 index of second atom * @param atom3 index of third atom * @param atom4 index of fourth atom * @return time series of torsion angle */ public static ArrayList getTorsionAngleTimeSeries(Trajectory t, int atom1, int atom2, int atom3, int atom4){ ArrayList ret = new ArrayList(); for (int k = 0; k < t.getNumberOfFrames(); k++) { Structure frame = t.getFrameAsStructure(k); Point3D A = frame.getAtomByIndex(atom1).getCoordinates(); Point3D B = frame.getAtomByIndex(atom2).getCoordinates(); Point3D C = frame.getAtomByIndex(atom3).getCoordinates(); Point3D D = frame.getAtomByIndex(atom4).getCoordinates(); ret.add(getAngleBetweenPlanes(A, B, C, D)); } return ret; } /** * Calculates the Ramachandran Plot of a structure * @param s structure (a polypeptide chain) * @return (N-2)x2 matrix of (phi,psi) pairs */ public static Matrix getRamachandranPlot(Structure s){ Matrix ret = new Matrix(s.getNumberOfResidues()-2,2); for (int i = 1; i < s.getNumberOfResidues()-1; i++) { Angle phi = getDihedralPhi(s, i); Angle psi = getDihedralPsi(s, i); ret.set(i-1, 0, phi.getInDegrees()); ret.set(i-1, 1, psi.getInDegrees()); } return ret; } } source/jgromacs/analysis/Distances.java000644 000000620561164527561200142160ustar /** * * Written by Márton Münz and Philip C Biggin * Copyright (c) University of Oxford, United Kingdom * Visit http://sbcb.bioch.ox.ac.uk/jgromacs/ * * This source code file is part of JGromacs v1.0. * * JGromacs v1.0 is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * JGromacs v1.0. is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with JGromacs v1.0. If not, see . * */ package jgromacs.analysis; import java.util.ArrayList; import jgromacs.data.Atom; import jgromacs.data.FrameIndexSet; import jgromacs.data.IndexSet; import jgromacs.data.Point3D; import jgromacs.data.PointList; import jgromacs.data.Residue; import jgromacs.data.Structure; import jgromacs.data.Trajectory; import jama.Matrix; /** * Collection of methods for analysing distances * */ public class Distances { public static final int ALPHACARBON = 1; public static final int CLOSEST = 2; public static final int CLOSESTHEAVY = 3; // Distance matrices /** * Calculates the distance matrix from a point list * @param points point list * @return distance matrix */ public static Matrix getDistanceMatrix(PointList points){ Matrix ret = new Matrix(points.getNumberOfPoints(),points.getNumberOfPoints(),0); for (int i = 0; i < points.getNumberOfPoints(); i++) { for (int j = i+1; j < points.getNumberOfPoints(); j++) { ret.set(i, j, points.getPoint(i).distance(points.getPoint(j))); ret.set(j, i, ret.get(i, j)); } } return ret; } /** * Calculates the distance matrix of all atoms in a structure * @param s structure * @return distance matrix */ public static Matrix getAtomicDistanceMatrix(Structure s){ PointList points = s.getAllAtomCoordinates(); return getDistanceMatrix(points); } /** * Calculates the distance matrix of atoms of given indices in a structure * @param s structure * @param indices index set * @return distance matrix */ public static Matrix getAtomicDistanceMatrix(Structure s, IndexSet indices){ int dim = indices.getNumberOfIndices(); Matrix ret = new Matrix(dim,dim,0); ArrayList indexList = indices.getAsArrayList(); for (int i = 0; i < dim; i++) { Atom atomI = s.getAtomByIndex(indexList.get(i)); for (int j = i+1; j < dim; j++) { Atom atomJ = s.getAtomByIndex(indexList.get(j)); ret.set(i, j, atomI.distance(atomJ)); ret.set(j, i, ret.get(i, j)); } } return ret; } /** * Calculates the distance matrix between two sets of atoms * @param s structure * @param indices1 index set 1 * @param indices2 index set 2 * @return distance matrix */ public static Matrix getAtomicDistanceMatrix(Structure s, IndexSet indices1, IndexSet indices2){ int dim1 = indices1.getNumberOfIndices(); int dim2 = indices2.getNumberOfIndices(); Matrix ret = new Matrix(dim1,dim2,0); ArrayList indexList1 = indices1.getAsArrayList(); ArrayList indexList2 = indices2.getAsArrayList(); for (int i = 0; i < dim1; i++) { Atom atomI = s.getAtomByIndex(indexList1.get(i)); for (int j = 0; j < dim2; j++) { Atom atomJ = s.getAtomByIndex(indexList2.get(j)); ret.set(i, j, atomI.distance(atomJ)); } } return ret; } /** * Calculates the distance matrix of residues in a structure by the given method * @param s structure * @param distanceBetween which atoms are used for calculating the distances (ALPHACARBON: alpha carbon atoms, * CLOSEST: closest atoms of two residues, CLOSESTHEAVY: closest heavy atoms of two residues) * @return distance matrix */ public static Matrix getResidueDistanceMatrix(Structure s, int distanceBetween){ int dim = s.getNumberOfResidues(); Matrix ret = new Matrix(dim,dim,0); for (int i = 0; i < dim; i++) { Residue resI = s.getResidue(i); for (int j = i+1; j < dim; j++) { Residue resJ = s.getResidue(j); double dist = 0; if (distanceBetween==ALPHACARBON) dist = resI.distanceAlphaCarbons(resJ); if (distanceBetween==CLOSEST) dist = resI.distanceClosest(resJ); if (distanceBetween==CLOSESTHEAVY) dist = resI.distanceClosestHeavy(resJ); ret.set(i, j, dist); ret.set(j, i, dist); } } return ret; } /** * Calculates the mean distance matrix of all atoms in a trajectory * @param t trajecotry * @return mean distance matrix */ public static Matrix getMeanAtomicDistanceMatrix(Trajectory t){ int dim = t.getNumberOfAtoms(); Matrix ret = new Matrix(dim,dim,0); for (int i = 0; i < t.getNumberOfFrames(); i++) { PointList frame = t.getFrameAsPointList(i); Matrix Di = getDistanceMatrix(frame); ret = ret.plus(Di); } return ret.times(1.0/t.getNumberOfFrames()); } /** * Calculates the mean distance matrix of atoms of given indices in a trajectory * @param t trajecotry * @param indices index set * @return mean distance matrix */ public static Matrix getMeanAtomicDistanceMatrix(Trajectory t, IndexSet indices){ ArrayList indexList = t.getFrameAsStructure(0).convertIndicesToArrayListIndices(indices); int dim = indexList.size(); Matrix ret = new Matrix(dim,dim,0); for (int i = 0; i < t.getNumberOfFrames(); i++) { PointList frame = t.getFrameAsPointList(i).getSubList(indexList); Matrix Di = getDistanceMatrix(frame); ret = ret.plus(Di); } return ret.times(1.0/t.getNumberOfFrames()); } /** * Calculates the mean distance matrix of residues in a trajectory by the given method * @param t trajectory * @param distanceBetween which atoms are used for calculating the distances (ALPHACARBON: alpha carbon atoms, * CLOSEST: closest atoms of two residues, CLOSESTHEAVY: closest heavy atoms of two residues) * @return mean distance matrix */ public static Matrix getMeanResidueDistanceMatrix(Trajectory t, int distanceBetween){ int dim = t.getNumberOfResidues(); Matrix ret = new Matrix(dim,dim,0); for (int i = 0; i < t.getNumberOfFrames(); i++) { Structure frame = t.getFrameAsStructure(i); Matrix Di = getResidueDistanceMatrix(frame, distanceBetween); ret = ret.plus(Di); } return ret.times(1.0/t.getNumberOfFrames()); } // Contact matrices /** * Calculates the contact matrix from a point list * @param points point list * @param cutoff distance cutoff * @return contact matrix */ public static Matrix getContactMatrix(PointList points, double cutoff){ Matrix distM = getDistanceMatrix(points); Matrix ret = new Matrix(distM.getRowDimension(),distM.getColumnDimension(),0); for (int i = 0; i < distM.getRowDimension(); i++) { for (int j = i; j < distM.getColumnDimension(); j++) { if (distM.get(i, j)<=cutoff) ret.set(i, j, 1); ret.set(j, i, ret.get(i, j)); } } return ret; } /** * Calculates the contact matrix of residues in a structure by the given method * @param s structure * @param distanceBetween which atoms are used for calculating the distances (ALPHACARBON: alpha carbon atoms, * CLOSEST: closest atoms of two residues, CLOSESTHEAVY: closest heavy atoms of two residues) * @param cutoff distance cutoff * @return contact matrix */ public static Matrix getContactMatrix(Structure s, int distanceBetween, double cutoff){ Matrix distM = getResidueDistanceMatrix(s,distanceBetween); Matrix ret = new Matrix(distM.getRowDimension(),distM.getColumnDimension(),0); for (int i = 0; i < distM.getRowDimension(); i++) { for (int j = i; j < distM.getColumnDimension(); j++) { if (distM.get(i, j)<=cutoff) ret.set(i, j, 1); ret.set(j, i, ret.get(i, j)); } } return ret; } /** * Calculates the contact matrix based on the mean residue distance matrix in a trajectory * @param t trajectory * @param distanceBetween which atoms are used for calculating the distances (ALPHACARBON: alpha carbon atoms, * CLOSEST: closest atoms of two residues, CLOSESTHEAVY: closest heavy atoms of two residues) * @param cutoff distance cutoff * @return contact matrix */ public static Matrix getContactOfMeanMatrix(Trajectory t, int distanceBetween, double cutoff){ Matrix distM = getMeanResidueDistanceMatrix(t, distanceBetween); Matrix ret = new Matrix(distM.getRowDimension(),distM.getColumnDimension(),0); for (int i = 0; i < distM.getRowDimension(); i++) { for (int j = i; j < distM.getColumnDimension(); j++) { if (distM.get(i, j)<=cutoff) ret.set(i, j, 1); ret.set(j, i, ret.get(i, j)); } } return ret; } /** * Calculates the contact matrix of residues where two residues are said to be in contact if they are in contact * in at least the given percentage of frames of the trajectory * @param t trajectory * @param distanceBetween which atoms are used for calculating the distances (ALPHACARBON: alpha carbon atoms, * CLOSEST: closest atoms of two residues, CLOSESTHEAVY: closest heavy atoms of two residues) * @param cutoff distance cutoff * @param frequency minimal frequency of frames in which two residues are in contact * @return contact matrix */ public static Matrix getFrequencyContactMatrix(Trajectory t, int distanceBetween, double cutoff, double frequency){ int dim = t.getNumberOfResidues(); Matrix ret = new Matrix(dim,dim,0); for (int i = 0; i < t.getNumberOfFrames(); i++) { Structure frame = t.getFrameAsStructure(i); Matrix Ci = getContactMatrix(frame, distanceBetween, cutoff); ret = ret.plus(Ci); } ret = ret.times(1.0/t.getNumberOfFrames()); for (int i = 0; i < dim; i++) { for (int j = i+1; j < dim; j++) { if (ret.get(i, j)>=frequency) ret.set(i, j, 1); else ret.set(i, j, 0); ret.set(j, i, ret.get(i, j)); } } return ret; } // Distance distributions / time series /** * Returns the time series of the distance of two atoms in a trajectory * @param t trajectory * @param atomindex1 index of first atom * @param atomindex2 index of second atom * @return time series of distance */ public static ArrayList getDistanceTimeSeries(Trajectory t, int atomindex1, int atomindex2){ ArrayList ret = new ArrayList(); IndexSet indices = new IndexSet(); indices.addIndex(atomindex1); indices.addIndex(atomindex2); ArrayList listindices = t.getFrameAsStructure(0).convertIndicesToArrayListIndices(indices); int listIndex1 = listindices.get(0); int listIndex2; if (listindices.size()>1) listIndex2 = listindices.get(1); else listIndex2=listIndex1; for (int i = 0; i < t.getNumberOfFrames(); i++) { Point3D point1 = t.getFrameAsPointList(i).getPoint(listIndex1); Point3D point2 = t.getFrameAsPointList(i).getPoint(listIndex2); double d = point1.distance(point2); ret.add(d); } return ret; } /** * Returns the time series of the distance of a single atom and a set of atoms in a trajectory * @param t trajectory * @param atomindex index of atom * @param referenceset index set of reference atoms * @return time series of distance */ public static ArrayList getDistanceTimeSeries(Trajectory t, int atomindex, IndexSet referenceset){ ArrayList ret = new ArrayList(); for (int i = 0; i < t.getNumberOfFrames(); i++) { double d = Distances.getDistanceOfAtomToAtomSet(t.getFrameAsStructure(i), atomindex, referenceset); ret.add(d); } return ret; } /** * Returns the time series of the distance of two sets of atoms in a trajectory * @param t trajectory * @param indices1 first index set * @param indices2 second index set * @return time series of distance */ public static ArrayList getDistanceTimeSeries(Trajectory t, IndexSet indices1, IndexSet indices2){ ArrayList ret = new ArrayList(); for (int i = 0; i < t.getNumberOfFrames(); i++) { double d = Distances.getDistanceOfTwoAtomSets(t.getFrameAsStructure(i), indices1, indices2); ret.add(d); } return ret; } /** * Returns the mean of the distance of two atoms in a trajectory * @param t trajectory * @param atomindex1 index of first atom * @param atomindex2 index of second atom * @return mean of distance */ public static double getMeanDistance(Trajectory t, int atomindex1, int atomindex2){ double ret = 0; ArrayList distr = getDistanceTimeSeries(t, atomindex1, atomindex2); for (int i = 0; i < distr.size(); i++) ret+=distr.get(i); return ret/distr.size(); } /** * Returns the variance of the distance of two atoms in a trajectory * @param t trajectory * @param atomindex1 index of first atom * @param atomindex2 index of second atom * @return variance of distance */ public static double getVarianceOfDistance(Trajectory t, int atomindex1, int atomindex2){ double mean = 0; ArrayList distr = getDistanceTimeSeries(t, atomindex1, atomindex2); for (int i = 0; i < distr.size(); i++) mean+=distr.get(i); mean = mean/distr.size(); double ret = 0; for (int i = 0; i < distr.size(); i++) ret+=Math.pow(distr.get(i)-mean,2); return ret/distr.size(); } /** * Returns the minimal distance of two atoms in a trajectory * @param t trajectory * @param atomindex1 index of first atom * @param atomindex2 index of second atom * @return minimal distance */ public static double getMinimalDistance(Trajectory t, int atomindex1, int atomindex2){ double ret = 999999; ArrayList distr = getDistanceTimeSeries(t, atomindex1, atomindex2); for (int i = 0; i < distr.size(); i++) { double value = distr.get(i); if (value distr = getDistanceTimeSeries(t, atomindex1, atomindex2); for (int i = 0; i < distr.size(); i++) { double value = distr.get(i); if (value>ret) ret=value; } return ret; } /** * Returns the range (max-min) of the distance of two atoms in a trajectory * @param t trajectory * @param atomindex1 index of first atom * @param atomindex2 index of second atom * @return size of distance interval */ public static double getDistanceRange(Trajectory t, int atomindex1, int atomindex2){ double min = 999999; double max = -999999; ArrayList distr = getDistanceTimeSeries(t, atomindex1, atomindex2); for (int i = 0; i < distr.size(); i++) { double value = distr.get(i); if (value>max) max=value; if (value atoms = atomIndices.getAsArrayList(); for (int j = 0; j < atoms.size(); j++) { Atom atom = s.getAtomByIndex(atoms.get(j)); if (isInProximity(s, atom, referenceIndices, radius)) ret.addIndex(atom.getIndex()); } return ret; } private static boolean isInProximity(Structure s, Atom atom, IndexSet referenceindices, double radius){ ArrayList indexList = s.convertIndicesToArrayListIndices(referenceindices); for (int i = 0; i < indexList.size(); i++) { int index = indexList.get(i); if (s.getAtom(index).distance(atom)<=radius) return true; } return false; } // Misc /** * Returns the frame in which two atoms are closest to each other in a simulation * @param t trajectory * @param atomindex1 index of first atom * @param atomindex2 index of second atom * @return frame of trajectory */ public static PointList findFrameWhereClosest(Trajectory t, int atomindex1, int atomindex2){ int best = 0; double min = 99999; for (int i = 0; i < t.getNumberOfFrames(); i++) { Structure frame = t.getFrameAsStructure(i); double dist = frame.getAtomByIndex(atomindex1).distance(frame.getAtomByIndex(atomindex2)); if (distmax){ max = dist; best = i; } } return t.getFrameAsPointList(best); } /** * Calculates the distance of an atom to a reference set of atoms (i.e. the minimum of all pairwise distances) * @param s structure * @param atomindex index of atom * @param referenceset index set of reference atoms * @return minimal distance */ public static double getDistanceOfAtomToAtomSet(Structure s, int atomindex, IndexSet referenceset){ double ret = 999999; Atom atom = s.getAtomByIndex(atomindex); ArrayList indexList = referenceset.getAsArrayList(); for (int i = 0; i < indexList.size(); i++) { Atom refatom = s.getAtomByIndex(indexList.get(i)); double dist = atom.distance(refatom); if (dist indexList1 = indices1.getAsArrayList(); ArrayList indexList2 = indices2.getAsArrayList(); for (int i = 0; i < indexList1.size(); i++) { Atom atom1 = s.getAtomByIndex(indexList1.get(i)); for (int j = 0; j < indexList2.size(); j++) { Atom atom2 = s.getAtomByIndex(indexList2.get(j)); double dist = atom1.distance(atom2); if (dist indexList = atomset.getAsArrayList(); for (int i = 0; i < indexList.size(); i++) { double dist = getDistanceOfAtomToAtomSet(s, indexList.get(i), referenceset); if (dist=cutoff) ret.addFrame(i); } String name1 = atomindex1+t.getFirstFrameAsStructure().getAtomByIndex(atomindex1).getName(); String name2 = atomindex2+t.getFirstFrameAsStructure().getAtomByIndex(atomindex2).getName(); ret.setName("Distant["+cutoff+"]["+name1+","+name2+"]"); return ret; } /** * Returns the list of frames in the trajectory where an atoms is closer to a reference point than a given cutoff * @param t trajectory * @param atomindex index of atom * @param point reference point * @param cutoff distance cutoff * @return frame list */ public static FrameIndexSet getFramesWhereAtomIsCloseToPoint(Trajectory t, int atomindex, Point3D point, double cutoff){ FrameIndexSet ret = new FrameIndexSet(); for (int i = 0; i < t.getNumberOfFrames(); i++) { Structure frame = t.getFrameAsStructure(i); if (frame.getAtomByIndex(atomindex).getCoordinates().distance(point)<=cutoff) ret.addFrame(i); } String name = atomindex+t.getFirstFrameAsStructure().getAtomByIndex(atomindex).getName(); ret.setName("Close["+cutoff+"]["+name+","+point+"]"); return ret; } /** * Returns the list of frames in the trajectory where an atoms is more distant from a reference point than a given cutoff * @param t trajectory * @param atomindex index of atom * @param point reference point * @param cutoff distance cutoff * @return frame list */ public static FrameIndexSet getFramesWhereAtomIsDistantFromPoint(Trajectory t, int atomindex, Point3D point, double cutoff){ FrameIndexSet ret = new FrameIndexSet(); for (int i = 0; i < t.getNumberOfFrames(); i++) { Structure frame = t.getFrameAsStructure(i); if (frame.getAtomByIndex(atomindex).getCoordinates().distance(point)>=cutoff) ret.addFrame(i); } String name = atomindex+t.getFirstFrameAsStructure().getAtomByIndex(atomindex).getName(); ret.setName("Distant["+cutoff+"]["+name+","+point+"]"); return ret; } } source/jgromacs/analysis/Dynamics.java000644 000000647341164714072000140460ustar /** * * Written by Márton Münz and Philip C Biggin * Copyright (c) University of Oxford, United Kingdom * Visit http://sbcb.bioch.ox.ac.uk/jgromacs/ * * This source code file is part of JGromacs v1.0. * * JGromacs v1.0 is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * JGromacs v1.0. is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with JGromacs v1.0. If not, see . * */ package jgromacs.analysis; import java.util.ArrayList; import jgromacs.data.IndexSet; import jgromacs.data.Point3D; import jgromacs.data.PointList; import jgromacs.data.Structure; import jgromacs.data.Trajectory; import jama.EigenvalueDecomposition; import jama.Matrix; /** * Collection of methods for analysing molecular motions * */ public class Dynamics { // Covariance and correlation matrices /** * Calculates the 3Nx3N coordinate covariance matrix from a trajectory and a reference frame for superposition * @param t trajectory * @param reference reference frame * @return coordinate covariance matrix */ public static Matrix getCoordinateCovarianceMatrix(Trajectory t, PointList reference){ int numofatoms = t.getNumberOfAtoms(); int numofframes = t.getNumberOfFrames(); Matrix ret = new Matrix(3*numofatoms,3*numofatoms,0); t = Superposition.superposeTo(t, reference); PointList mean = t.getMeanFrame(); for (int i = 0; i < numofframes; i++) { PointList frame = t.getFrameAsPointList(i); for (int k = 0; k < numofatoms; k++) { Point3D pointk = frame.getPoint(k); Point3D meank = mean.getPoint(k); double dx_k = pointk.getX()-meank.getX(); double dy_k = pointk.getY()-meank.getY(); double dz_k = pointk.getZ()-meank.getZ(); for (int j = k; j < numofatoms; j++) { Point3D pointj = frame.getPoint(j); Point3D averagej = mean.getPoint(j); double dx_j = pointj.getX()-averagej.getX(); double dy_j = pointj.getY()-averagej.getY(); double dz_j = pointj.getZ()-averagej.getZ(); ret.set(k*3, j*3, ret.get(k*3, j*3)+dx_k*dx_j); ret.set(k*3, j*3+1, ret.get(k*3, j*3+1)+dx_k*dy_j); ret.set(k*3, j*3+2, ret.get(k*3, j*3+2)+dx_k*dz_j); ret.set(k*3+1, j*3, ret.get(k*3+1, j*3)+dy_k*dx_j); ret.set(k*3+1, j*3+1, ret.get(k*3+1, j*3+1)+dy_k*dy_j); ret.set(k*3+1, j*3+2, ret.get(k*3+1, j*3+2)+dy_k*dz_j); ret.set(k*3+2, j*3, ret.get(k*3+2, j*3)+dz_k*dx_j); ret.set(k*3+2, j*3+1, ret.get(k*3+2, j*3+1)+dz_k*dy_j); ret.set(k*3+2, j*3+2, ret.get(k*3+2, j*3+2)+dz_k*dz_j); } } } double n = numofframes; // numofframes-1; ret = ret.times(1/n); for (int i = 0; i < ret.getRowDimension(); i++) { for (int j = i; j < ret.getColumnDimension(); j++) { ret.set(j, i, ret.get(i,j)); } } return ret; } /** * Calculates the NxN atomic covariance matrix from a trajectory and a reference frame for superposition * @param t trajectory * @param reference reference frame * @return atomic covariance matrix */ public static Matrix getAtomicCovarianceMatrix(Trajectory t, PointList reference){ int numofatoms = t.getNumberOfAtoms(); int numofframes = t.getNumberOfFrames(); Matrix ret = new Matrix(numofatoms,numofatoms,0); t = Superposition.superposeTo(t, reference); PointList mean = t.getMeanFrame(); for (int i = 0; i < numofframes; i++) { PointList frame = t.getFrameAsPointList(i); for (int k = 0; k < numofatoms; k++) { Point3D pointk = frame.getPoint(k); Point3D meank = mean.getPoint(k); Point3D devK = pointk.minus(meank); for (int j = k; j < numofatoms; j++) { Point3D pointj = frame.getPoint(j); Point3D meanj = mean.getPoint(j); Point3D devJ = pointj.minus(meanj); double value = devK.innerProduct(devJ); ret.set(k, j, ret.get(k, j)+value); } } } double n = numofframes; // numofframes-1 ret = ret.times(1/n); for (int i = 0; i < ret.getRowDimension(); i++) { for (int j = i; j < ret.getColumnDimension(); j++) { ret.set(j, i, ret.get(i,j)); } } return ret; } /** * Calculates the 3Nx3N coordinate correlation matrix from a trajectory and a reference frame for superposition * @param t trajectory * @param reference reference frame * @return coordinate correlation matrix */ public static Matrix getCoordinateCorrelationMatrix(Trajectory t, PointList reference){ Matrix cov = getCoordinateCovarianceMatrix(t, reference); Matrix ret = new Matrix(cov.getRowDimension(),cov.getColumnDimension()); for (int i = 0; i < ret.getRowDimension(); i++) { for (int j = i; j < ret.getColumnDimension(); j++) { ret.set(i, j, cov.get(i, j)/Math.sqrt(cov.get(i, i)*cov.get(j, j))); ret.set(j, i, ret.get(i, j)); } } return ret; } /** * Calculates the NxN atomic correlation matrix from a trajectory and a reference frame for superposition * @param t trajectory * @param reference reference frame * @return atomic correlation matrix */ public static Matrix getAtomicCorrelationMatrix(Trajectory t, PointList reference){ Matrix cov = getAtomicCovarianceMatrix(t, reference); Matrix ret = new Matrix(cov.getRowDimension(),cov.getColumnDimension()); for (int i = 0; i < ret.getRowDimension(); i++) { for (int j = i; j < ret.getColumnDimension(); j++) { ret.set(i, j, cov.get(i, j)/Math.sqrt(cov.get(i, i)*cov.get(j, j))); ret.set(j, i, ret.get(i, j)); } } return ret; } /** * Calculates the 3Nx3N coordinate covariance matrix from a trajectory using its first frame as the reference frame for superposition * @param t trajectory * @return coordinate covariance matrix */ public static Matrix getCoordinateCovarianceMatrix(Trajectory t){ return getCoordinateCovarianceMatrix(t,t.getFirstFrameAsPointList()); } /** * Calculates the NxN atomic covariance matrix from a trajectory using its first frame as the reference frame for superposition * @param t trajectory * @return atomic covariance matrix */ public static Matrix getAtomicCovarianceMatrix(Trajectory t){ return getAtomicCovarianceMatrix(t,t.getFirstFrameAsPointList()); } /** * Calculates the 3Nx3N coordinate correlation matrix from a trajectory using its first frame as the reference frame for superposition * @param t trajectory * @return coordinate correlation matrix */ public static Matrix getCoordinateCorrelationMatrix(Trajectory t){ return getCoordinateCorrelationMatrix(t,t.getFirstFrameAsPointList()); } /** * Calculates the NxN atomic correlation matrix from a trajectory using its first frame as the reference frame for superposition * @param t trajectory * @return atomic correlation matrix */ public static Matrix getAtomicCorrelationMatrix(Trajectory t){ return getAtomicCorrelationMatrix(t,t.getFirstFrameAsPointList()); } // PCA and related /** * Calculates the principal components and the corresponding eigenvalues from a covariance matrix * @param covariance covariance matrix * @return a Matrix array containing D (block diagonal eigenvalue matrix) and V (principal component matrix) */ public static Matrix[] getPCA(Matrix covariance){ EigenvalueDecomposition evd = new EigenvalueDecomposition(covariance); Matrix D = evd.getD(); Matrix V = evd.getV(); Matrix[] ret = new Matrix[2]; ret[0] = D; ret[1] = V; return ret; } /** * Calculates the principal components and the corresponding eigenvalues from a trajectory * @param t trajectory * @return a Matrix array containing D (block diagonal eigenvalue matrix) and V (principal component matrix) */ public static Matrix[] getPCA(Trajectory t){ Matrix covariance = getCoordinateCovarianceMatrix(t); return getPCA(covariance); } /** * Calculates the cumulative variance profile from a trajectory * @param t trajectory * @return cumulative variance profile */ public static ArrayList getCumulativeVariances(Trajectory t){ ArrayList ret = new ArrayList(); Matrix[] result = Dynamics.getPCA(t); Matrix D = result[0]; int dim = D.getRowDimension(); double N = D.trace(); double sum = 0; for (int i = 0; i < dim; i++) { sum+=D.get(dim-i-1, dim-i-1); ret.add(sum/N); } return ret; } /** * Calculates the cumulative variance profile from a covariance matrix * @param covariance covariance matrix * @return cumulative variance profile */ public static ArrayList getCumulativeVariances(Matrix covariance){ ArrayList ret = new ArrayList(); Matrix[] result = Dynamics.getPCA(covariance); Matrix D = result[0]; int dim = D.getRowDimension(); double N = D.trace(); double sum = 0; for (int i = 0; i < dim; i++) { sum+=D.get(dim-i-1, dim-i-1); ret.add(sum/N); } return ret; } /** * Calculates the root mean square inner product (RMSIP) from two covariance matrices * @param covariance1 first covariance matrix * @param covariance2 second covariance matrix * @param N number of principal components used from the first trajectory * @param M number of principal components used from the second trajectory * @return root mean square inner product (RMSIP) */ public static double getRootMeanSquareInnerProduct(Matrix covariance1, Matrix covariance2, int N, int M){ EigenvalueDecomposition evd1 = new EigenvalueDecomposition(covariance1); Matrix V1 = evd1.getV(); EigenvalueDecomposition evd2 = new EigenvalueDecomposition(covariance2); Matrix V2 = evd2.getV(); double ret = 0; int dim = evd1.getD().getColumnDimension(); for (int i = dim-1; i >= dim-N; i--) { for (int j = dim-1; j >= dim-M; j--) ret+=product(V1,V2,i,j); } return Math.sqrt(ret/N); } private static double product(Matrix V1, Matrix V2, int i, int j){ double ret = 0; for (int k = 0; k < V1.getRowDimension(); k++) ret+=V1.get(k, i)*V2.get(k, j); return ret*ret; } /** * Calculates the root mean square inner product (RMSIP) from two trajectories * @param t1 first trajectory * @param t2 second trajectory * @param N number of principal components used from the first trajectory * @param M number of principal components used from the second trajectory * @return root mean square inner product (RMSIP) */ public static double getRootMeanSquareInnerProduct(Trajectory t1, Trajectory t2, int N, int M){ Matrix covariance1 = getCoordinateCovarianceMatrix(t1); Matrix covariance2 = getCoordinateCovarianceMatrix(t2); return getRootMeanSquareInnerProduct(covariance1,covariance2,N,M); } /** * Calculates the covariance overlap of two covariance matrices * @param covariance1 first covariance matrix * @param covariance2 second covariance matrix * @param N number of dimensions used in the calculation * @return covariance overlap */ public static double getCovarianceMatrixOverlap(Matrix covariance1, Matrix covariance2, int N){ EigenvalueDecomposition evd1 = new EigenvalueDecomposition(covariance1); Matrix D1 = evd1.getD(); Matrix V1 = evd1.getV(); EigenvalueDecomposition evd2 = new EigenvalueDecomposition(covariance2); Matrix D2 = evd2.getD(); Matrix V2 = evd2.getV(); double A = 0; double B = 0; int dim = D1.getRowDimension(); for (int i = dim-N; i < dim; i++) A+=(D1.get(i, i)+D2.get(i, i)); for (int i = dim-N; i < dim; i++) { for (int j = dim-N; j < dim; j++) { double x = 0; for (int k = 0; k < dim; k++) x+=V1.get(k, i)*V2.get(k, j); B+= Math.sqrt(Math.abs(D1.get(i, i)*D2.get(j, j)))*Math.pow(x, 2); } } //return 1-Math.sqrt(Math.abs((A-2*B)/A)); return 1-Math.sqrt(A-2*B)/Math.sqrt(A); } /** * Calculates the covariance overlap of two covariance matrices * @param covariance1 first covariance matrix * @param covariance2 second covariance matrix * @return covariance overlap */ public static double getCovarianceMatrixOverlap(Matrix covariance1, Matrix covariance2){ EigenvalueDecomposition evd1 = new EigenvalueDecomposition(covariance1); Matrix D1 = evd1.getD(); Matrix V1 = evd1.getV(); EigenvalueDecomposition evd2 = new EigenvalueDecomposition(covariance2); Matrix D2 = evd2.getD(); Matrix V2 = evd2.getV(); double A = 0; double B = 0; int dim = D1.getRowDimension(); for (int i = 0; i < dim; i++) A+=(D1.get(i, i)+D2.get(i, i)); for (int i = 0; i < dim; i++) { for (int j = 0; j < dim; j++) { double x = 0; for (int k = 0; k < dim; k++) x+=V1.get(k, i)*V2.get(k, j); B+= Math.sqrt(Math.abs(D1.get(i, i)*D2.get(j, j)))*Math.pow(x, 2); } } //return 1-Math.sqrt(Math.abs((A-2*B)/A)); return 1-Math.sqrt(A-2*B)/Math.sqrt(A); } /** * Calculates the covariance overlap from two trajectories * @param t1 first trajectory * @param t2 second trajectory * @param N number of dimensions used in the calculation * @return covariance overlap */ public static double getCovarianceMatrixOverlap(Trajectory t1, Trajectory t2, int N){ Matrix covariance1 = getCoordinateCovarianceMatrix(t1); Matrix covariance2 = getCoordinateCovarianceMatrix(t2); return getCovarianceMatrixOverlap(covariance1, covariance2, N); } /** * Calculates the covariance overlap from two trajectories * @param t1 first trajectory * @param t2 second trajectory * @return covariance overlap */ public static double getCovarianceMatrixOverlap(Trajectory t1, Trajectory t2){ Matrix covariance1 = getCoordinateCovarianceMatrix(t1); Matrix covariance2 = getCoordinateCovarianceMatrix(t2); return getCovarianceMatrixOverlap(covariance1, covariance2); } // Fluctuations /** * Calculates the F fluctuation matrix (variances of distances) from a trajectory * @param t trajectory * @return F fluctuation matrix */ public static Matrix getFluctuationMatrix(Trajectory t){ int dim = t.getNumberOfAtoms(); Matrix ret = new Matrix(dim, dim, 0); Matrix mean = Distances.getMeanAtomicDistanceMatrix(t); for (int i = 0; i < t.getNumberOfFrames(); i++) { PointList frame = t.getFrameAsPointList(i); Matrix D = Distances.getDistanceMatrix(frame); for (int j = 0; j < dim; j++) { for (int k = j+1; k < dim; k++) { ret.set(j, k, ret.get(j, k)+Math.pow(D.get(j, k)-mean.get(j, k),2)); } } } ret = ret.times(1.0/t.getNumberOfFrames()); for (int i = 0; i < dim; i++) { for (int j = i+1; j < dim; j++) { ret.set(j, i, ret.get(i, j)); } } return ret; } /** * Calculates the F fluctuation matrix (variances of distances) for a group of atoms * @param t trajectory * @param indices index set of atoms * @return F fluctuation matrix */ public static Matrix getFluctuationMatrix(Trajectory t, IndexSet indices){ int dim = indices.getNumberOfIndices(); Matrix ret = new Matrix(dim, dim, 0); Matrix mean = Distances.getMeanAtomicDistanceMatrix(t, indices); for (int i = 0; i < t.getNumberOfFrames(); i++) { Structure frame = t.getFrameAsStructure(i); Matrix D = Distances.getAtomicDistanceMatrix(frame, indices); for (int j = 0; j < dim; j++) { for (int k = j+1; k < dim; k++) { ret.set(j, k, ret.get(j, k)+Math.pow(D.get(j, k)-mean.get(j, k),2)); } } } ret = ret.times(1.0/t.getNumberOfFrames()); for (int i = 0; i < dim; i++) { for (int j = i+1; j < dim; j++) { ret.set(j, i, ret.get(i, j)); } } return ret; } /** * Calculates the fluctuation between two subsets of atoms defined as the mean of entries * of the selected submatrix of matrix F (fluctuation matrix) * @param t trajectory * @param set1 first subset * @param set2 second subset * @return fluctuation between the two atom sets */ public static double getFluctuationOfSubsets(Trajectory t, IndexSet set1, IndexSet set2){ double ret = 0; Matrix F = getFluctuationMatrix(t); ArrayList indexList1 = t.getFrameAsStructure(0).convertIndicesToArrayListIndices(set1); ArrayList indexList2 = t.getFrameAsStructure(0).convertIndicesToArrayListIndices(set2); for (int i = 0; i < indexList1.size(); i++) { for (int j = 0; j < indexList2.size(); j++) { ret+=F.get(indexList1.get(i), indexList2.get(j)); } } return ret/(indexList1.size()*indexList2.size()); } /** * Calculates the RMSF profile from a trajectory and a reference frame for superposition * @param t trajectory * @param R reference frame * @return RMSF profile */ public static ArrayList getRMSFprofile(Trajectory t, PointList R){ ArrayList ret = new ArrayList(); int numofatoms = t.getNumberOfAtoms(); for (int i = 0; i < numofatoms; i++) ret.add(0.0); int K = t.getNumberOfFrames(); for (int k = 0; k < K; k++) { PointList frame = t.getFrameAsPointList(k); ArrayList RMSDi = Similarity.getRMSDiProfile(frame, R); for (int i = 0; i < numofatoms; i++) ret.set(i, ret.get(i)+Math.pow(RMSDi.get(i),2)); } for (int i = 0; i < numofatoms; i++) ret.set(i, Math.sqrt(ret.get(i)/K)); return ret; } /** * Calculates the RMSF profile from a trajectory and a reference frame for superposition * @param t trajectory * @param R reference frame * @return RMSF profile */ public static ArrayList getRMSFprofile(Trajectory t, Structure R){ return getRMSFprofile(t,R.getAllAtomCoordinates()); } /** * Calculates the RMSF profile of a group of atoms from a trajectory and a reference frame for superposition * @param t trajectory * @param indicesT index set of atoms used from the trajectory * @param R reference frame * @param indicesR index set of atoms used from the reference frame * @return RMSF profile */ public static ArrayList getRMSFprofile(Trajectory t, IndexSet indicesT, Structure R, IndexSet indicesR){ ArrayList ret = new ArrayList(); ArrayList indexListT = t.getFrameAsStructure(0).convertIndicesToArrayListIndices(indicesT); ArrayList indexListR = R.convertIndicesToArrayListIndices(indicesR); PointList reference = R.getAllAtomCoordinates().getSubList(indexListR); int numofatoms = indexListT.size(); for (int i = 0; i < numofatoms; i++) ret.add(0.0); int K = t.getNumberOfFrames(); for (int k = 0; k < K; k++) { PointList frame = t.getFrameAsPointList(k).getSubList(indexListT); ArrayList RMSDi = Similarity.getRMSDiProfile(frame, reference); for (int i = 0; i < numofatoms; i++) ret.set(i, ret.get(i)+Math.pow(RMSDi.get(i),2)); } for (int i = 0; i < numofatoms; i++) ret.set(i, Math.sqrt(ret.get(i)/K)); return ret; } /** * Calculates the RMSF profile from a trajectory by superposing all frames to a reference frame R * and calculating the RMSDi deviations with regards to a reference frame Q * @param t trajectory * @param R reference frame to which all frames are superposed * @param Q reference frame from which deviations are measured * @return RMSF profile */ public static ArrayList getRMSFprofile(Trajectory t, PointList R, PointList Q){ ArrayList ret = new ArrayList(); int numofatoms = t.getNumberOfAtoms(); for (int i = 0; i < numofatoms; i++) ret.add(0.0); int K = t.getNumberOfFrames(); for (int k = 0; k < K; k++) { PointList frame = t.getFrameAsPointList(k); PointList superposed = Superposition.superposeTo(frame, R); ArrayList RMSDi = Similarity.getRMSDiProfileNoSuperposition(superposed, Q); for (int i = 0; i < numofatoms; i++) ret.set(i, ret.get(i)+Math.pow(RMSDi.get(i),2)); } for (int i = 0; i < numofatoms; i++) ret.set(i, Math.sqrt(ret.get(i)/K)); return ret; } /** * Calculates the RMSF profile from a trajectory by superposing all frames to a reference frame R * and calculating the RMSDi deviations with regards to a reference frame Q * @param t trajectory * @param R reference frame to which all frames are superposed * @param Q reference frame from which deviations are measured * @return RMSF profile */ public static ArrayList getRMSFprofile(Trajectory t, Structure R, Structure Q){ return getRMSFprofile(t,R.getAllAtomCoordinates(),Q.getAllAtomCoordinates()); } /** * Calculates the RMSF profile from a trajectory by superposing all frames to a reference frame R * and calculating the RMSDi deviations with regards to the mean structure * @param t trajectory * @param R reference frame * @return RMSF profile */ public static ArrayList getRMSFaroundTheMeanProfile(Trajectory t, PointList R){ ArrayList ret = new ArrayList(); int numofatoms = t.getNumberOfAtoms(); for (int i = 0; i < numofatoms; i++) ret.add(0.0); Trajectory superposed = Superposition.superposeTo(t, R); PointList mean = superposed.getMeanFrame(); int K = superposed.getNumberOfFrames(); for (int k = 0; k < K; k++) { PointList frame = superposed.getFrameAsPointList(k); ArrayList RMSDi = Similarity.getRMSDiProfileNoSuperposition(frame, mean); for (int i = 0; i < numofatoms; i++) ret.set(i, ret.get(i)+Math.pow(RMSDi.get(i),2)); } for (int i = 0; i < numofatoms; i++) ret.set(i, Math.sqrt(ret.get(i)/K)); return ret; } /** * Calculates the RMSF profile from a trajectory by superposing all frames to a reference frame R * and calculating the RMSDi deviations with regards to the mean structure * @param t trajectory * @param R reference frame * @return RMSF profile */ public static ArrayList getRMSFaroundTheMeanProfile(Trajectory t, Structure R){ return getRMSFaroundTheMeanProfile(t,R.getAllAtomCoordinates()); } // Dynamical networks (Sethi et al. 2009) /** * Calculates the dynamical network of a protein according to the definition of Sethi et al. 2009 * (Dynamical networks in tRNA:protein complexes, PNAS) * @param t trajectory * @param cutoff distance cutoff for the calculation of contact matrix * @param frequency minimal frequency of frames in which two residues must be in contact * @return weighted adjacency matrix of dynamical network */ public static Matrix getDynamicalNetwork(Trajectory t, double cutoff, double frequency){ int d = t.getNumberOfResidues(); Matrix Adjacency = new Matrix(d,d,0); Matrix Contact = Distances.getFrequencyContactMatrix(t, Distances.CLOSESTHEAVY, cutoff, frequency); IndexSet alphaCarbons = t.getFirstFrameAsStructure().getAlphaCarbonIndexSet(); t = t.getSubTrajectory(alphaCarbons); Matrix Correlation = Dynamics.getAtomicCorrelationMatrix(t); for (int i = 0; i < d; i++) { for (int j = i+1; j < d; j++) { //if (Contact.get(i, j)==1) Adjacency.set(i, j, Math.abs(Correlation.get(i, j))); if (Contact.get(i, j)==1) Adjacency.set(i, j, -Math.log(Math.abs(Correlation.get(i, j)))); else Adjacency.set(i, j, Double.NaN); Adjacency.set(j, i, Adjacency.get(i, j)); } } return Adjacency; } // Structural radius (Kuzmanic and Zagrovic, 2010) /** * Calculates the structural radius of the conformational ensemble sampled in the trajectory * as defined by Kuzmanic and Zagrovic, 2010 * (Determination of Ensemble-Average Pairwise Root Mean-Square Deviation from Experimental B-Factors, Biophysical Journal) * @param t trajectory * @return structural radius */ public static double getStructuralRadius(Trajectory t){ double ret = 0; int Ns = t.getNumberOfFrames(); for (int i = 0; i < Ns; i++) { PointList frameI = t.getFrameAsPointList(i); for (int j = 0; j < Ns; j++) { PointList frameJ = t.getFrameAsPointList(j); ret+=Math.pow(Similarity.getRMSD(frameI, frameJ), 2); } } return Math.sqrt(ret/(2*Ns*Ns)); } // Ensemble averaged RMSD (Brüschweiler, 2002) /** * Calculates the ensemble averaged RMSD between two conformational ensembles sampled in two trajectories * as defined by Brüschweiler, 2002 * (Efficient RMSD measures for the comparison of two molecular ensembles, Proteins: Structure, Function, and Bioinformatics) * @param t1 first trajectory * @param t2 second trajectory * @return ensemble averaged RMSD */ public static double getEnsembleAveragedRMSD(Trajectory t1, Trajectory t2){ double ret = 0; int N = t1.getNumberOfFrames(); int M = t2.getNumberOfFrames(); for (int i = 0; i < N; i++) { PointList frameI = t1.getFrameAsPointList(i); for (int j = 0; j < M; j++) { PointList frameJ = t2.getFrameAsPointList(j); ret+=Math.pow(Similarity.getRMSD(frameI, frameJ), 2); } } double n = Double.valueOf(N*M); return Math.sqrt(ret/n); } // Contact probability map (Wei et al. 2009 ) /** * Calculates the (residue) contact probability map for a trajectory * as defined by Wei et al, 2009 * (Residual Structure in Islet Amyloid Polypeptide Mediates Its Interactions with Soluble Insulin, Biochemistry) * @param t simulation trajectory * @param cutoff distance cutoff * @return contact probability matrix */ public static Matrix getContactProbabilityMap(Trajectory t, double cutoff){ int dim = t.getNumberOfResidues(); Matrix ret = new Matrix(dim,dim,0); for (int k = 0; k < t.getNumberOfFrames(); k++) { Structure frame = t.getFrameAsStructure(k); Matrix C = Distances.getContactMatrix(frame, Distances.CLOSESTHEAVY, cutoff); ret = ret.plus(C); } ret = ret.times(1.0/t.getNumberOfFrames()); return ret; } // Trajectory of a single atom /** * Returns the trajectory of a single atom in the course of the simulation * @param t simulation trajectory * @param atomindex index of atom * @return atomic trajectory as an ArrayList of coordinates */ public static ArrayList getTrajectoryOfAtom(Trajectory t, int atomindex){ ArrayList ret = new ArrayList(); for (int i = 0; i < t.getNumberOfFrames(); i++) ret.add(t.getFrameAsStructure(i).getAtomByIndex(atomindex).getCoordinates()); return ret; } } source/jgromacs/analysis/GNM.java000644 000000063231163705234400127110ustar /** * * Written by Márton Münz and Philip C Biggin * Copyright (c) University of Oxford, United Kingdom * Visit http://sbcb.bioch.ox.ac.uk/jgromacs/ * * This source code file is part of JGromacs v1.0. * * JGromacs v1.0 is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * JGromacs v1.0. is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with JGromacs v1.0. If not, see . * */ package jgromacs.analysis; import jama.Matrix; import jama.SingularValueDecomposition; import java.util.ArrayList; import jgromacs.data.Structure; /** * Objects of this class represent a Gaussian Network Model (GNM) of a protein * */ public class GNM { private Matrix cM = new Matrix(1,1,0); private Matrix KM = new Matrix(1,1,0); private Matrix U = new Matrix(1,1,0); private Matrix Lambda = new Matrix(1,1,0); /** * Constructs a new Gaussian Network Model * @param s structure to be modelled * @param cutoff distance cutoff * @param distanceBetween which atoms are used for calculating the distances (ALPHACARBON: alpha carbon atoms, * CLOSEST: closest atoms of two residues, CLOSESTHEAVY: closest heavy atoms of two residues) */ public GNM(Structure s, double cutoff, int distanceBetween){ cM = Distances.getContactMatrix(s, distanceBetween, cutoff); KM = calculateKirchhoffMatrix(cM); SingularValueDecomposition svd = new SingularValueDecomposition(KM); U = svd.getU(); Lambda = svd.getS(); } /** * Returns the contact matrix * @return contact matrix */ public Matrix getContactMatrix(){ return cM; } /** * Returns the Kirchhoff matrix * @return Kirchhoff matrix */ public Matrix getKirchhoffMatrix(){ return KM; } /** * Returns the diagonal matrix of eigenvalues (Lambda) * @return Lambda matrix */ public Matrix getLambdaMatrix(){ return Lambda; } /** * Returns the orthogonal matrix of eigenvectors (U) * @return U matrix */ public Matrix getEigenvectorMatrix(){ return U; } /** * Calculates the mean square fluctuation (MSF) profile * @return MSF profile */ public ArrayList getMSFProfile(){ ArrayList ret = new ArrayList(); int resnum = Lambda.getRowDimension(); for (int i = 0; i < resnum; i++) { double msf = 0; for (int q = 0; q < resnum-1; q++) msf+=Math.pow(U.get(i, q),2)/Lambda.get(q, q); ret.add(msf); } return ret; } private static Matrix calculateKirchhoffMatrix(Matrix cM){ Matrix ret = cM.times(-1); int resnum = ret.getRowDimension(); for (int i = 0; i < resnum; i++) { double sum = 0; for (int j = 0; j < resnum; j++) if (j!=i) sum+=ret.get(i, j); ret.set(i, i, -sum); } return ret; } } source/jgromacs/analysis/package-info.java000644 000000002111157566051000146030ustar /** * jgromacs.analysis is a collection of classes providing static methods for various analysis tasks */ package jgromacs.analysis;source/jgromacs/analysis/Similarity.java000644 000000661351164754071600144330ustar /** * * Written by Márton Münz and Philip C Biggin * Copyright (c) University of Oxford, United Kingdom * Visit http://sbcb.bioch.ox.ac.uk/jgromacs/ * * This source code file is part of JGromacs v1.0. * * JGromacs v1.0 is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * JGromacs v1.0. is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with JGromacs v1.0. If not, see . * */ package jgromacs.analysis; import java.util.ArrayList; import jgromacs.data.FrameIndexSet; import jgromacs.data.IndexSet; import jgromacs.data.PointList; import jgromacs.data.Structure; import jgromacs.data.Trajectory; import jama.Matrix; /** * Collection of methods for measuring structural similarity * */ public class Similarity { // Coordinate-based measures /** * Calculates RMSD similarity between two point lists * @param A first point list * @param B second point list * @return RMSD */ public static double getRMSD(PointList A, PointList B){ PointList superposedA = Superposition.superposeTo(A, B); return getRMSDnoSuperposition(superposedA, B); } /** * Calculates RMSD similarity between two structures * @param A first structure * @param B second structure * @return RMSD */ public static double getRMSD(Structure A, Structure B){ return getRMSD(A.getAllAtomCoordinates(),B.getAllAtomCoordinates()); } /** * Calculates RMSD similarity between two groups of atoms * @param A first structure * @param indicesA index set of atoms in the first structure * @param B second structure * @param indicesB index set of atoms in the second structure * @return RMSD */ public static double getRMSD(Structure A, IndexSet indicesA, Structure B, IndexSet indicesB){ Structure subA = A.getSubStructure(indicesA); Structure subB = B.getSubStructure(indicesB); return getRMSD(subA, subB); } /** * Calculates the RMSDi profile between two point lists * @param A first point list * @param B second point list * @return RMSDi profile */ public static ArrayList getRMSDiProfile(PointList A, PointList B){ PointList superposedA = Superposition.superposeTo(A, B); return getRMSDiProfileNoSuperposition(superposedA, B); } /** * Calculates the RMSDi profile between two structures * @param A first structure * @param B second structure * @return RMSDi profile */ public static ArrayList getRMSDiProfile(Structure A, Structure B){ return getRMSDiProfile(A.getAllAtomCoordinates(),B.getAllAtomCoordinates()); } /** * Calculates the RMSDi profile between two groups of atoms * @param A first structure * @param indicesA index set of atoms in the first structure * @param B second structure * @param indicesB index set of atoms in the second structure * @return RMSDi profile */ public static ArrayList getRMSDiProfile(Structure A, IndexSet indicesA, Structure B, IndexSet indicesB){ Structure subA = A.getSubStructure(indicesA); Structure subB = B.getSubStructure(indicesB); return getRMSDiProfile(subA,subB); } /** * Calculates RMSD similarity between two point lists without doing superposition * @param A first point list * @param B second point list * @return RMSD without superposition */ public static double getRMSDnoSuperposition(PointList A, PointList B){ double ret = 0; for (int i = 0; i < A.getNumberOfPoints(); i++) ret+= Math.pow(A.getPoint(i).distance(B.getPoint(i)),2); double n = (double)A.getNumberOfPoints(); return Math.sqrt(ret/n); } /** * Calculates RMSD similarity between two structures without doing superposition * @param A first structure * @param B second structure * @return RMSD without superposition */ public static double getRMSDnoSuperposition(Structure A, Structure B){ return getRMSDnoSuperposition(A.getAllAtomCoordinates(),B.getAllAtomCoordinates()); } /** * Calculates RMSD similarity between two groups of atoms without superposition * @param A first structure * @param indicesA index set of atoms in the first structure * @param B second structure * @param indicesB index set of atoms in the second structure * @return RMSD without superposition */ public static double getRMSDnoSuperposition(Structure A, IndexSet indicesA, Structure B, IndexSet indicesB){ Structure subA = A.getSubStructure(indicesA); Structure subB = B.getSubStructure(indicesB); return getRMSDnoSuperposition(subA, subB); } /** * Calculates the RMSDi profile between two point lists without superposition * @param A first point list * @param B second point list * @return RMSDi profile without superposition */ public static ArrayList getRMSDiProfileNoSuperposition(PointList A, PointList B){ ArrayList ret = new ArrayList(); for (int i = 0; i < A.getNumberOfPoints(); i++) ret.add(A.getPoint(i).distance(B.getPoint(i))); return ret; } /** * Calculates the RMSDi profile between two structures without superposition * @param A first structure * @param B second structure * @return RMSDi profile without superposition */ public static ArrayList getRMSDiProfileNoSuperposition(Structure A, Structure B){ return getRMSDiProfileNoSuperposition(A.getAllAtomCoordinates(),B.getAllAtomCoordinates()); } /** * Calculates the RMSDi profile between two groups of atoms without superposition * @param A first structure * @param indicesA index set of atoms in the first structure * @param B second structure * @param indicesB index set of atoms in the second structure * @return RMSDi profile without superposition */ public static ArrayList getRMSDiProfileNoSuperposition(Structure A, IndexSet indicesA, Structure B, IndexSet indicesB){ Structure subA = A.getSubStructure(indicesA); Structure subB = B.getSubStructure(indicesB); return getRMSDiProfileNoSuperposition(subA, subB); } // Distance-based measures /** * Calculates dRMSD similarity between two distance matrices * @param A first distance matrix * @param B second distance matrix * @return dRMSD */ public static double getDRMSD(Matrix A, Matrix B){ double ret = 0; int n = A.getRowDimension(); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { double dif = A.get(i, j)-B.get(i, j); ret+=Math.pow(dif, 2); } } return Math.sqrt(ret/(n*n)); } /** * Calculates dRMSD similarity between two point lists * @param A first point list * @param B second point list * @return dRMSD */ public static double getDRMSD(PointList A, PointList B){ double ret = 0; Matrix D1 = Distances.getDistanceMatrix(A); Matrix D2 = Distances.getDistanceMatrix(B); int n = D1.getRowDimension(); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { double dif = D1.get(i, j)-D2.get(i, j); ret+=Math.pow(dif, 2); } } return Math.sqrt(ret/(n*n)); } /** * Calculates dRMSD similarity between two structures * @param A first structure * @param B second structure * @return dRMSD */ public static double getDRMSD(Structure A, Structure B){ return getDRMSD(A.getAllAtomCoordinates(),B.getAllAtomCoordinates()); } /** * Calculates dRMSD similarity between two groups of atoms * @param A first structure * @param indicesA index set of atoms in the first structure * @param B second structure * @param indicesB index set of atoms in the second structure * @return dRMSD */ public static double getDRMSD(Structure A, IndexSet indicesA, Structure B, IndexSet indicesB){ Structure subA = A.getSubStructure(indicesA); Structure subB = B.getSubStructure(indicesB); return getDRMSD(subA, subB); } /** * Calculates the dRMSDi profile between two distance matrices * @param A first distance matrix * @param B second distance matrix * @return dRMSDi profile */ public static ArrayList getDRMSDiProfile(Matrix A, Matrix B){ ArrayList ret = new ArrayList(); int n = A.getRowDimension(); for (int i = 0; i < n; i++) { double drmsdi = 0; for (int j = 0; j < n; j++) drmsdi+=Math.pow(A.get(i, j)-B.get(i, j), 2); drmsdi = Math.sqrt(drmsdi/n); ret.add(drmsdi); } return ret; } /** * Calculates the dRMSDi profile between two point lists * @param A first point list * @param B second point list * @return dRMSDi profile */ public static ArrayList getDRMSDiProfile(PointList A, PointList B){ ArrayList ret = new ArrayList(); Matrix D1 = Distances.getDistanceMatrix(A); Matrix D2 = Distances.getDistanceMatrix(B); int n = D1.getRowDimension(); for (int i = 0; i < n; i++) { double drmsdi = 0; for (int j = 0; j < n; j++) drmsdi+=Math.pow(D1.get(i, j)-D2.get(i, j), 2); drmsdi = Math.sqrt(drmsdi/n); ret.add(drmsdi); } return ret; } /** * Calculates the dRMSDi profile between two structures * @param A first structure * @param B second structure * @return dRMSDi profile */ public static ArrayList getDRMSDiProfile(Structure A, Structure B){ return getDRMSDiProfile(A.getAllAtomCoordinates(),B.getAllAtomCoordinates()); } /** * Calculates the dRMSDi profile between two groups of atoms * @param A first structure * @param indicesA index set of atoms in the first structure * @param B second structure * @param indicesB index set of atoms in the second structure * @return dRMSDi profile */ public static ArrayList getDRMSDiProfile(Structure A, IndexSet indicesA, Structure B, IndexSet indicesB){ Structure subA = A.getSubStructure(indicesA); Structure subB = B.getSubStructure(indicesB); return getDRMSDiProfile(subA, subB); } /** * Calculates the wdRMSD (weighted dRMSD) similarity of two point lists * @param A first point list * @param B second point list * @param W weight matrix * @return wdRMSD */ public static double getWDRMSD(PointList A, PointList B, Matrix W){ double ret = 0; double N = 0; Matrix D1 = Distances.getDistanceMatrix(A); Matrix D2 = Distances.getDistanceMatrix(B); int n = D1.getRowDimension(); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { double dif = D1.get(i, j)-D2.get(i, j); ret+=W.get(i, j)*Math.pow(dif, 2); N+=W.get(i, j); } } return Math.sqrt(ret/N); } /** * Calculates the wdRMSD (weighted dRMSD) similarity of two structures * @param A first structure * @param B second structure * @param W weight matrix * @return wdRMSD */ public static double getWDRMSD(Structure A, Structure B, Matrix W){ return getWDRMSD(A.getAllAtomCoordinates(),B.getAllAtomCoordinates(),W); } /** * Calculates wdRMSD (weighted dRMSD) similarity between two groups of atoms * @param A first structure * @param indicesA index set of atoms in the first structure * @param B second structure * @param indicesB index set of atoms in the second structure * @param W weight matrix * @return wdRMSD */ public static double getWDRMSD(Structure A, IndexSet indicesA, Structure B, IndexSet indicesB, Matrix W){ Structure subA = A.getSubStructure(indicesA); Structure subB = B.getSubStructure(indicesB); return getWDRMSD(subA, subB, W); } /** * Calculates the wdRMSDi (weighted dRMSDi) profile between two point lists * @param A first point list * @param B second point list * @param W weight matrix * @return wdRMSDi profile */ public static ArrayList getWDRMSDiProfile(PointList A, PointList B, Matrix W){ ArrayList ret = new ArrayList(); Matrix D1 = Distances.getDistanceMatrix(A); Matrix D2 = Distances.getDistanceMatrix(B); int n = D1.getRowDimension(); for (int i = 0; i < n; i++) { double wdrmsdi = 0; double N = 0; for (int j = 0; j < n; j++) { double dif = D1.get(i, j)-D2.get(i, j); wdrmsdi+=W.get(i, j)*Math.pow(dif, 2); N+=W.get(i, j); } wdrmsdi = Math.sqrt(wdrmsdi/N); ret.add(wdrmsdi); } return ret; } /** * Calculates the wdRMSDi (weighted dRMSDi) profile between two structures * @param A first structure * @param B second structure * @param W weight matrix * @return wdRMSDi profile */ public static ArrayList getWDRMSDiProfile(Structure A, Structure B, Matrix W){ return getWDRMSDiProfile(A.getAllAtomCoordinates(),B.getAllAtomCoordinates(),W); } /** * Calculates the wdRMSDi (weighted dRMSDi) profile between two groups of atoms * @param A first structure * @param indicesA index set of atoms in the first structure * @param B second structure * @param indicesB index set of atoms in the second structure * @param W weight matrix * @return wdRMSDi profile */ public static ArrayList getWDRMSDiProfile(Structure A, IndexSet indicesA, Structure B, IndexSet indicesB, Matrix W){ Structure subA = A.getSubStructure(indicesA); Structure subB = B.getSubStructure(indicesB); return getWDRMSDiProfile(subA, subB, W); } // Similarity matrices /** * Calculates the similarity matrix of all frames in a trajectory using the RMSD measure * @param t trajectory * @return similarity matrix */ public static Matrix getSimilarityMatrixRMSD(Trajectory t){ int dim = t.getNumberOfFrames(); Matrix ret = new Matrix(dim,dim,0); for (int i = 0; i < dim; i++) { PointList frameI = t.getFrameAsPointList(i); for (int j = i+1; j < dim; j++) { PointList frameJ = t.getFrameAsPointList(j); double sim = getRMSD(frameI, frameJ); ret.set(i, j, sim); ret.set(j, i, sim); } } return ret; } /** * Calculates the similarity matrix of all frames in a trajectory using the RMSD measure * taking into account only a subset of atoms * @param t trajectory * @param indices index set of atoms * @return similarity matrix */ public static Matrix getSimilarityMatrixRMSD(Trajectory t, IndexSet indices){ int dim = t.getNumberOfFrames(); Matrix ret = new Matrix(dim,dim,0); for (int i = 0; i < dim; i++) { Structure frameI = t.getFrameAsStructure(i); for (int j = i+1; j < dim; j++) { Structure frameJ = t.getFrameAsStructure(j); double sim = getRMSD(frameI, indices, frameJ, indices); ret.set(i, j, sim); ret.set(j, i, sim); } } return ret; } /** * Calculates the similarity matrix of all frames in a trajectory using the dRMSD measure * @param t trajectory * @return similarity matrix */ public static Matrix getSimilarityMatrixDRMSD(Trajectory t){ int dim = t.getNumberOfFrames(); Matrix ret = new Matrix(dim,dim,0); for (int i = 0; i < dim; i++) { PointList frameI = t.getFrameAsPointList(i); for (int j = i+1; j < dim; j++) { PointList frameJ = t.getFrameAsPointList(j); double sim = getDRMSD(frameI, frameJ); ret.set(i, j, sim); ret.set(j, i, sim); } } return ret; } /** * Calculates the similarity matrix of all frames in a trajectory using the dRMSD measure * taking into account only a subset of atoms * @param t trajectory * @param indices index set of atoms * @return similarity matrix */ public static Matrix getSimilarityMatrixDRMSD(Trajectory t, IndexSet indices){ int dim = t.getNumberOfFrames(); Matrix ret = new Matrix(dim,dim,0); for (int i = 0; i < dim; i++) { Structure frameI = t.getFrameAsStructure(i); for (int j = i+1; j < dim; j++) { Structure frameJ = t.getFrameAsStructure(j); double sim = getDRMSD(frameI, indices, frameJ, indices); ret.set(i, j, sim); ret.set(j, i, sim); } } return ret; } /** * Calculates the similarity matrix of all frames in a trajectory using the wdRMSD (weighted dRMSD) measure * @param t trajectory * @param W weight matrix * @return similarity matrix */ public static Matrix getSimilarityMatrixWDRMSD(Trajectory t, Matrix W){ int dim = t.getNumberOfFrames(); Matrix ret = new Matrix(dim,dim,0); for (int i = 0; i < dim; i++) { PointList frameI = t.getFrameAsPointList(i); for (int j = i+1; j < dim; j++) { PointList frameJ = t.getFrameAsPointList(j); double sim = getWDRMSD(frameI, frameJ, W); ret.set(i, j, sim); ret.set(j, i, sim); } } return ret; } /** * Calculates the similarity matrix of all frames in a trajectory using the wdRMSD (weighted dRMSD) measure * taking into account only a subset of atoms * @param t trajectory * @param indices index set of atoms * @param W weight matrix * @return similarity matrix */ public static Matrix getSimilarityMatrixWDRMSD(Trajectory t, IndexSet indices, Matrix W){ int dim = t.getNumberOfFrames(); Matrix ret = new Matrix(dim,dim,0); for (int i = 0; i < dim; i++) { Structure frameI = t.getFrameAsStructure(i); for (int j = i+1; j < dim; j++) { Structure frameJ = t.getFrameAsStructure(j); double sim = getWDRMSD(frameI, indices, frameJ, indices, W); ret.set(i, j, sim); ret.set(j, i, sim); } } return ret; } // Similarity time series /** * Returns the time series of RMSD in a trajectory with regards to a reference point list * @param t trajectory * @param R reference point list * @return time series of RMSD */ public static ArrayList getSimilarityTimeSeriesRMSD(Trajectory t, PointList R){ ArrayList ret = new ArrayList(); int dim = t.getNumberOfFrames(); for (int i = 0; i < dim; i++) { PointList frame = t.getFrameAsPointList(i); ret.add(getRMSD(frame, R)); } return ret; } /** * Returns the time series of RMSD in a trajectory with regards to a reference structure * @param t trajectory * @param R reference structure * @return time series of RMSD */ public static ArrayList getSimilarityTimeSeriesRMSD(Trajectory t, Structure R){ return getSimilarityTimeSeriesRMSD(t,R.getAllAtomCoordinates()); } /** * Returns the time series of RMSD in a trajectory with regards to a reference structure * taking into account only a subset of atoms * @param t trajectory * @param indicesT index set of atoms in the trajectory * @param R reference structure * @param indicesR index set of atoms in the reference structure * @return time series of RMSD */ public static ArrayList getSimilarityTimeSeriesRMSD(Trajectory t, IndexSet indicesT, Structure R, IndexSet indicesR){ ArrayList ret = new ArrayList(); int dim = t.getNumberOfFrames(); for (int i = 0; i < dim; i++) { Structure frame = t.getFrameAsStructure(i); ret.add(getRMSD(frame, indicesT, R, indicesR)); } return ret; } /** * Returns the time series of dRMSD in a trajectory with regards to a reference point list * @param t trajectory * @param R reference point list * @return time series of dRMSD */ public static ArrayList getSimilarityTimeSeriesDRMSD(Trajectory t, PointList R){ ArrayList ret = new ArrayList(); int dim = t.getNumberOfFrames(); for (int i = 0; i < dim; i++) { PointList frame = t.getFrameAsPointList(i); ret.add(getDRMSD(frame, R)); } return ret; } /** * Returns the time series of dRMSD in a trajectory with regards to a reference structure * @param t trajectory * @param R reference structure * @return time series of dRMSD */ public static ArrayList getSimilarityTimeSeriesDRMSD(Trajectory t, Structure R){ return getSimilarityTimeSeriesDRMSD(t,R.getAllAtomCoordinates()); } /** * Returns the time series of dRMSD in a trajectory with regards to a reference structure * taking into account only a subset of atoms * @param t trajectory * @param indicesT index set of atoms in the trajectory * @param R reference structure * @param indicesR index set of atoms in the reference structure * @return time series of dRMSD */ public static ArrayList getSimilarityTimeSeriesDRMSD(Trajectory t, IndexSet indicesT, Structure R, IndexSet indicesR){ ArrayList ret = new ArrayList(); int dim = t.getNumberOfFrames(); for (int i = 0; i < dim; i++) { Structure frame = t.getFrameAsStructure(i); ret.add(getDRMSD(frame, indicesT, R, indicesR)); } return ret; } /** * Returns the time series of wdRMSD (weighted dRMSD) in a trajectory with regards to a reference point list * @param t trajectory * @param R reference point list * @param W weight matrix * @return time series of wdRMSD */ public static ArrayList getSimilarityTimeSeriesWDRMSD(Trajectory t, PointList R, Matrix W){ ArrayList ret = new ArrayList(); int dim = t.getNumberOfFrames(); for (int i = 0; i < dim; i++) { PointList frame = t.getFrameAsPointList(i); ret.add(getWDRMSD(frame, R, W)); } return ret; } /** * Returns the time series of wdRMSD (weighted dRMSD) in a trajectory with regards to a reference structure * @param t trajectory * @param R reference structure * @param W weight matrix * @return time series of wdRMSD */ public static ArrayList getSimilarityTimeSeriesWDRMSD(Trajectory t, Structure R, Matrix W){ return getSimilarityTimeSeriesWDRMSD(t,R.getAllAtomCoordinates(),W); } /** * Returns the time series of wdRMSD (weighted dRMSD) in a trajectory with regards to a reference structure * taking into account only a subset of atoms * @param t trajectory * @param indicesT index set of atoms in the trajectory * @param R reference structure * @param indicesR index set of atoms in the reference structure * @param W weight matrix * @return time series of wdRMSD */ public static ArrayList getSimilarityTimeSeriesWDRMSD(Trajectory t, IndexSet indicesT, Structure R, IndexSet indicesR, Matrix W){ ArrayList ret = new ArrayList(); int dim = t.getNumberOfFrames(); for (int i = 0; i < dim; i++) { Structure frame = t.getFrameAsStructure(i); ret.add(getWDRMSD(frame, indicesT, R, indicesR, W)); } return ret; } // Difference distance matrix /** * Calculates the difference distance matrix between two point lists * @param points1 first point list * @param points2 second point list * @return difference distance matrix * */ public static Matrix getDifferenceDistanceMatrix(PointList points1, PointList points2){ Matrix d1 = Distances.getDistanceMatrix(points1); Matrix d2 = Distances.getDistanceMatrix(points2); return d1.minus(d2); } /** * Calculates the atomic difference distance matrix between two structures * @param s1 first structure * @param s2 second structure * @return difference distance matrix * */ public static Matrix getDifferenceDistanceMatrix(Structure s1, Structure s2){ Matrix d1 = Distances.getAtomicDistanceMatrix(s1); Matrix d2 = Distances.getAtomicDistanceMatrix(s2); return d1.minus(d2); } /** * Calculates the atomic difference distance matrix between two sets of atoms defined by two index sets in two structures * @param s1 first structure * @param indices1 first index set * @param s2 second structure * @param indices2 second index set * @return difference distance matrix * */ public static Matrix getDifferenceDistanceMatrix(Structure s1, IndexSet indices1, Structure s2, IndexSet indices2){ Matrix d1 = Distances.getAtomicDistanceMatrix(s1, indices1); Matrix d2 = Distances.getAtomicDistanceMatrix(s2, indices2); return d1.minus(d2); } // Find similar frames /** * Returns the set of frames in a trajectory that are more similar to a reference frame (based on the RMSD similarity measure) than a cutoff value * @param t trajectory * @param reference reference frame * @param cutoff similarity cutoff * @return frame index set */ public static FrameIndexSet findSimilarFramesRMSD(Trajectory t, PointList reference, double cutoff){ FrameIndexSet ret = new FrameIndexSet(); for (int i = 0; i < t.getNumberOfFrames(); i++) { PointList frame = t.getFrameAsPointList(i); if (Similarity.getRMSD(frame, reference)<=cutoff) ret.addFrame(i); } ret.setName("Similar[RMSD:"+cutoff+"]"+"(to:Noname)"); return ret; } /** * Returns the list of frames in a trajectory that are more similar to a reference frame (based on the dRMSD similarity measure) than a cutoff value * @param t trajectory * @param reference reference frame * @param cutoff similarity cutoff * @return frame list */ public static FrameIndexSet findSimilarFramesDRMSD(Trajectory t, PointList reference, double cutoff){ FrameIndexSet ret = new FrameIndexSet(); for (int i = 0; i < t.getNumberOfFrames(); i++) { PointList frame = t.getFrameAsPointList(i); if (Similarity.getDRMSD(frame, reference)<=cutoff) ret.addFrame(i); } ret.setName("Similar[dRMSD:"+cutoff+"]"+"(to:Noname)"); return ret; } /** * Returns the list of frames in a trajectory that are more similar to a reference distance matrix (based on the dRMSD similarity measure) than a cutoff value * @param t trajectory * @param reference reference distance matrix * @param cutoff similarity cutoff * @return frame list */ public static FrameIndexSet findSimilarFramesDRMSD(Trajectory t, Matrix reference, double cutoff){ FrameIndexSet ret = new FrameIndexSet(); for (int i = 0; i < t.getNumberOfFrames(); i++) { PointList frame = t.getFrameAsPointList(i); if (Similarity.getDRMSD(Distances.getDistanceMatrix(frame), reference)<=cutoff) ret.addFrame(i); } ret.setName("Similar[dRMSD:"+cutoff+"]"+"(to:Noname)"); return ret; } // Medoids /** * Calculates the medoid frame of a trajectory using the RMSD measure * @param t trajectory * @return medoid frame */ public static PointList getMedoidRMSD(Trajectory t){ Matrix S = getSimilarityMatrixRMSD(t); int dim = S.getRowDimension(); int best = 0; double min = 99999; for (int i = 0; i < dim; i++) { double sum = 0; for (int j = 0; j < dim; j++) sum+=S.get(i, j); if (sum. * */ package jgromacs.analysis; import java.util.ArrayList; import jgromacs.data.IndexSet; import jgromacs.data.Point3D; import jgromacs.data.PointList; import jgromacs.data.Structure; import jgromacs.data.Trajectory; import jama.Matrix; import jama.SingularValueDecomposition; /** * Collection of methods for superposing structures * */ public class Superposition { // Non Weighted /** * Calculates the superposition of a point list to another * @param toBeSuperposed the point list to be superposed * @param reference the reference point list * @return superposed points */ public static PointList superposeTo(PointList toBeSuperposed, PointList reference){ PointList referencecopy = (PointList)reference.clone(); PointList forfitcopy = (PointList)toBeSuperposed.clone(); referencecopy.centerPoints(); forfitcopy.centerPoints(); Matrix Y = referencecopy.getAsMatrix(); Matrix X = forfitcopy.getAsMatrix(); Matrix C = X.times(Y.transpose()); SingularValueDecomposition svn = new SingularValueDecomposition(C); Matrix U = svn.getU(); Matrix V = svn.getV(); double d = Math.signum(C.det()); Matrix middle = new Matrix(3,3,0); middle.set(0, 0, 1); middle.set(1, 1, 1); middle.set(2, 2, d); Matrix R = V.times(middle.times(U.transpose())); forfitcopy.rotate(R); forfitcopy.translate(reference.getCentroid()); return forfitcopy; } /** * Calculates the superposition of a structure to another * @param toBeSuperposed the structure to be superposed * @param reference the reference structure * @return superposed structure */ public static Structure superposeTo(Structure toBeSuperposed, Structure reference){ PointList fitted = superposeTo(toBeSuperposed.getAllAtomCoordinates(), reference.getAllAtomCoordinates()); Structure ret = (Structure)toBeSuperposed.clone(); ret.setAllAtomCoordinates(fitted); return ret; } /** * Calculates the superposition of a structure to another using a subset of atoms for fitting * @param toBeSuperposed the structure to be superposed * @param indices1 first index set * @param reference the reference structure * @param indices2 second index set * @return superposed structure */ public static Structure superposeTo(Structure toBeSuperposed, IndexSet indices1, Structure reference, IndexSet indices2){ PointList superposed = (PointList)toBeSuperposed.getAllAtomCoordinates().clone(); PointList referencecopy = (PointList)reference.getSubStructure(indices2).getAllAtomCoordinates().clone(); PointList forfitcopy = (PointList)toBeSuperposed.getSubStructure(indices1).getAllAtomCoordinates().clone(); Structure ret = (Structure)toBeSuperposed.clone(); Point3D centroid = toBeSuperposed.getSubStructure(indices1).getAllAtomCoordinates().getCentroid(); for (int i = 0; i < superposed.getNumberOfPoints(); i++){ superposed.getPoint(i).setX(superposed.getPoint(i).getX()-centroid.getX()); superposed.getPoint(i).setY(superposed.getPoint(i).getY()-centroid.getY()); superposed.getPoint(i).setZ(superposed.getPoint(i).getZ()-centroid.getZ()); } referencecopy.centerPoints(); forfitcopy.centerPoints(); Matrix Y = referencecopy.getAsMatrix(); Matrix X = forfitcopy.getAsMatrix(); Matrix C = X.times(Y.transpose()); SingularValueDecomposition svn = new SingularValueDecomposition(C); Matrix U = svn.getU(); Matrix V = svn.getV(); double d = Math.signum(C.det()); Matrix middle = new Matrix(3,3,0); middle.set(0, 0, 1); middle.set(1, 1, 1); middle.set(2, 2, d); Matrix R = V.times(middle.times(U.transpose())); superposed.rotate(R); superposed.translate(reference.getSubStructure(indices2).getAllAtomCoordinates().getCentroid()); ret.setAllAtomCoordinates(superposed); return ret; } /** * Calculates the superposition of each frame of a trajectory to a common reference frame * @param t trajectory to be superposed * @param reference reference point list * @return superposed trajectory */ public static Trajectory superposeTo(Trajectory t, PointList reference){ Trajectory ret = new Trajectory(); for (int i = 0; i < t.getNumberOfFrames(); i++) { PointList frame = t.getFrameAsPointList(i); PointList fittedframe = superposeTo(frame, reference); ret.addFrame(fittedframe); } return ret; } /** * Calculates the superposition of each frame of a trajectory to a common reference frame * @param t trajectory to be superposed * @param reference reference structure * @return superposed trajectory */ public static Trajectory superposeTo(Trajectory t, Structure reference){ return superposeTo(t, reference.getAllAtomCoordinates()); } /** * Calculates the superposition of each frame of a trajectory to a common reference frame * using a subset of atoms for fitting * @param t trajectory to be superposed * @param reference reference structure * @param indices index set * @return superposed trajectory */ public static Trajectory superposeTo(Trajectory t, Structure reference, IndexSet indices){ Trajectory ret = new Trajectory(); for (int i = 0; i < t.getNumberOfFrames(); i++) { Structure frame = t.getFrameAsStructure(i); Structure fittedframe = superposeTo(frame, indices, reference, indices); ret.addFrame(fittedframe.getAllAtomCoordinates()); } return ret; } // Weighted /** * Calculates the weighted superposition of a point list to another * @param toBeSuperposed the point list to be superposed * @param reference the reference point list * @param weights vector of weights * @return superposed points */ public static PointList weightedSuperposeTo(PointList toBeSuperposed, PointList reference, ArrayList weights){ int numofpoints = toBeSuperposed.getNumberOfPoints(); // Computing weighted center of mass: Point3D muA = new Point3D(); Point3D muB = new Point3D(); double sumw = 0; for (int i = 0; i < numofpoints; i++) { muA = muA.plus(toBeSuperposed.getPoint(i).multiplyByScalar(weights.get(i))); muB = muB.plus(reference.getPoint(i).multiplyByScalar(weights.get(i))); sumw += weights.get(i); } muA = muA.multiplyByScalar(1.0/sumw); muB = muB.multiplyByScalar(1.0/sumw); // Weighted covariance matrix: Matrix C = new Matrix(3,3,0); for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { double sum = 0; for (int k = 0; k < numofpoints; k++) { double aki = 0; double muAi = 0; double bkj = 0; double muBj = 0; if (i==0) { aki = toBeSuperposed.getPoint(k).getX(); muAi = muA.getX(); } if (i==1) { aki = toBeSuperposed.getPoint(k).getY(); muAi = muA.getY(); } if (i==2) { aki = toBeSuperposed.getPoint(k).getZ(); muAi = muA.getZ(); } if (j==0) { bkj = reference.getPoint(k).getX(); muBj = muB.getX(); } if (j==1) { bkj = reference.getPoint(k).getY(); muBj = muB.getY(); } if (j==2) { bkj = reference.getPoint(k).getZ(); muBj = muB.getZ(); } sum+=weights.get(k)*(aki-muAi)*(bkj-muBj); } C.set(i, j, sum); } } // SVD of C SingularValueDecomposition svn = new SingularValueDecomposition(C); Matrix U = svn.getU(); Matrix V = svn.getV(); double lambda = Math.signum(C.det()); // Computing optimal rotation: Matrix middle = new Matrix(3,3,0); middle.set(0, 0, 1); middle.set(1, 1, 1); middle.set(2, 2, lambda); Matrix Rmin = V.times(middle.times(U.transpose())); // Computing optimal translation: Point3D Tmin = muB.minus(muA.transformByMatrix(Rmin)); // Rotate and translate PointList forfitcopy = (PointList)toBeSuperposed.clone(); forfitcopy.rotate(Rmin); forfitcopy.translate(Tmin); return forfitcopy; } /** * Calculates the weighted superposition of a structure to another * @param toBeSuperposed the structure to be superposed * @param reference the reference structure * @param weights vector of weights * @return superposed structure */ public static Structure weightedSuperposeTo(Structure toBeSuperposed, Structure reference, ArrayList weights){ PointList fitted = weightedSuperposeTo(toBeSuperposed.getAllAtomCoordinates(), reference.getAllAtomCoordinates(), weights); Structure ret = (Structure)toBeSuperposed.clone(); ret.setAllAtomCoordinates(fitted); return ret; } /** * Calculates the weighted superposition of each frame of a trajectory to a common reference frame * @param t trajectory to be superposed * @param reference reference point list * @param weights vector of weights * @return superposed trajectory */ public static Trajectory weightedSuperposeTo(Trajectory t, PointList reference, ArrayList weights){ Trajectory ret = new Trajectory(); for (int i = 0; i < t.getNumberOfFrames(); i++) { PointList frame = t.getFrameAsPointList(i); PointList fittedframe = weightedSuperposeTo(frame, reference, weights); ret.addFrame(fittedframe); } return ret; } /** * Calculates the weighted superposition of each frame of a trajectory to a common reference frame * @param t trajectory to be superposed * @param reference reference structure * @param weights vector of weights * @return superposed trajectory */ public static Trajectory weightedSuperposeTo(Trajectory t, Structure reference, ArrayList weights){ return weightedSuperposeTo(t, reference.getAllAtomCoordinates(), weights); } } source/jgromacs/data/000755 000000000001165162413600105075ustar source/jgromacs/data/Alignment.java000644 000000262261164137241000132720ustar /** * * Written by Márton Münz and Philip C Biggin * Copyright (c) University of Oxford, United Kingdom * Visit http://sbcb.bioch.ox.ac.uk/jgromacs/ * * This source code file is part of JGromacs v1.0. * * JGromacs v1.0 is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * JGromacs v1.0. is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with JGromacs v1.0. If not, see . * */ package jgromacs.data; import java.util.ArrayList; import jgromacs.db.ResidueType; /** * Objects of this class represent a sequence alignment * */ public class Alignment implements Cloneable{ private ArrayList sequences = new ArrayList(); // Constructors /** * Constructs a new Alignment object * * */ public Alignment(){ } // Getters and setters /** * Returns sequence #i of the alignment * @return sequence #i * */ public Sequence getSequence(int i){ return sequences.get(i); } /** * Returns sequences of the alignment as an ArrayList object * @return list of sequences as an ArrayList * */ public ArrayList getSequencesAsArrayList(){ return sequences; } /** * Returns the number of sequences in the alignment * @return number of sequences * */ public int getNumberOfSequences(){ return sequences.size(); } /** * Returns the length of the longest sequence in the alignment * @return length of longest sequence * */ public int getMaxSequenceLength(){ int ret = -9999; for (int i = 0; i < getNumberOfSequences(); i++) { if (getSequence(i).getSequenceLength()>ret) ret = getSequence(i).getSequenceLength(); } return ret; } /** * Returns the length of the shortest sequence in the alignment * @return length of shortest sequence * */ public int getMinSequenceLength(){ int ret = 9999; for (int i = 0; i < getNumberOfSequences(); i++) { if (getSequence(i).getSequenceLength() getMatchPositionIndicesAsArrayList(int i){ Sequence seq = getSequence(i); ArrayList ret = new ArrayList(); for (int j = 0; j < seq.getSequenceLengthWithGaps(); j++) { if (isMatchColumn(j)) ret.add(seq.getIndexOfPosition(j)); } return ret; } /** * Returns the most frequent residue type in column #i of the alignment * * @return most frequent residue type */ public ResidueType getMostFrequentResidueType(int i){ ArrayList histogram = new ArrayList(); for (int j = 0; j < 22; j++) histogram.add(0); for (int k = 0; k < getNumberOfSequences(); k++) { ResidueType type = getSequence(k).getResidueTypeOfPosition(i); if (type.get1LetterCode().equals("A")) histogram.set(0, histogram.get(0)+1); if (type.get1LetterCode().equals("R")) histogram.set(1, histogram.get(1)+1); if (type.get1LetterCode().equals("N")) histogram.set(2, histogram.get(2)+1); if (type.get1LetterCode().equals("D")) histogram.set(3, histogram.get(3)+1); if (type.get1LetterCode().equals("C")) histogram.set(4, histogram.get(4)+1); if (type.get1LetterCode().equals("E")) histogram.set(5, histogram.get(5)+1); if (type.get1LetterCode().equals("Q")) histogram.set(6, histogram.get(6)+1); if (type.get1LetterCode().equals("G")) histogram.set(7, histogram.get(7)+1); if (type.get1LetterCode().equals("H")) histogram.set(8, histogram.get(8)+1); if (type.get1LetterCode().equals("I")) histogram.set(9, histogram.get(9)+1); if (type.get1LetterCode().equals("L")) histogram.set(10, histogram.get(10)+1); if (type.get1LetterCode().equals("K")) histogram.set(11, histogram.get(11)+1); if (type.get1LetterCode().equals("M")) histogram.set(12, histogram.get(12)+1); if (type.get1LetterCode().equals("F")) histogram.set(13, histogram.get(13)+1); if (type.get1LetterCode().equals("P")) histogram.set(14, histogram.get(14)+1); if (type.get1LetterCode().equals("S")) histogram.set(15, histogram.get(15)+1); if (type.get1LetterCode().equals("T")) histogram.set(16, histogram.get(16)+1); if (type.get1LetterCode().equals("W")) histogram.set(17, histogram.get(17)+1); if (type.get1LetterCode().equals("Y")) histogram.set(18, histogram.get(18)+1); if (type.get1LetterCode().equals("V")) histogram.set(19, histogram.get(19)+1); if (type.get1LetterCode().equals("X")) histogram.set(20, histogram.get(20)+1); if (getSequence(k).getIndexOfPosition(i)==-999) histogram.set(21, histogram.get(21)+1); } int max = -1; for (int j = 0; j < histogram.size(); j++) { if (histogram.get(j)>max) max=histogram.get(j); } if (max==0) return null; for (int j = 0; j < histogram.size(); j++) { if (histogram.get(j)==max) { if (j==0) return new ResidueType(1); if (j==1) return new ResidueType(2); if (j==2) return new ResidueType(3); if (j==3) return new ResidueType(4); if (j==4) return new ResidueType(5); if (j==5) return new ResidueType(6); if (j==6) return new ResidueType(7); if (j==7) return new ResidueType(8); if (j==8) return new ResidueType(9); if (j==9) return new ResidueType(10); if (j==10) return new ResidueType(11); if (j==11) return new ResidueType(12); if (j==12) return new ResidueType(13); if (j==13) return new ResidueType(14); if (j==14) return new ResidueType(15); if (j==15) return new ResidueType(16); if (j==16) return new ResidueType(17); if (j==17) return new ResidueType(18); if (j==18) return new ResidueType(19); if (j==19) return new ResidueType(20); if (j==20) return new ResidueType(23); if (j==21) return new ResidueType(); } } return null; } /** * Returns the (majority) consensus sequence of the alignment * * @return consensus sequence */ public Sequence getConsensusSequence(){ Sequence ret = new Sequence("Consensus"); int lenght = getSequence(0).getSequenceLengthWithGaps(); for (int i = 0; i < lenght; i++) { ResidueType type = getMostFrequentResidueType(i); if (!type.equals(new ResidueType())) ret.addPosition(type,""); else ret.addGap(); } return ret; } // toString, clone, equals /** * Returns the String representation of alignment * * @return String representation */ public String toString(){ StringBuffer buf = new StringBuffer(); for (int i = 0; i < getNumberOfSequences(); i++){ if (i>0) buf.append("\n"); buf.append(getSequence(i).toString()); } return buf.toString(); } /** * Returns summary information about the alignment * * @return summary information */ public String toStringInfo(){ return "Alignment: ("+getNumberOfSequences()+" sequences)"; } /** * Returns an identical Alignment object * * @return clone of the alignment */ public Object clone(){ try { Alignment ret = (Alignment)super.clone(); ret.sequences = new ArrayList(); for (int i = 0; i < sequences.size(); i++) ret.addSequence((Sequence)sequences.get(i).clone()); return ret; } catch (CloneNotSupportedException e) { e.printStackTrace(); return null; } } /** * Returns true if the two alignments are identical * @param other the other alignment * */ public boolean equals(Object other){ if (other == null) return false; if (other == this) return true; if (this.getClass() != other.getClass()) return false; Alignment alignment = (Alignment)other; if (alignment.getNumberOfSequences()!=getNumberOfSequences()) return false; for (int i = 0; i < getNumberOfSequences(); i++) { if (!getSequence(i).equals(alignment.getSequence(i))) return false; } return true; } /** * Returns hash code * */ public int hashCode() { return sequences.size(); } } source/jgromacs/data/Angle.java000644 000000064171164134735600124150ustar /** * * Written by Márton Münz and Philip C Biggin * Copyright (c) University of Oxford, United Kingdom * Visit http://sbcb.bioch.ox.ac.uk/jgromacs/ * * This source code file is part of JGromacs v1.0. * * JGromacs v1.0 is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * JGromacs v1.0. is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with JGromacs v1.0. If not, see . * */ package jgromacs.data; /** * Objects of this class represent an angle * */ public class Angle implements Cloneable{ private double valueInDegrees; // Constructors /** * Constructs a new Angle object * * */ public Angle(){ } /** * Constructs a new Angle object of given value in degrees * @param valueInDegrees value in degrees * */ public Angle(double valueInDegrees){ this.valueInDegrees = valueInDegrees; } // Getters and setters /** * Returns the value of angle in degrees * @return value in degrees * */ public double getInDegrees(){ return valueInDegrees; } /** * Returns the value of angle in radians * @return value in radians * */ public double getInRadians(){ return valueInDegrees*Math.PI/180; } /** * Sets the value of angle in degrees * @param valueInDegrees value in degrees * */ public void setInDegrees(double valueInDegrees){ this.valueInDegrees = valueInDegrees; } /** * Sets the value of angle in radians * @param valueInRadians value in radians * */ public void setInRadians(double valueInRadians){ valueInDegrees = valueInRadians*180/Math.PI; } // equals, clone and toString /** * Returns true if the two angles are identical * @param other the other angle * */ public boolean equals(Object other){ if (other == null) return false; if (other == this) return true; if (this.getClass() != other.getClass()) return false; Angle angle = (Angle)other; return (Math.abs(angle.valueInDegrees-valueInDegrees)<0.0000001); } /** * Returns hash code * */ public int hashCode() { return (int)valueInDegrees; } /** * Returns an identical Angle object * * @return clone of the angle */ public Object clone(){ try { Angle ret = (Angle)super.clone(); ret.valueInDegrees = valueInDegrees; return ret; } catch (CloneNotSupportedException e) { e.printStackTrace(); return null; } } /** * Returns the String representation of angle * * @return String representation */ public String toString(){ return String.valueOf(roundIt(getInDegrees(),2))+" degrees"; } private double roundIt(double d, int digit){ double N = Math.pow(10, digit); long L = (int)Math.round(d * N); double ret = L / N; return ret; } } source/jgromacs/data/Atom.java000644 000000232541164603042200122510ustar /** * * Written by Márton Münz and Philip C Biggin * Copyright (c) University of Oxford, United Kingdom * Visit http://sbcb.bioch.ox.ac.uk/jgromacs/ * * This source code file is part of JGromacs v1.0. * * JGromacs v1.0 is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * JGromacs v1.0. is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with JGromacs v1.0. If not, see . * */ package jgromacs.data; import jgromacs.db.AtomType; /** * Objects of this class represent a single atom * */ public class Atom implements Cloneable{ private int index = 0; private String name = "Noname"; private AtomType atomType = new AtomType(); private Point3D coordinates = new Point3D(); private double occupancy = 0; private double bvalue = 0; // Constructor /** * Constructs a new Atom object * * */ public Atom(){ super(); } // Getters and setters /** * Returns the type of atom * @return Type of the atom */ public AtomType getAtomType() { return atomType; } /** * Returns the index of atom * @return Index of the atom */ public int getIndex() { return index; } /** * Sets the index of atom * @param index index of the atom * */ public void setIndex(int index) { this.index = index; } /** * Returns the name of atom * @return Name of the atom */ public String getName() { return name; } /** * Sets the name of atom * @param name name of the atom * */ public void setName(String name) { this.name = name; } /** * Sets the type of atom * @param atomType type of the atom * */ public void setAtomType(AtomType atomType) { this.atomType = atomType; } /** * Returns the coordinates of atom * * @return Coordinates of atom */ public Point3D getCoordinates() { return coordinates; } /** * Sets the coordinates of atom * @param coordinates coordinates of the atom * */ public void setCoordinates(Point3D coordinates) { this.coordinates = coordinates; } /** * Returns the X coordinate of atom * * @return X coordinate of atom */ public double getXCoordinate() { return coordinates.getX(); } /** * Sets the X coordinate of atom * @param x X coordinate of the atom * */ public void setXCoordinate(double x) { coordinates.setX(x); } /** * Returns the Y coordinate of atom * * @return Y coordinate of atom */ public double getYCoordinate() { return coordinates.getY(); } /** * Sets the Y coordinate of atom * @param y Y coordinate of the atom * */ public void setYCoordinate(double y) { coordinates.setY(y); } /** * Returns the Z coordinate of atom * * @return Z coordinate of atom */ public double getZCoordinate() { return coordinates.getZ(); } /** * Sets the Z coordinate of atom * @param z Z coordinate of the atom * */ public void setZCoordinate(double z) { coordinates.setZ(z); } /** * Returns the occupancy of atom * * @return occupancy of atom */ public double getOccupancy() { return occupancy; } /** * Sets the occupancy of atom * @param occupancy occupancy of the atom * */ public void setOccupancy(double occupancy) { this.occupancy = occupancy; } /** * Returns the B-value of atom * * @return B-value of atom */ public double getBvalue() { return bvalue; } /** * Sets the B-value of atom * @param bvalue B-value of the atom * */ public void setBvalue(double bvalue) { this.bvalue = bvalue; } // is? /** * Returns true if the atom is a Hydrogen * * */ public boolean isHydrogenAtom(){ return atomType.getCode().equals("H"); } /** * Returns true if it is a heavy atom (not hydrogen) * * */ public boolean isHeavyAtom(){ return !isHydrogenAtom(); } /** * Returns true if it is an alpha carbon atom * * */ public boolean isAlphaCarbon(){ return atomType.getCode().equals("C")&&name.equals("CA"); } /** * Returns true if it is a C-terminal carbon atom * * */ public boolean isCTerminalCarbon(){ return atomType.getCode().equals("C")&&name.equals("C"); } /** * Returns true if it is a beta carbon atom * * */ public boolean isBetaCarbon(){ return atomType.getCode().equals("C")&&name.equals("CB"); } /** * Returns true if it is a gamma carbon atom * * */ public boolean isGammaCarbon(){ return atomType.getCode().equals("C")&&(name.equals("CG")||name.equals("CG1")||name.equals("CG2")); } /** * Returns true if it is a delta carbon atom * * */ public boolean isDeltaCarbon(){ return atomType.getCode().equals("C")&&(name.equals("CD")||name.equals("CD1")||name.equals("CD2")); } /** * Returns true if it is an epsilon carbon atom * * */ public boolean isEpsilonCarbon(){ return atomType.getCode().equals("C")&&(name.equals("CE")||name.equals("CE1")||name.equals("CE2")||name.equals("CE3")); } /** * Returns true if it is a zeta carbon atom * * */ public boolean isZetaCarbon(){ return atomType.getCode().equals("C")&&(name.equals("CZ")||name.equals("CZ1")||name.equals("CZ2")||name.equals("CZ3")); } /** * Returns true if it is a carbonyl oxygen atom * * */ public boolean isCarbonylOxygen(){ return atomType.getCode().equals("O")&&name.equals("O"); } /** * Returns true if it is a terminal oxygen atom * * */ public boolean isTerminalOxygen(){ return atomType.getCode().equals("O")&&name.equals("OXT"); } /** * Returns true if it is an N-terminal nitrogen atom * * */ public boolean isNTerminalNitrogen(){ return atomType.getCode().equals("N")&&name.equals("N"); } /** * Returns true if it is a backbone atom * * */ public boolean isBackboneAtom(){ return isCTerminalCarbon()||isAlphaCarbon()||isNTerminalNitrogen(); } /** * Returns true if it is a main chain atom * * */ public boolean isMainChainAtom(){ return isCTerminalCarbon()||isAlphaCarbon()||isNTerminalNitrogen()||isCarbonylOxygen()||isTerminalOxygen(); } /** * Returns true if it is a main chain hydrogen atom * * */ public boolean isMainChainHydrogenAtom(){ return atomType.getCode().equals("H")&&(name.equals("H")||name.equals("HA")||name.equals("HA1")||name.equals("HA2")||name.equals("HO")); } /** * Returns true if it is a main chain or hydrogen atom * * */ public boolean isMainChainPlusHAtom(){ return isCTerminalCarbon()||isAlphaCarbon()||isNTerminalNitrogen()||isCarbonylOxygen()||isTerminalOxygen()||isMainChainHydrogenAtom(); } /** * Returns true if it is a main chain or beta carbon atom * * */ public boolean isMainChainPlusCbAtom(){ return isCTerminalCarbon()||isAlphaCarbon()||isNTerminalNitrogen()||isCarbonylOxygen()||isTerminalOxygen()||isBetaCarbon(); } /** * Returns true if it is a side chain atom * * */ public boolean isSideChainAtom(){ return !isMainChainPlusHAtom(); } /** * Returns true if it is a side chain atom but not hydrogen * * */ public boolean isSideChainMinusHAtom(){ return isSideChainAtom()&&(!isHydrogenAtom()); } // Distance /** * Returns the Euclidean distance between this atom and another atom * @param other another atom * @return distance between atoms */ public double distance(Atom other){ return getCoordinates().distance(other.getCoordinates()); } // toString, clone and equals /** * Returns the String representation of atom * * @return String representation */ public String toString(){ return getName()+"\t"+getIndex()+"\t"+getAtomType()+"\t("+roundIt(getXCoordinate(),3)+"\t"+roundIt(getYCoordinate(),3)+"\t"+roundIt(getZCoordinate(),3)+")"; } /** * Returns an identical Atom object * * @return clone of the atom */ public Object clone(){ try { Atom ret = (Atom)super.clone(); ret.index = index; ret.name = name; ret.atomType = (AtomType)atomType.clone(); ret.coordinates = (Point3D)coordinates.clone(); ret.occupancy = occupancy; ret.bvalue = bvalue; return ret; } catch (CloneNotSupportedException e) { e.printStackTrace(); return null; } } /** * Returns true if the two atoms are identical * @param other the other atom * */ public boolean equals(Object other){ if (other == null) return false; if (other == this) return true; if (this.getClass() != other.getClass()) return false; Atom atom = (Atom)other; return atom.atomType.equals(atomType) &&atom.coordinates.equals(coordinates) &&(atom.index==index) &&(atom.name.equals(name)) &&(Math.abs(atom.occupancy-occupancy)<0.0000001) &&(Math.abs(atom.bvalue-bvalue)<0.0000001); } /** * Returns hash code * */ public int hashCode() { return index+name.length(); } private static double roundIt( double d, int digit){ double N = Math.pow(10, digit); long L = (int)Math.round(d * N); double ret = L / N; return ret; } } source/jgromacs/data/FrameIndexSet.java000644 000000155771164135511000140570ustar /** * * Written by Márton Münz and Philip C Biggin * Copyright (c) University of Oxford, United Kingdom * Visit http://sbcb.bioch.ox.ac.uk/jgromacs/ * * This source code file is part of JGromacs v1.0. * * JGromacs v1.0 is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * JGromacs v1.0. is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with JGromacs v1.0. If not, see . * */ package jgromacs.data; import java.util.ArrayList; import java.util.Iterator; import java.util.TreeSet; /** * Objects of this class represent a single frame index set * */ public class FrameIndexSet implements Cloneable { private String name = "Noname"; private TreeSet frame_indices = new TreeSet(); // Constructors /** * Constructs a new FrameIndexSet object * * */ public FrameIndexSet() { } /** * Constructs a new FrameIndexSet object of a given name * * */ public FrameIndexSet(String name) { super(); this.name = name; } /** * Constructs a new FrameIndexSet object and loads data from an ArrayList * * */ public FrameIndexSet(ArrayList list) { frame_indices = new TreeSet(list); } /** * Constructs a new FrameIndexSet object of a given name and loads data from an ArrayList * * */ public FrameIndexSet(ArrayList list, String name) { frame_indices = new TreeSet(list); this.name = name; } /** * Constructs a new FrameIndexSet object and loads data from a TreeSet * * */ public FrameIndexSet(TreeSet set) { frame_indices = new TreeSet(set); } /** * Constructs a new FrameIndexSet object of a given name and loads data from a TreeSet * * */ public FrameIndexSet(TreeSet set, String name) { frame_indices = new TreeSet(set); this.name = name; } /** * Constructs a new FrameIndexSet object identical to a given FrameIndexSet * * */ public FrameIndexSet(FrameIndexSet set){ this.name = set.getName(); frame_indices = new TreeSet(set.frame_indices); } // Getters and setters /** * Returns the name of frame index set * * @return Name of frame index set */ public String getName() { return name; } /** * Sets the name of frame index set * * */ public void setName(String name) { this.name = name; } /** * Returns frame index set as a TreeSet * * @return frame index set as a TreeSet */ public TreeSet getAsTreeSet(){ return frame_indices; } /** * Returns frame index set as an ArrayList * * @return frame index set as an ArrayList */ public ArrayList getAsArrayList(){ return new ArrayList(frame_indices); } /** * Returns the number of frames in this frame index set * * @return number of frames */ public int getNumberOfFrames(){ return frame_indices.size(); } /** * Returns true if the frame index set contains a given frame index * * */ public boolean isFrameIn(int frame_index){ return frame_indices.contains(frame_index); } // Modifications /** * Adds a new frame to the frame index set * * */ public void addFrame(int frame_index){ frame_indices.add(frame_index); } /** * Removes a frame from the frame index set * * */ public void removeFrame(int frame_index){ frame_indices.remove(frame_index); } // Set operations /** * Returns the intersection of this frame index set and another * * @return intersection of two frame index sets */ public FrameIndexSet intersect(FrameIndexSet other) { TreeSet ret = getAsTreeSet(); ret.retainAll(other.getAsTreeSet()); return new FrameIndexSet(ret,"Intersection("+getName()+","+other.getName()+")"); } /** * Returns the subtraction of another frame index set from this frame index set * * @return subtraction of two frame index sets */ public FrameIndexSet subtract(FrameIndexSet other) { TreeSet ret = new TreeSet(getAsTreeSet()); ret.removeAll(other.getAsTreeSet()); return new FrameIndexSet(ret,"Subtraction("+getName()+","+other.getName()+")"); } /** * Returns the union of this frame index set and another * * @return union of two frame index sets */ public FrameIndexSet union(FrameIndexSet other) { TreeSet ret = getAsTreeSet(); ret.addAll(other.getAsTreeSet()); return new FrameIndexSet(ret,"Union("+getName()+","+other.getName()+")"); } // toString, equals and clone /** * Returns the String representation of frame index set * * @return String representation */ public String toString(){ StringBuffer buf = new StringBuffer("[ "+getName()+" ]"); Iterator itr = this.getAsTreeSet().iterator(); int i=0; while (itr.hasNext()) { if (i%15==0) buf.append(" \n"); else buf.append(" "); String numstr = String.valueOf(itr.next()); if (numstr.length()==3) numstr = " "+numstr; if (numstr.length()==2) numstr = " "+numstr; if (numstr.length()==1) numstr = " "+numstr; buf.append(numstr); i++; } return buf.toString(); } /** * Returns summary information about the frame index set * * @return summary information */ public String toStringInfo(){ return "Name: "+name+" | ("+getNumberOfFrames()+" frame_indices)"; } /** * Returns true if this frame index set is identical to another * * */ public boolean equals(Object other){ if (other == null) return false; if (other == this) return true; if (this.getClass() != other.getClass()) return false; FrameIndexSet group = (FrameIndexSet)other; return group.frame_indices.equals(frame_indices)&&group.name.equals(name); } /** * Returns hash code * */ public int hashCode() { return frame_indices.size()+name.length(); } /** * Returns an identical FrameIndexSet object * * @return clone of the frame index set */ public Object clone(){ try { FrameIndexSet ret = (FrameIndexSet)super.clone(); ret.name = name; ret.frame_indices = new TreeSet(); Iterator itr = frame_indices.iterator(); while(itr.hasNext()) ret.frame_indices.add(itr.next()); return ret; } catch (CloneNotSupportedException e) { e.printStackTrace(); return null; } } } source/jgromacs/data/IndexSet.java000644 000000147221164135572200131040ustar /** * * Written by Márton Münz and Philip C Biggin * Copyright (c) University of Oxford, United Kingdom * Visit http://sbcb.bioch.ox.ac.uk/jgromacs/ * * This source code file is part of JGromacs v1.0. * * JGromacs v1.0 is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * JGromacs v1.0. is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with JGromacs v1.0. If not, see . * */ package jgromacs.data; import java.util.ArrayList; import java.util.Iterator; import java.util.TreeSet; /** * Objects of this class represent a single index set * */ public class IndexSet implements Cloneable{ private String name = "Noname"; private TreeSet indices = new TreeSet(); // Constructors /** * Constructs a new IndexSet object * * */ public IndexSet() { } /** * Constructs a new IndexSet object of a given name * * */ public IndexSet(String name) { super(); this.name = name; } /** * Constructs a new IndexSet object and loads data from an ArrayList * * */ public IndexSet(ArrayList list) { indices = new TreeSet(list); } /** * Constructs a new IndexSet object of a given name and loads data from an ArrayList * * */ public IndexSet(ArrayList list, String name) { indices = new TreeSet(list); this.name = name; } /** * Constructs a new IndexSet object and loads data from a TreeSet * * */ public IndexSet(TreeSet set) { indices = new TreeSet(set); } /** * Constructs a new IndexSet object of a given name and loads data from a TreeSet * * */ public IndexSet(TreeSet set, String name) { indices = new TreeSet(set); this.name = name; } /** * Constructs a new IndexSet object identical to a given IndexSet * * */ public IndexSet(IndexSet set){ this.name = set.getName(); indices = new TreeSet(set.indices); } // Getters and setters /** * Returns the name of index set * * @return Name of index set */ public String getName() { return name; } /** * Sets the name of index set * * */ public void setName(String name) { this.name = name; } /** * Returns index set as a TreeSet * * @return index set as a TreeSet */ public TreeSet getAsTreeSet(){ return new TreeSet(indices); } /** * Returns index set as an ArrayList * * @return index set as an ArrayList */ public ArrayList getAsArrayList(){ return new ArrayList(indices); } /** * Returns the number of indices in this index set * * @return number of indices */ public int getNumberOfIndices(){ return indices.size(); } /** * Returns true if the index set contains a given index * * */ public boolean isIndexIn(int index){ return indices.contains(index); } // Modifications /** * Adds a new index to the index set * * */ public void addIndex(int index){ indices.add(index); } /** * Removes an index from the index set * * */ public void removeIndex(int index){ indices.remove(index); } // Set operations /** * Returns the intersection of this index set and another * * @return intersection of two index sets */ public IndexSet intersect(IndexSet other) { TreeSet ret = getAsTreeSet(); ret.retainAll(other.getAsTreeSet()); return new IndexSet(ret,"Intersection("+getName()+","+other.getName()+")"); } /** * Returns the subtraction of another index set from this index set * * @return subtraction of two index sets */ public IndexSet subtract(IndexSet other) { TreeSet ret = new TreeSet(getAsTreeSet()); ret.removeAll(other.getAsTreeSet()); return new IndexSet(ret,"Subtraction("+getName()+","+other.getName()+")"); } /** * Returns the union of this index set and another * * @return union of two index sets */ public IndexSet union(IndexSet other) { TreeSet ret = getAsTreeSet(); ret.addAll(other.getAsTreeSet()); return new IndexSet(ret,"Union("+getName()+","+other.getName()+")"); } // toString, equals and clone /** * Returns the String representation of index set * * @return String representation */ public String toString(){ StringBuffer buf = new StringBuffer("[ "+getName()+" ]"); Iterator itr = this.getAsTreeSet().iterator(); int i=0; while (itr.hasNext()) { if (i%15==0) buf.append(" \n"); else buf.append(" "); String numstr = String.valueOf(itr.next()); if (numstr.length()==3) numstr = " "+numstr; if (numstr.length()==2) numstr = " "+numstr; if (numstr.length()==1) numstr = " "+numstr; buf.append(numstr); i++; } return buf.toString(); } /** * Returns summary information about the index set * * @return summary information */ public String toStringInfo(){ return "Name: "+name+" | ("+getNumberOfIndices()+" indices)"; } /** * Returns true if this index sets is identical to another * * */ public boolean equals(Object other){ if (other == null) return false; if (other == this) return true; if (this.getClass() != other.getClass()) return false; IndexSet group = (IndexSet)other; return group.indices.equals(indices)&&group.name.equals(name); } /** * Returns hash code * */ public int hashCode() { return indices.size()+name.length(); } /** * Returns an identical IndexSet object * * @return clone of the index set */ public Object clone(){ try { IndexSet ret = (IndexSet)super.clone(); ret.name = name; ret.indices = new TreeSet(); Iterator itr = indices.iterator(); while(itr.hasNext()) ret.indices.add(itr.next()); return ret; } catch (CloneNotSupportedException e) { e.printStackTrace(); return null; } } } source/jgromacs/data/IndexSetList.java000644 000000136201164135623000137270ustar /** * * Written by Márton Münz and Philip C Biggin * Copyright (c) University of Oxford, United Kingdom * Visit http://sbcb.bioch.ox.ac.uk/jgromacs/ * * This source code file is part of JGromacs v1.0. * * JGromacs v1.0 is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * JGromacs v1.0. is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with JGromacs v1.0. If not, see . * */ package jgromacs.data; import java.util.ArrayList; /** * Objects of this class represent a list of index sets * */ public class IndexSetList implements Cloneable{ private ArrayList indexsets = new ArrayList(); // Constructor /** * Constructs a new IndexSetList object * * */ public IndexSetList(){ } // Getters /** * Returns index set list as an ArrayList object * @return index set list as an ArrayList */ public ArrayList getAsAnArrayList(){ return indexsets; } /** * Returns the number of index sets in the list * @return number of index sets */ public int getNumberOfIndexSets(){ return indexsets.size(); } /** * Returns the index set of given index * @param i index of index set * @return index set of given index */ public IndexSet getIndexSet(int i){ return (IndexSet)indexsets.get(i); } /** * Returns the index set of given name * @param name name of index set * @return index set of given name */ public IndexSet getIndexSet(String name){ ArrayList indexsets = getAsAnArrayList(); for (int i = 0; i < indexsets.size(); i++) { IndexSet set = (IndexSet)indexsets.get(i); if (set.getName().equals(name)) return set; } return null; } /** * Returns the number of atoms in the index set of given index * @param i index of index set * @return number of atoms */ public int getNumberOfAtomsInIndexSet(int i){ IndexSet set = getIndexSet(i); return set.getNumberOfIndices(); } /** * Returns the number of atoms in the index set of given name * @param name name of index set * @return number of atoms */ public int getNumberOfAtomsInIndexSet(String name){ IndexSet set = getIndexSet(name); return set.getNumberOfIndices(); } // Modifications /** * Adds a new index set to the list * @param set new index set */ public void addIndexSet(IndexSet set){ indexsets.add(set); } /** * Adds a new index set of given name to the list * @param set new index set * @param name name of index set */ public void addIndexSet(IndexSet set, String name){ set.setName(name); indexsets.add(set); } /** * Removes index set of given index from the list * @param i index of index set to be removed */ public void removeIndexSet(int i){ indexsets.remove(i); } /** * Removes the given index set from the list * @param set index set to be removed */ public void removeIndexSet(IndexSet set){ indexsets.remove(set); } /** * Replaces index set of given index with a new index set * @param i index of index set to be replaced * @param set new index set */ public void setIndexSet(int i, IndexSet set){ indexsets.set(i, set); } // Fusion of index sets /** * Returns the union of all index sets as a single index set * @return union of index sets * */ public IndexSet fuseIntoOneIndexSet(){ IndexSet ret = new IndexSet(); StringBuffer buf = new StringBuffer(); for (int i = 0; i < indexsets.size(); i++) { IndexSet set = (IndexSet)indexsets.get(i); if (i>0) buf.append(","); buf.append(set.getName()); ret = ret.union(set); } ret.setName("Fusion("+buf.toString()+")"); return ret; } // toString, equals, clone /** * Returns the String representation of index set list * * @return String representation */ public String toString(){ StringBuffer buf = new StringBuffer(); ArrayList indexsets = getAsAnArrayList(); for (int i = 0; i < indexsets.size(); i++) { IndexSet set = (IndexSet)indexsets.get(i); buf.append(set.toString()+"\n"); } return buf.toString(); } /** * Returns summary information about the index set list * * @return summary information */ public String toStringInfo(){ return "("+getNumberOfIndexSets()+" index sets)"; } /** * Returns an identical IndexSetList object * * @return clone of the index set list */ public Object clone(){ try { IndexSetList ret = (IndexSetList)super.clone(); ret.indexsets = new ArrayList(); for (int i = 0; i < indexsets.size(); i++) ret.addIndexSet(indexsets.get(i)); return ret; } catch (CloneNotSupportedException e) { e.printStackTrace(); return null; } } /** * Returns true if the two index set lists are identical * @param other the other index set list * */ public boolean equals(Object other){ if (other == null) return false; if (other == this) return true; if (this.getClass() != other.getClass()) return false; IndexSetList setlist = (IndexSetList)other; if (setlist.getNumberOfIndexSets()!=getNumberOfIndexSets()) return false; for (int i = 0; i < indexsets.size(); i++){ if (!getIndexSet(i).equals(setlist.getIndexSet(i))) return false; } return true; } /** * Returns hash code * */ public int hashCode() { return indexsets.size(); } } source/jgromacs/data/package-info.java000644 000000001751153530221400136700ustar /** * jgromacs.data is a collection of classes representing multiple levels of structural data */ package jgromacs.data;source/jgromacs/data/Point3D.java000644 000000133121164134462200126300ustar /** * * Written by Márton Münz and Philip C Biggin * Copyright (c) University of Oxford, United Kingdom * Visit http://sbcb.bioch.ox.ac.uk/jgromacs/ * * This source code file is part of JGromacs v1.0. * * JGromacs v1.0 is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * JGromacs v1.0. is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with JGromacs v1.0. If not, see . * */ package jgromacs.data; import jama.Matrix; /** * Objects of this class represent a single 3D point * */ public class Point3D implements Cloneable{ private double x = 0; private double y = 0; private double z = 0; // Constructors /** * Constructs a new Point3D object * * */ public Point3D() { } /** * Constructs a new Point3D object with the given coordinates * @param x X coordinate * @param y Y coordinate * @param z Z coordinate */ public Point3D(double x, double y, double z) { super(); this.x = x; this.y = y; this.z = z; } // Getters and setters /** * Returns the X coordinate of point * * @return X coordinate */ public double getX() { return x; } /** * Sets the X coordinate of point * @param x X coordinate * */ public void setX(double x) { this.x = x; } /** * Returns the Y coordinate of point * * @return Y coordinate */ public double getY() { return y; } /** * Sets the Y coordinate of point * @param y Y coordinate * */ public void setY(double y) { this.y = y; } /** * Returns the Z coordinate of point * * @return Z coordinate */ public double getZ() { return z; } /** * Sets the Z coordinate of point * @param z Z coordinate * */ public void setZ(double z) { this.z = z; } // Distance between between points /** * Returns the Euclidean distance between this point and another point * @param other another point * @return distance between points */ public double distance(Point3D other){ return Math.sqrt(Math.pow(x-other.x, 2)+Math.pow(y-other.y, 2)+Math.pow(z-other.z, 2)); } // Operations /** * Adds another vector to this vector * @param other another vector * @return result vector */ public Point3D plus(Point3D other){ return new Point3D(x+other.x,y+other.y,z+other.z); } /** * Subtracts another vector from this vector * @param other another vector * @return result vector */ public Point3D minus(Point3D other){ return new Point3D(x-other.x,y-other.y,z-other.z); } /** * Returns the inner product of this vector and another vector * @param other another vector * @return inner product */ public double innerProduct(Point3D other){ return x*other.x+y*other.y+z*other.z; } /** * Returns the cross product of this vector and another vector * @param other another vector * @return cross product */ public Point3D crossProduct(Point3D other){ Point3D ret = new Point3D(); ret.setX(y*other.z-z*other.y); ret.setY(z*other.x-x*other.z); ret.setZ(x*other.y-y*other.x); return ret; } /** * Returns this vector multiplied by a scalar * @param scalar scalar value * @return result vector */ public Point3D multiplyByScalar(double scalar){ return new Point3D(x*scalar,y*scalar,z*scalar); } /** * Returns the length of the vector * @return length of vector */ public double length(){ return Math.sqrt(innerProduct(this)); } /** * Returns the resulting vector of a matrix transformation * @param matrix 3x3 transformation matrix * @return transformed vector */ public Point3D transformByMatrix(Matrix matrix){ Point3D ret = new Point3D(); ret.setX(matrix.get(0, 0)*x+matrix.get(0, 1)*y+matrix.get(0, 2)*z); ret.setY(matrix.get(1, 0)*x+matrix.get(1, 1)*y+matrix.get(1, 2)*z); ret.setZ(matrix.get(2, 0)*x+matrix.get(2, 1)*y+matrix.get(2, 2)*z); return ret; } // toString, clone and equals /** * Returns the String representation of point * * @return String representation */ public String toString(){ return "("+roundIt(getX(),3)+","+roundIt(getY(),3)+","+roundIt(getZ(),3)+")"; } /** * Returns an identical Point3D object * * @return clone of the point */ public Object clone(){ try { Point3D ret = (Point3D)super.clone(); ret.x = x; ret.y = y; ret.z = z; return ret; } catch (CloneNotSupportedException e) { e.printStackTrace(); return null; } } /** * Returns true if the two 3D points are identical * @param other the other point * */ public boolean equals(Object other){ if (other == null) return false; if (other == this) return true; if (this.getClass() != other.getClass()) return false; Point3D p = (Point3D)other; if ((Math.abs(p.x-x)<0.0000001)&&(Math.abs(p.y-y)<0.0000001)&&(Math.abs(p.z-z)<0.0000001)) return true; else return false; } /** * Returns hash code * */ public int hashCode() { return (int)(x*10+y*10-z*10); } private double roundIt(double d, int digit){ double N = Math.pow(10, digit); long L = (int)Math.round(d * N); double ret = L / N; return ret; } } source/jgromacs/data/PointList.java000644 000000165401164135651600133100ustar /** * * Written by Márton Münz and Philip C Biggin * Copyright (c) University of Oxford, United Kingdom * Visit http://sbcb.bioch.ox.ac.uk/jgromacs/ * * This source code file is part of JGromacs v1.0. * * JGromacs v1.0 is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * JGromacs v1.0. is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with JGromacs v1.0. If not, see . * */ package jgromacs.data; import java.util.ArrayList; import jama.Matrix; /** * Objects of this class represent a list of 3D points * */ public class PointList implements Cloneable { private ArrayList points = new ArrayList(); // Constructor /** * Constructs a new PointList object * * */ public PointList() { } // Getters, setters and modifications /** * Returns points in an ArrayList * @return Points in an ArrayList */ public ArrayList getPointsAsArrayList() { return points; } /** * Loads points from an ArrayList * @param points ArrayList of points */ public void setPointFromArrayList(ArrayList points) { this.points = points; } /** * Adds a new point to the point list * @param point new point */ public void addPoint(Point3D point){ points.add(point); } /** * Returns the point of index i * @return Point of index i * @param i index */ public Point3D getPoint(int i){ return (Point3D)points.get(i); } /** * Replaces the point of index i with a given point * @param i index * @param point new point */ public void setPoint(int i, Point3D point){ points.set(i, point); } /** * Removes the point of index i from the point list * @param i index */ public void removePoint(int i){ points.remove(i); } /** * Removes the given point from the point list * @param point point to remove */ public void removePoint(Point3D point){ points.remove(point); } /** * Returns the number of points in the list * @return Number of points */ public int getNumberOfPoints(){ return points.size(); } /** * Returns a subset of points defined by an ArrayList of indices * @param indices ArrayList of indices * @return subset of points */ public PointList getSubList(ArrayList indices){ PointList ret = new PointList(); for (int i = 0; i < indices.size(); i++) ret.addPoint(getPoint(indices.get(i))); return ret; } /** * Returns point coordinates in a 3xN matrix * @return coordinate matrix */ public Matrix getAsMatrix(){ Matrix ret = new Matrix(3,getNumberOfPoints()); for (int i = 0; i < getNumberOfPoints(); i++) { ret.set(0, i, getPoint(i).getX()); ret.set(1, i, getPoint(i).getY()); ret.set(2, i, getPoint(i).getZ()); } return ret; } /** * Loads point coordinates from a 3xN matrix * @param M coordinate matrix */ public void loadFromMatrix(Matrix M){ points.clear(); for (int i = 0; i < M.getColumnDimension(); i++) addPoint(new Point3D(M.get(0, i),M.get(1, i),M.get(2, i))); } // Transformations /** * Centers the points (around the origin) * */ public void centerPoints(){ Point3D centroid = new Point3D(0,0,0); for (int i = 0; i < getNumberOfPoints(); i++){ centroid.setX(centroid.getX()+getPoint(i).getX()); centroid.setY(centroid.getY()+getPoint(i).getY()); centroid.setZ(centroid.getZ()+getPoint(i).getZ()); } centroid.setX(centroid.getX()/getNumberOfPoints()); centroid.setY(centroid.getY()/getNumberOfPoints()); centroid.setZ(centroid.getZ()/getNumberOfPoints()); for (int i = 0; i < getNumberOfPoints(); i++){ getPoint(i).setX(getPoint(i).getX()-centroid.getX()); getPoint(i).setY(getPoint(i).getY()-centroid.getY()); getPoint(i).setZ(getPoint(i).getZ()-centroid.getZ()); } } /** * Returns the centroid of points * @return centroid point */ public Point3D getCentroid(){ Point3D centroid = new Point3D(0,0,0); for (int i = 0; i < getNumberOfPoints(); i++){ centroid.setX(centroid.getX()+getPoint(i).getX()); centroid.setY(centroid.getY()+getPoint(i).getY()); centroid.setZ(centroid.getZ()+getPoint(i).getZ()); } centroid.setX(centroid.getX()/getNumberOfPoints()); centroid.setY(centroid.getY()/getNumberOfPoints()); centroid.setZ(centroid.getZ()/getNumberOfPoints()); return centroid; } /** * Rotates the points by a given 3x3 rotation matrix * @param rotationMatrix rotation matrix */ public void rotate(Matrix rotationMatrix){ Matrix vector = new Matrix(3,1,0); for (int i = 0; i < getNumberOfPoints(); i++) { vector.set(0, 0, getPoint(i).getX()); vector.set(1, 0, getPoint(i).getY()); vector.set(2, 0, getPoint(i).getZ()); Matrix result = rotationMatrix.times(vector); getPoint(i).setX(result.get(0, 0)); getPoint(i).setY(result.get(1, 0)); getPoint(i).setZ(result.get(2, 0)); } } /** * Translates the points by a given vector * @param vector translation vector */ public void translate(Point3D vector){ for (int i = 0; i < getNumberOfPoints(); i++) { getPoint(i).setX(getPoint(i).getX()+vector.getX()); getPoint(i).setY(getPoint(i).getY()+vector.getY()); getPoint(i).setZ(getPoint(i).getZ()+vector.getZ()); } } // toString, equals, clone /** * Returns the String representation of point list * * @return String representation */ public String toString(){ StringBuffer buf = new StringBuffer(); for (int i = 0; i < points.size(); i++) buf.append(((Point3D)points.get(i)).toString()+"\n"); return buf.toString(); } /** * Returns summary information about the point list * * @return summary information */ public String toStringInfo(){ String ret = "("+getNumberOfPoints()+" points)"; return ret; } /** * Returns an identical PointList object * * @return clone of the point list */ public Object clone(){ try { PointList ret = (PointList)super.clone(); ret.points = new ArrayList(); for (int i = 0; i < getNumberOfPoints(); i++) ret.addPoint((Point3D)getPoint(i).clone()); return ret; } catch (CloneNotSupportedException e) { e.printStackTrace(); return null; } } /** * Returns true if the two point lists are identical * @param other the other point list * */ public boolean equals(Object other){ if (other == null) return false; if (other == this) return true; if (this.getClass() != other.getClass()) return false; PointList pl = (PointList)other; if (getNumberOfPoints()!=pl.getNumberOfPoints()) return false; for (int i = 0; i < getNumberOfPoints(); i++) if (!getPoint(i).equals(pl.getPoint(i))) return false; return true; } /** * Returns hash code * */ public int hashCode() { return points.size(); } } source/jgromacs/data/Residue.java000644 000000424321164262433400127570ustar /** * * Written by Márton Münz and Philip C Biggin * Copyright (c) University of Oxford, United Kingdom * Visit http://sbcb.bioch.ox.ac.uk/jgromacs/ * * This source code file is part of JGromacs v1.0. * * JGromacs v1.0 is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * JGromacs v1.0. is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with JGromacs v1.0. If not, see . * */ package jgromacs.data; import java.util.ArrayList; import jgromacs.data.Atom; import jgromacs.db.ResidueType; /** * Objects of this class represent a single residue * */ public class Residue implements Cloneable{ private int index = 0; private String name = "Noname"; private String chainID = "A"; private ArrayList atoms = new ArrayList(); private ResidueType residueType = new ResidueType(); // Constructors /** * Constructs a new Residue object * * */ public Residue(){ } /** * Constructs a new Residue object of given name * * */ public Residue(String name) { super(); this.name = name; } /** * Constructs a new Residue object of given index, name and residue type * * */ public Residue(int index, String name, ResidueType residueType) { super(); this.index = index; this.name = name; this.residueType = residueType; } /** * Constructs a new Residue object of given index, name, chainID and residue type * * */ public Residue(int index, String name, String chainID, ResidueType residueType) { super(); this.index = index; this.name = name; this.chainID = chainID; this.residueType = residueType; } // Getters and setters /** * Returns the index of residue * @return index of the residue */ public int getIndex() { return index; } /** * Sets the index of residue * @param index index of the residue */ public void setIndex(int index) { this.index = index; } /** * Returns the name of residue * @return name of the residue */ public String getName() { return name; } /** * Sets the name of residue * @param name name of the residue */ public void setName(String name) { this.name = name; } /** * Returns the type of residue * @return residue type */ public ResidueType getResidueType() { return residueType; } /** * Sets the type of residue * @param residueType residue type */ public void setResidueType(ResidueType residueType) { this.residueType = residueType; } /** * Returns the chain ID of residue * @return chain ID of residue */ public String getChainID(){ return chainID; } /** * Sets the chain ID of residue * @param chainID chain ID */ public void setChainID(String chainID){ this.chainID = chainID; } /** * Returns the number of atoms in the residue * @return number of atoms * */ public int getNumberOfAtoms(){ return atoms.size(); } /** * Returns the list of atoms as an ArrayList object * @return list of atoms as an ArrayList * */ public ArrayList getAtomsAsArrayList(){ return atoms; } /** * Returns atom #i of the residue * @return atom #i * */ public Atom getAtom(int i){ return atoms.get(i); } /** * Returns the atom of given index * @param index index of atom * @return atom of given index */ public Atom getAtomByIndex(int index){ for (int i = 0; i < atoms.size(); i++) { if (atoms.get(i).getIndex()==index) return atoms.get(i); } return null; } /** * Returns the atom of name * @param name name of atom * @return atom of given name */ public Atom getAtomByName(String name){ for (int i = 0; i < atoms.size(); i++) { if (atoms.get(i).getName().equals(name)) return atoms.get(i); } return null; } /** * Returns the 1 letter code of residue type * @return 1 letter code * */ public String get1LetterCode(){ return residueType.get1LetterCode(); } /** * Returns the 3 letter code of residue type * @return 3 letter code * */ public String get3LetterCode(){ return residueType.get3LetterCode(); } /** * Returns residue index and the 3 letter code of residue type * @return combined code * */ public String getCombinedCode(){ return getIndex()+residueType.get3LetterCode(); } // Modifications /** * Adds a new atom to the residue * @param atom new atom */ public void addAtom(Atom atom){ atoms.add(atom); } /** * Replaces atom #i of the residue with the given atom * @param atom new atom * */ public void setAtom(int i, Atom atom){ atoms.set(i, atom); } /** * Removes atom #i from the residue * */ public void removeAtom(int i){ atoms.remove(i); } /** * Removes the given atom from the residue * @param atom the atom to be removed */ public void removeAtom(Atom atom){ atoms.remove(atom); } /** * Removes atom of given index from the residue * @param index index of atom to be removed * */ public void removeAtomByIndex(int index){ for (int i = 0; i < atoms.size(); i++) { Atom atom = atoms.get(i); if (atom.getIndex()==index) removeAtom(atom); } } // Getting important atoms /** * Returns the N-terminal nitrogen atom of amino acid * @return N-terminal nitrogen atom * */ public Atom getNTerminalNitrogen(){ Atom ret; for (int i = 0; i < getNumberOfAtoms(); i++) { ret = getAtom(i); if (ret.isNTerminalNitrogen()) return ret; } return null; } /** * Returns the alpha carbon atom if any (otherwise returns null) * @return alpha carbon atom * */ public Atom getAlphaCarbon(){ Atom ret; for (int i = 0; i < getNumberOfAtoms(); i++) { ret = getAtom(i); if (ret.isAlphaCarbon()) return ret; } return null; } /** * Returns the beta carbon atom if any (otherwise returns null) * @return beta carbon atom * */ public Atom getBetaCarbon(){ Atom ret; for (int i = 0; i < getNumberOfAtoms(); i++) { ret = getAtom(i); if (ret.isBetaCarbon()) return ret; } return null; } /** * Returns the gamma carbon atom if any (otherwise returns null) * @return gamma carbon atom * */ public Atom getGammaCarbon(){ Atom ret; for (int i = 0; i < getNumberOfAtoms(); i++) { ret = getAtom(i); if (ret.isGammaCarbon()) return ret; } return null; } /** * Returns the delta carbon atom if any (otherwise returns null) * @return delta carbon atom * */ public Atom getDeltaCarbon(){ Atom ret; for (int i = 0; i < getNumberOfAtoms(); i++) { ret = getAtom(i); if (ret.isDeltaCarbon()) return ret; } return null; } /** * Returns the epsilon carbon atom if any (otherwise returns null) * @return epsilon carbon atom * */ public Atom getEpsilonCarbon(){ Atom ret; for (int i = 0; i < getNumberOfAtoms(); i++) { ret = getAtom(i); if (ret.isEpsilonCarbon()) return ret; } return null; } /** * Returns the zeta carbon atom if any (otherwise returns null) * @return zeta carbon atom * */ public Atom getZetaCarbon(){ Atom ret; for (int i = 0; i < getNumberOfAtoms(); i++) { ret = getAtom(i); if (ret.isZetaCarbon()) return ret; } return null; } /** * Returns the C-terminal carbon atom of amino acid * @return C-terminal carbon atom * */ public Atom getCTerminalCarbon(){ Atom ret; for (int i = 0; i < getNumberOfAtoms(); i++) { ret = getAtom(i); if (ret.isCTerminalCarbon()) return ret; } return null; } /** * Returns the carbonyl oxygen atom of amino acid * @return carbonyl oxygen atom * */ public Atom getCarbonylOxygen(){ Atom ret; for (int i = 0; i < getNumberOfAtoms(); i++) { ret = getAtom(i); if (ret.isCarbonylOxygen()) return ret; } return null; } // Getting important index sets /** * Returns the index set of all atoms * @return index set of all atoms * */ public IndexSet getAtomIndices(){ IndexSet ret = new IndexSet(); ret.setName("AllAtoms"); for (int i = 0; i < atoms.size(); i++) ret.addIndex(atoms.get(i).getIndex()); return ret; } /** * Returns the index set of hydrogen atoms * @return index set of hydrogen atoms * */ public IndexSet getHydrogenAtomIndices(){ IndexSet ret = new IndexSet(); ret.setName("HydrogenAtoms"); for (int i = 0; i < atoms.size(); i++) { Atom atom = atoms.get(i); if (atom.isHydrogenAtom()) ret.addIndex(atom.getIndex()); } return ret; } /** * Returns the index set of heavy atoms * @return index set of heavy atoms * */ public IndexSet getHeavyAtomIndices(){ IndexSet ret = new IndexSet(); ret.setName("HeavyAtoms"); for (int i = 0; i < atoms.size(); i++) { Atom atom = atoms.get(i); if (atom.isHeavyAtom()) ret.addIndex(atom.getIndex()); } return ret; } /** * Returns the index set of backbone atoms * @return index set of backbone atoms * */ public IndexSet getBackBoneAtomIndices(){ IndexSet ret = new IndexSet(); ret.setName("BackboneAtoms"); for (int i = 0; i < atoms.size(); i++) { Atom atom = atoms.get(i); if (atom.isBackboneAtom()) ret.addIndex(atom.getIndex()); } return ret; } /** * Returns the index set of main chain atoms * @return index set of main chain atoms * */ public IndexSet getMainChainAtomIndices(){ IndexSet ret = new IndexSet(); ret.setName("MainChainAtoms"); for (int i = 0; i < atoms.size(); i++) { Atom atom = atoms.get(i); if (atom.isMainChainAtom()) ret.addIndex(atom.getIndex()); } return ret; } /** * Returns the index set of main chain atoms and beta carbon atom * @return index set of main chain atoms and beta carbon atom * */ public IndexSet getMainChainPlusCbAtomIndices(){ IndexSet ret = new IndexSet(); ret.setName("MainChainPlusCbAtoms"); for (int i = 0; i < atoms.size(); i++) { Atom atom = atoms.get(i); if (atom.isMainChainPlusCbAtom()) ret.addIndex(atom.getIndex()); } return ret; } /** * Returns the index set of main chain atoms and hydrogen atoms * @return index set of main chain atoms and hydrogen atoms * */ public IndexSet getMainChainPlusHAtomIndices(){ IndexSet ret = new IndexSet(); ret.setName("MainChainPlusHAtoms"); for (int i = 0; i < atoms.size(); i++) { Atom atom = atoms.get(i); if (atom.isMainChainPlusHAtom()) ret.addIndex(atom.getIndex()); } return ret; } /** * Returns the index set of side chain atoms * @return index set of side chain atoms * */ public IndexSet getSideChainAtomIndices(){ IndexSet ret = new IndexSet(); ret.setName("SideChainAtoms"); for (int i = 0; i < atoms.size(); i++) { Atom atom = atoms.get(i); if (atom.isSideChainAtom()) ret.addIndex(atom.getIndex()); } return ret; } /** * Returns the index set of side chain atoms except of hydrogen atoms * @return index set of side chain atoms except of hydrogens * */ public IndexSet getSideChainMinusHAtomIndices(){ IndexSet ret = new IndexSet(); ret.setName("SideChainMinusH"); for (int i = 0; i < atoms.size(); i++) { Atom atom = atoms.get(i); if (atom.isSideChainMinusHAtom()) ret.addIndex(atom.getIndex()); } return ret; } // Coorddinates /** * Sets the coordinates of atom #i * @param coordinates new atomic coordinates */ public void setAtomCoordinates(int i, Point3D coordinates){ getAtom(i).setCoordinates(coordinates); } /** * Sets the coordinates of atom of given index * @param coordinates new atomic coordinates */ public void setAtomOfIndexCoordinates(int index, Point3D coordinates){ getAtomByIndex(index).setCoordinates(coordinates); } /** * Sets the coordinates of all atoms * @param pointlist list of new atomic coordinates */ public void setAllAtomCoordinates(PointList pointlist){ int numofatoms = getNumberOfAtoms(); for (int i = 0; i < numofatoms; i++) { setAtomCoordinates(i, pointlist.getPoint(i)); } } /** * Returns the coordinates of all atoms * @return list of atomic coordinates */ public PointList getAllAtomCoordinates(){ PointList ret = new PointList(); for (int k = 0; k < getNumberOfAtoms(); k++) ret.addPoint(getAtom(k).getCoordinates()); return ret; } /** * Returns the position of alpha-carbon atom * @return position of alpha-carbon atom */ public Point3D getAlphaCarbonCoordinates(){ return getAlphaCarbon().getCoordinates(); } // Distances /** * Returns the Euclidean distance of alpha-carbon atoms of this amino acid an another * @param other other amino acid * @return Euclidean distance of alpha-carbon atoms */ public double distanceAlphaCarbons(Residue other){ Atom atom1 = getAlphaCarbon(); Atom atom2 = other.getAlphaCarbon(); return atom1.distance(atom2); } /** * Returns the Euclidean distance of the closest atoms of this amino acid and another * @param other other amino acid * @return Euclidean distance of closest atoms */ public double distanceClosest(Residue other){ double ret = 999999; for (int i = 0; i < getNumberOfAtoms(); i++) { Atom atom1 = getAtom(i); for (int j = 0; j < other.getNumberOfAtoms(); j++) { Atom atom2 = other.getAtom(j); double dist = atom1.distance(atom2); if (dist(); for (int i = 0; i < atoms.size(); i++) ret.atoms.add((Atom)atoms.get(i).clone()); return ret; } catch (CloneNotSupportedException e) { e.printStackTrace(); return null; } } /** * Returns the String representation of residue * * @return String representation */ public String toString(){ StringBuffer buf = new StringBuffer(name+"\t"+getCombinedCode()+"\t"+chainID+"\n"); for (int i = 0; i < getNumberOfAtoms(); i++) buf.append(getAtom(i).toString()+"\n"); return buf.toString(); } /** * Returns summary information about the residue * * @return summary information */ public String toStringInfo(){ String ret = "Name: "+name+" | Code: "+getCombinedCode()+" | Chain ID: "+chainID+" | ("+getNumberOfAtoms()+" atoms)\n";; return ret; } /** * Returns true if the two residues are identical * @param other the other residue * */ public boolean equals(Object other){ if (other == null) return false; if (other == this) return true; if (this.getClass() != other.getClass()) return false; Residue res = (Residue)other; if (!res.chainID.equals(chainID)) return false; if (!res.name.equals(name)) return false; if (res.index!=index) return false; if (!res.residueType.equals(residueType)) return false; if (res.getNumberOfAtoms()!=getNumberOfAtoms()) return false; for (int i = 0; i < getNumberOfAtoms(); i++) { if (!res.getAtom(i).equals(getAtom(i))) return false; } return true; } /** * Returns hash code * */ public int hashCode() { return index+name.length()+atoms.size(); } } source/jgromacs/data/Sequence.java000644 000000445031164305331600131250ustar /** * * Written by Márton Münz and Philip C Biggin * Copyright (c) University of Oxford, United Kingdom * Visit http://sbcb.bioch.ox.ac.uk/jgromacs/ * * This source code file is part of JGromacs v1.0. * * JGromacs v1.0 is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * JGromacs v1.0. is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with JGromacs v1.0. If not, see . * */ package jgromacs.data; import java.util.ArrayList; import jgromacs.db.ResidueType; /** * Objects of this class represent a single amino acid sequence * */ public class Sequence implements Cloneable { private String name = "Noname"; private ArrayList positions = new ArrayList(); // Constructors /** * Constructs a new Sequence object * * */ public Sequence(){ } /** * Constructs a new Sequence object of given name * * */ public Sequence(String name){ this.name = name; } // Getters and setters /** * Returns the name of sequence * @return name of sequence */ public String getName() { return name; } /** * Sets the name of sequence * @param name name of sequence */ public void setName(String name) { this.name = name; } /** * Returns sequence as an ArrayList object * @return sequence as an ArrayList */ public ArrayList getAsArrayList(){ return positions; } /** * Returns the length of sequence (gaps excluded) * @return length of sequence */ public int getSequenceLength(){ int ret = 0; for (int i = 0; i < positions.size(); i++) if (!isPositionAGap(i)) ret++; return ret; } /** * Returns the length of sequence (gaps included) * @return length of sequence */ public int getSequenceLengthWithGaps(){ return positions.size(); } /** * Returns sequence position #i * @return sequence position #i */ public SequencePosition getPosition(int i){ return positions.get(i); } /** * Returns sequence position of given index * @param index index of position * @return sequence position of given index */ public SequencePosition getPositionByIndex(int index){ for (int i = 0; i < getSequenceLengthWithGaps(); i++) if (getIndexOfPosition(i)==index) return getPosition(i); return null; } /** * Returns the index of sequence position #i * @return index of sequence position */ public int getIndexOfPosition(int i){ return positions.get(i).getIndex(); } /** * Returns the residue type of sequence position #i * @return residue type of sequence position */ public ResidueType getResidueTypeOfPosition(int i){ return positions.get(i).getResidueType(); } /** * Returns the annotation of sequence position #i * @return annotation of sequence position */ public String getAnnotationOfPosition(int i){ return positions.get(i).getAnnotation(); } /** * Returns the residue type of sequence position of given index * @param index index of position * @return residue type of sequence position */ public ResidueType getResidueTypeOfPositionOfIndex(int index){ return getPositionByIndex(index).getResidueType(); } /** * Returns the annotation of sequence position of given index * @param index index of position * @return annotation of sequence position */ public String getAnnotationOfPositionOfIndex(int index){ return getPositionByIndex(index).getAnnotation(); } // Modifications /** * Adds a new position to the sequence * @param pos new sequence position * */ public void addPosition(SequencePosition pos){ positions.add((SequencePosition)pos.clone()); } /** * Adds a new position of given residue type and annotation to the sequence * @param type residue type of new position * @param annotation annotation of new position */ public void addPosition(ResidueType type, String annotation){ SequencePosition pos = new SequencePosition(type, annotation); pos.setIndex(calculateIndexUponAddition()); positions.add(pos); } /** * Adds a new position of given index and residue type to the sequence * @param index index of new position * @param type residue type of new position */ public void addPosition(int index, ResidueType type){ SequencePosition pos = new SequencePosition(index,type); positions.add(pos); } /** * Adds a new position of given index, residue type and annotation to the sequence * @param index index of new position * @param type residue type of new position * @param annotation annotation of new position */ public void addPosition(int index, ResidueType type, String annotation){ SequencePosition pos = new SequencePosition(index,type,annotation); positions.add(pos); } /** * Adds a series of new positions to the sequence taken from a String object * @param str String object encoding a series of sequence positions */ public void addPositionsFromString(String str){ str = str.trim(); for (int k = 0; k < str.length(); k++) { String code = str.substring(k,k+1); if (code.equals("-")) addGap(); else addPosition(new ResidueType(code),""); } } /** * Adds a new gap to the sequence * */ public void addGap(){ SequencePosition pos = new SequencePosition(-999,new ResidueType()); positions.add(pos); } /** * Inserts a new gap to position #i * */ public void insertGap(int i){ SequencePosition pos = new SequencePosition(-999,new ResidueType()); positions.add(i, pos); } /** * Replaces position #i with the given sequence position * @param pos new sequence position * */ public void setPosition(int i, SequencePosition pos){ positions.set(i,pos); } /** * Replaces position #i with the a sequence position of given residue type and annotation * @param type residue type of new sequence position * @param annotation annotation of new sequence position * */ public void setPosition(int i, ResidueType type, String annotation){ int index = calculateIndexUponSetting(i); SequencePosition pos = new SequencePosition(index,type,annotation); positions.set(i,pos); } /** * Replaces position #i with the a sequence position of given index and residue type * @param index index of new sequence position * @param type residue type of new sequence position * */ public void setPosition(int i, int index, ResidueType type){ SequencePosition pos = new SequencePosition(index,type); positions.set(i,pos); } /** * Replaces position #i with the a sequence position of given index, residue type and annotation * @param index index of new sequence position * @param type residue type of new sequence position * @param annotation annotation of new sequence position * */ public void setPosition(int i, int index, ResidueType type, String annotation){ SequencePosition pos = new SequencePosition(index,type,annotation); positions.set(i,pos); } /** * Replaces the position of given index with the a sequence position of given residue type and annotation * @param index index of sequence position * @param type residue type of new sequence position * @param annotation annotation of new sequence position * */ public void setPositionByIndex(int index, ResidueType type, String annotation){ for (int i = 0; i < getSequenceLengthWithGaps(); i++){ if (getIndexOfPosition(i)==index) setPosition(i, new SequencePosition(index,type,annotation)); } } /** * Replaces the position of given index with the a sequence position of given residue type * @param index index of sequence position * @param type residue type of new sequence position * */ public void setPositionByIndex(int index, ResidueType type){ for (int i = 0; i < getSequenceLengthWithGaps(); i++){ if (getIndexOfPosition(i)==index) setPosition(i, new SequencePosition(index,type)); } } /** * Removes sequence position #i * */ public void removePosition(int i){ positions.remove(i); } /** * Removes the given sequence position * @param pos sequence position to be removed */ public void removePosition(SequencePosition pos){ positions.remove(pos); } /** * Removes the sequence position of given index * @param index index of sequence position to be removed */ public void removePositionByIndex(int index){ SequencePosition pos = getPositionByIndex(index); removePosition(pos); } /** * Removes all gaps from the sequence * */ public void removeGaps(){ for (int i = 0; i < getSequenceLengthWithGaps(); i++) { if (isPositionAGap(i)) { removePosition(i); i--; } } } /** * Reindexes all positions in the sequence starting from a given index * @param startindex index of position #0 */ public void reIndexPositions(int startindex){ for (int i = 0; i < getSequenceLengthWithGaps(); i++) { if (!isPositionAGap(i)){ getPosition(i).setIndex(startindex); startindex++; } } } /** * Reindexes all positions in the sequence starting from 1 * */ public void reIndexPositions(){ reIndexPositions(1); } /** * Inserts the given sequence position to position #i * Note that you may have to re-index sequence positions after using this method * @param pos new sequence position * */ public void insertPosition(int i, SequencePosition pos){ positions.add(i,(SequencePosition)pos.clone()); } /** * Inserts sequence position of given residue type and annotation to position #i * Note that you may have to re-index sequence positions after using this method * @param type residue type of new sequence position * @param annotation annotation of new sequence position * */ public void insertPosition(int i, ResidueType type, String annotation){ int index = calculateIndexUponInsertion(i); SequencePosition pos = new SequencePosition(index,type,annotation); positions.add(i,pos); } /** * Inserts sequence position of given index and residue type to position #i * Note that you may have to re-index sequence positions after using this method * @param index index of new sequence position * @param type residue type of new sequence position * */ public void insertPosition(int i, int index, ResidueType type){ SequencePosition pos = new SequencePosition(index,type); positions.add(i,pos); } /** * Inserts sequence position of given index, residue type and annotation to position #i * Note that you may have to re-index sequence positions after using this method * @param index index of new sequence position * @param type residue type of new sequence position * @param annotation annotation of new sequence position * */ public void insertPosition(int i, int index, ResidueType type, String annotation){ SequencePosition pos = new SequencePosition(index,type,annotation); positions.add(i,pos); } // isGap? /** * Returns true if sequence position #i is a gap * */ public boolean isPositionAGap(int i){ if (i>getSequenceLengthWithGaps()) return true; if (getIndexOfPosition(i)==-999) return true; return false; } // Miscellaneous /** * Returns subsequence beginning at sequence position #begin and ending at sequence position #end * @param begin start position of subsequence * @param end end position of subsequence * @return subsequence */ public Sequence getSubSequence(int begin, int end){ Sequence ret = new Sequence("Subsequence["+begin+","+end+"](from:"+getName()+")"); for (int i = begin; i < end+1; i++) ret.addPosition(getPosition(i)); return ret; } /** * Returns subsequence beginning at sequence position #begin * @param begin start position of subsequence * @return subsequence */ public Sequence getSubSequenceFrom(int begin){ Sequence ret = getSubSequence(begin,getSequenceLengthWithGaps()-1); ret.setName("Subsequence["+begin+"-...](from:"+getName()+")"); return ret; } /** * Returns subsequence ending at sequence position #end * @param end end position of subsequence * @return subsequence */ public Sequence getSubSequenceTo(int end){ Sequence ret = getSubSequence(0,end); ret.setName("Subsequence[...-"+end+"](from:"+getName()+")"); return ret; } /** * Returns the reverse sequence * @return reverse sequence */ public Sequence getReverse(){ Sequence ret = new Sequence("Reverse("+getName()+")"); for (int i = getSequenceLengthWithGaps()-1; i >= 0; i--) ret.addPosition(getPosition(i)); return ret; } /** * Returns the given sequence concatenated to this sequence * @param other second sequence * @return concatenated sequence */ public Sequence concat(Sequence other){ Sequence ret = (Sequence)clone(); for (int i = 0; i < other.getSequenceLengthWithGaps(); i++) ret.addPosition(other.getPosition(i)); ret.setName("Concat("+ret.getName()+","+other.getName()+")"); return ret; } /** * Returns true if the given subsequence is contained in this sequence * @param subsequence subsequence to search for * */ public boolean containsSubSequence(Sequence subsequence){ for (int cursor = 0; cursor < getSequenceLengthWithGaps()-subsequence.getSequenceLengthWithGaps()+1; cursor++) { boolean ok = true; for (int i = 0; i < subsequence.getSequenceLengthWithGaps(); i++) { if (!subsequence.getPosition(i).getResidueType().equals(getPosition(cursor+i).getResidueType())) { ok = false; break; } } if (ok) return true; } return false; } // toString, equals, clone /** * Returns the String representation of sequence * * @return String representation */ public String toString(){ return toString1Letter(); } /** * Returns a String representation in which each residue is represented by its 1 letter code * * @return String representation */ public String toString1Letter(){ return toString1Letter(60); } /** * Returns a String representation in which each residue is represented by its 3 letter code * * @return String representation */ public String toString3Letter(){ return toString3Letter(15); } /** * Returns a String representation in which each residue is represented by its 1 letter code * and the string is split to lines of the given length * @param lengthOfLine max length of a line in the string * @return String representation */ public String toString1Letter(int lengthOfLine){ StringBuffer buf = new StringBuffer(">"+getName()+"\n"); for (int i = 0; i < positions.size(); i++) { if (i>0) { if (i%lengthOfLine==0) buf.append("\n"); } if (isPositionAGap(i)) buf.append("-"); else buf.append(getResidueTypeOfPosition(i).get1LetterCode()); } return buf.toString(); } /** * Returns a String representation in which each residue is represented by its 3 letter code * and the string is split to lines of the given length * @param lengthOfLine max length of a line (number of residues) in the string * @return String representation */ public String toString3Letter(int lengthOfLine){ StringBuffer buf = new StringBuffer(">"+getName()+"\n"); for (int i = 0; i < positions.size(); i++) { if (i>0) { if (i%lengthOfLine==0) buf.append("\n"); else buf.append(" "); } if (isPositionAGap(i)) buf.append("---"); else buf.append(getResidueTypeOfPosition(i).get3LetterCode()); } return buf.toString(); } /** * Returns summary information about the sequence * * @return summary information */ public String toStringInfo(){ return "Name: "+name+" | ("+getSequenceLengthWithGaps()+" sequence poisitions)"; } /** * Returns an identical Sequence object * * @return clone of the sequence */ public Object clone(){ Sequence ret; try { ret = (Sequence)super.clone(); ret.name = name; ret.positions = new ArrayList(); for (int i = 0; i < positions.size(); i++){ SequencePosition sp = (SequencePosition)positions.get(i).clone(); ret.positions.add(sp); } return ret; } catch (CloneNotSupportedException e) { e.printStackTrace(); return null; } } /** * Returns true if the two sequences are identical * @param other the other sequence * */ public boolean equals(Object other){ if (other == null) return false; if (other == this) return true; if (this.getClass() != other.getClass()) return false; Sequence seq = (Sequence)other; if (!name.equals(seq.name)) return false; if (getSequenceLengthWithGaps()!=seq.getSequenceLengthWithGaps()) return false; for (int i = 0; i < getSequenceLengthWithGaps(); i++) { if (!getPosition(i).equals(seq.getPosition(i))) return false; } return true; } /** * Returns hash code * */ public int hashCode() { return positions.size()+name.length(); } private int calculateIndexUponAddition(){ for (int i = positions.size()-1; i >= 0; i--) if (!isPositionAGap(i)) return positions.get(i).getIndex()+1; return 1; } private int calculateIndexUponSetting(int k){ for (int i = k-1; i >= 0; i--) if (!isPositionAGap(i)) return positions.get(i).getIndex()+1; for (int i = k+1; i < positions.size(); i++) if (!isPositionAGap(i)) { int I = positions.get(i).getIndex(); if (I>1) return I-1; else return 0; } return 1; } private int calculateIndexUponInsertion(int k){ for (int i = k-1; i >= 0; i--) if (!isPositionAGap(i)) return positions.get(i).getIndex()+1; for (int i = k; i < positions.size(); i++) if (!isPositionAGap(i)) { int I = positions.get(i).getIndex(); if (I>1) return I-1; else return 0; } return 1; } } source/jgromacs/data/SequencePosition.java000644 000000115711164135745000146550ustar /** * * Written by Márton Münz and Philip C Biggin * Copyright (c) University of Oxford, United Kingdom * Visit http://sbcb.bioch.ox.ac.uk/jgromacs/ * * This source code file is part of JGromacs v1.0. * * JGromacs v1.0 is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * JGromacs v1.0. is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with JGromacs v1.0. If not, see . * */ package jgromacs.data; import jgromacs.db.ResidueType; /** * Objects of this class represent a single sequence position * */ public class SequencePosition implements Cloneable { private ResidueType residueType = new ResidueType(); private int index = 0; private String annotation = ""; // Constructors /** * Constructs a new SequencePosition object * * */ public SequencePosition() { } /** * Constructs a new SequencePosition object of given index and residue type * @param index index * @param residueType residue type * */ public SequencePosition(int index, ResidueType residueType){ setIndex(index); this.residueType = residueType; } /** * Constructs a new SequencePosition object of given index and annotation * @param index index * @param annotation annotation * */ public SequencePosition(int index, String annotation) { super(); this.index = index; this.annotation = annotation; } /** * Constructs a new SequencePosition object of residue type and annotation * @param residueType residue type * @param annotation annotation * */ public SequencePosition(ResidueType residueType, String annotation){ this.residueType = residueType; setAnnotation(annotation); } /** * Constructs a new SequencePosition object of given index, residue type and annotation * @param index index * @param residueType residue type * @param annotation annotation * */ public SequencePosition(int index, ResidueType residueType, String annotation){ setIndex(index); this.residueType = residueType; setAnnotation(annotation); } // Getters and setters /** * Returns the index of sequence position * * @return index of sequence position */ public int getIndex() { return index; } /** * Sets the index of sequence position * @param index index of sequence position * */ public void setIndex(int index) { this.index = index; } /** * Returns the annotation of sequence position * * @return annotation of sequence position */ public String getAnnotation(){ return annotation; } /** * Sets the annotation of sequence position * @param annotation annotation of sequence position * */ public void setAnnotation(String annotation){ this.annotation = annotation; } /** * Returns the residue type of sequence position * * @return residue type of sequence position */ public ResidueType getResidueType() { return residueType; } /** * Sets the residue type of sequence position * @param residueType residue type of sequence position * */ public void setResidueType(ResidueType residueType) { this.residueType = residueType; } // clone, equals, toString /** * Returns an identical SequencePosition object * * @return clone of the sequence position */ public Object clone(){ try { SequencePosition ret = (SequencePosition)super.clone(); ret.index = index; ret.annotation = annotation; ret.residueType = (ResidueType)residueType.clone(); return ret; } catch (CloneNotSupportedException e) { e.printStackTrace(); return null; } } /** * Returns true if the two sequence positions are identical * @param other the other sequence position * */ public boolean equals(Object other){ if (other == null) return false; if (other == this) return true; if (this.getClass() != other.getClass()) return false; SequencePosition sp = (SequencePosition)other; if (residueType.equals(sp.residueType)&&(index==sp.index)&&(annotation.equals(sp.annotation))) return true; else return false; } /** * Returns hash code * */ public int hashCode() { return index+annotation.length(); } /** * Returns the String representation of sequence position * * @return String representation */ public String toString(){ return index+residueType.get3LetterCode(); } } source/jgromacs/data/Structure.java000644 000000637721164603172400133700ustar /** * * Written by Márton Münz and Philip C Biggin * Copyright (c) University of Oxford, United Kingdom * Visit http://sbcb.bioch.ox.ac.uk/jgromacs/ * * This source code file is part of JGromacs v1.0. * * JGromacs v1.0 is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * JGromacs v1.0. is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with JGromacs v1.0. If not, see . * */ package jgromacs.data; import java.util.ArrayList; import java.util.TreeSet; /** * Objects of this class represent a single structure * */ public class Structure implements Cloneable { private String name = "Noname"; private ArrayList residues = new ArrayList(); // Constructors /** * Constructs a new Structure object * * */ public Structure(){ } /** * Constructs a new Structure object of given name * * */ public Structure(String name) { super(); this.name = name; } // Getters and setters /** * Returns the name of structure * @return name of structure * */ public String getName() { return name; } /** * Sets the name of structure * @param name of structure * */ public void setName(String name) { this.name = name; } /** * Returns residues as an ArrayList object * @return residues as an ArrayList * */ public ArrayList getResiduesAsArrayList(){ return residues; } /** * Returns the number of residues in the structure * @return number of residues * */ public int getNumberOfResidues() { return residues.size(); } /** * Returns the number of atoms in the structure * @return number of atoms * */ public int getNumberOfAtoms(){ int ret = 0; for (int i = 0; i < getNumberOfResidues(); i++) { ret+= getResidue(i).getNumberOfAtoms(); } return ret; } /** * Returns the number of chains in the structure * @return number of chains * */ public int getNumberOfChains(){ TreeSet ids = new TreeSet(); for (int i = 0; i < getNumberOfResidues(); i++) { String id = getResidue(i).getChainID(); ids.add(id); } return ids.size(); } /** * Returns the list of chain IDs in the structure * @return list of chain IDs * */ public ArrayList getChainIDs(){ TreeSet ids = new TreeSet(); for (int i = 0; i < getNumberOfResidues(); i++) { String id = getResidue(i).getChainID(); ids.add(id); } return new ArrayList(ids); } /** * Returns residue #i of the structure * @return residue #i * */ public Residue getResidue(int i){ return residues.get(i); } /** * Returns the residue of given index and given chain ID * @param index index of residue * @param chainID chain ID of residue * @return residue of given index and chain ID * */ public Residue getResidueByIndex(int index, String chainID) { for (int i = 0; i < residues.size(); i++) { Residue res = residues.get(i); if ((res.getIndex()==index)&&(res.getChainID().equals(chainID))) return res; } return null; } /** * Returns the residue of given index * @param index index of residue * @return residue of given index * */ public Residue getResidueByIndex(int index) { for (int i = 0; i < residues.size(); i++) { Residue res = residues.get(i); if (res.getIndex()==index) return res; } return null; } /** * Returns atom #i of the structure * @return atom #i * */ public Atom getAtom(int i){ int counter = 0; for (int j = 0; j < getNumberOfResidues(); j++) { int numOfAtoms = getResidue(j).getNumberOfAtoms(); for (int k = 0; k < numOfAtoms; k++) { if (counter==i) return getResidue(j).getAtom(k); counter++; } } return null; } /** * Returns the atom of given index * @param index index of atom * @return atom of given index * */ public Atom getAtomByIndex(int index) { for (int j = 0; j < getNumberOfResidues(); j++) { Residue res = getResidue(j); int numOfAtoms = res.getNumberOfAtoms(); for (int k = 0; k < numOfAtoms; k++) { if (res.getAtom(k).getIndex()==index) return res.getAtom(k); } } return null; } /** * Returns atom #i of the residue of given index and chain ID * @param residueindex index of residue * @param chainID chain ID of residue * @return atom #i in residue of given index and chain ID * */ public Atom getAtomInResidueOfIndex(int residueindex, String chainID, int i){ Residue aa = getResidueByIndex(residueindex, chainID); return aa.getAtom(i); } /** * Returns atom #i of the residue of given index * @param residueindex index of residue * @return atom #i in residue of given index * */ public Atom getAtomInResidueOfIndex(int residueindex, int i){ Residue aa = getResidueByIndex(residueindex); return aa.getAtom(i); } // Modifications /** * Adds a new residue to the structure * @param residue new residue * */ public void addResidue(Residue residue) { residues.add(residue); } /** * Removes a residue from the structure * @param residue the residue to be removed * */ public void removeResidue(Residue residue) { residues.remove(residue); } /** * Removes residue #i from the structure * */ public void removeResidue(int i) { residues.remove(i); } /** * Replaces residue #i with a new residue * @param residue new residue * */ public void setResidue(int i, Residue residue){ residues.set(i, residue); } /** * Removes atom #i from the structure * */ public void removeAtom(int i){ int counter = 0; for (int k = 0; k < getNumberOfResidues(); k++) { Residue res = getResidue(k); for (int j = 0; j < res.getNumberOfAtoms(); j++) { if (counter==i) { res.removeAtom(j); counter++; break; } counter++; } if (res.getNumberOfAtoms()==0) removeResidue(k); } } /** * Removes the atom of given index from the structure * @param index index of atom */ public void removeAtomByIndex(int index){ for (int k = 0; k < getNumberOfResidues(); k++) { Residue res = getResidue(k); for (int j = 0; j < res.getNumberOfAtoms(); j++) { Atom atom = res.getAtom(j); if (atom.getIndex()==index) { res.removeAtom(j); j--; } } if (res.getNumberOfAtoms()==0){ removeResidue(k); k--; } } } /** * Removes the given atom from the structure * @param atom the atom to be removed */ public void removeAtom(Atom atom){ for (int k = 0; k < getNumberOfResidues(); k++) { Residue res = getResidue(k); for (int j = 0; j < res.getNumberOfAtoms(); j++) { Atom atomJ = res.getAtom(j); if (atomJ.equals(atom)) { res.removeAtom(j); j--; } } if (res.getNumberOfAtoms()==0){ removeResidue(k); k--; } } } /** * Adds the given atom to residue #i * @param atom new atom */ public void addAtomToResidue(int i, Atom atom){ getResidue(i).addAtom(atom); } /** * Adds the given atom to the residue of given index * @param index index of residue * @param atom new atom */ public void addAtomToResidueOfIndex(int index, Atom atom){ getResidueByIndex(index).addAtom(atom); } /** * Replaces atom #j of residue #i with a new atom * @param atom new atom * */ public void setAtomInResidue(int i, int j, Atom atom){ getResidue(i).setAtom(j, atom); } /** * Replaces atom #i of the residue of given index with a new atom * @param index index of residue * @param atom new atom * */ public void setAtomInResidueOfIndex(int index, int i, Atom atom){ getResidueByIndex(index).setAtom(i, atom); } // Getting important index sets /** * Returns the index set of all atoms in the system * @return index set of all atoms */ public IndexSet getSystemIndexSet(){ IndexSet ret = new IndexSet(); for (int i = 0; i < getNumberOfResidues(); i++) { Residue aa = getResidue(i); ret = ret.union(aa.getAtomIndices()); } ret.setName("System"); return ret; } /** * Returns the index set of protein atoms * @return index set of protein atoms */ public IndexSet getProteinIndexSet(){ IndexSet ret = new IndexSet(); for (int i = 0; i < getNumberOfResidues(); i++) { Residue aa = getResidue(i); if (aa.isAminoAcid()) ret = ret.union(aa.getAtomIndices()); } ret.setName("Protein"); return ret; } /** * Returns the index set of protein atoms except of hydrogen atoms * @return index set of protein atoms except of hydrogen atoms * */ public IndexSet getHeavyProteinIndexSet(){ IndexSet ret = new IndexSet(); for (int i = 0; i < getNumberOfResidues(); i++) { Residue aa = getResidue(i); if (aa.isAminoAcid()) ret = ret.union(aa.getHeavyAtomIndices()); } ret.setName("Protein-H"); return ret; } /** * Returns the index set of alpha carbon atoms * @return index set of alpha carbon atoms */ public IndexSet getAlphaCarbonIndexSet(){ IndexSet ret = new IndexSet(); for (int i = 0; i < getNumberOfResidues(); i++) { Residue aa = getResidue(i); if (aa.isAminoAcid()) { for (int k = 0; k < aa.getNumberOfAtoms(); k++) { if (aa.getAtom(k).isAlphaCarbon()) ret.addIndex(aa.getAtom(k).getIndex()); } } } ret.setName("C-alpha"); return ret; } /** * Returns the index set of backbone atoms * @return index set of backbone atoms */ public IndexSet getBackboneIndexSet(){ IndexSet ret = new IndexSet(); for (int i = 0; i < getNumberOfResidues(); i++) { Residue aa = getResidue(i); if (aa.isAminoAcid()) ret = ret.union(aa.getBackBoneAtomIndices()); } ret.setName("Backbone"); return ret; } /** * Returns the index set of main chain atoms * @return index set of main chain atoms */ public IndexSet getMainChainIndexSet(){ IndexSet ret = new IndexSet(); for (int i = 0; i < getNumberOfResidues(); i++) { Residue aa = getResidue(i); if (aa.isAminoAcid()) ret = ret.union(aa.getMainChainAtomIndices()); } ret.setName("MainChain"); return ret; } /** * Returns the index set of main chain plus beta carbon atoms * @return index set of main chain plus beta carbon atoms */ public IndexSet getMainChainPlusCbIndexSet(){ IndexSet ret = new IndexSet(); for (int i = 0; i < getNumberOfResidues(); i++) { Residue aa = getResidue(i); if (aa.isAminoAcid()) ret = ret.union(aa.getMainChainPlusCbAtomIndices()); } ret.setName("MainChain+Cb"); return ret; } /** * Returns the index set of main chain plus hydrogen atoms * @return index set of main chain plus hydrogen atoms */ public IndexSet getMainChainPlusHIndexSet(){ IndexSet ret = new IndexSet(); for (int i = 0; i < getNumberOfResidues(); i++) { Residue aa = getResidue(i); if (aa.isAminoAcid()) ret = ret.union(aa.getMainChainPlusHAtomIndices()); } ret.setName("MainChain+H"); return ret; } /** * Returns the index set of side chain atoms * @return index set of side chain atoms */ public IndexSet getSideChainIndexSet(){ IndexSet ret = new IndexSet(); for (int i = 0; i < getNumberOfResidues(); i++) { Residue aa = getResidue(i); if (aa.isAminoAcid()) ret = ret.union(aa.getSideChainAtomIndices()); } ret.setName("SideChain"); return ret; } /** * Returns the index set of side chain atoms except of hydrogen atoms * @return index set of side chain atoms except of hydrogen atoms */ public IndexSet getSideChainMinusHIndexSet(){ IndexSet ret = new IndexSet(); for (int i = 0; i < getNumberOfResidues(); i++) { Residue aa = getResidue(i); if (aa.isAminoAcid()) ret = ret.union(aa.getSideChainMinusHAtomIndices()); } ret.setName("SideChain-H"); return ret; } /** * Returns the index set of non-protein atoms * @return index set of non-protein atoms */ public IndexSet getNonProteinIndexSet(){ IndexSet ret = new IndexSet(); for (int i = 0; i < getNumberOfResidues(); i++) { Residue aa = getResidue(i); if (!aa.isAminoAcid()) ret = ret.union(aa.getAtomIndices()); } ret.setName("non-Protein"); return ret; } /** * Returns the index set of water atoms * @return index set of water atoms */ public IndexSet getWaterIndexSet(){ IndexSet ret = new IndexSet(); for (int i = 0; i < getNumberOfResidues(); i++) { Residue aa = getResidue(i); if (aa.isWater()) ret = ret.union(aa.getAtomIndices()); } ret.setName("Water"); return ret; } /** * Returns the list of default index sets * @return list of default index sets */ public IndexSetList getDefaultIndexSetList(){ IndexSetList ret = new IndexSetList(); IndexSet set; set = getSystemIndexSet(); if (set.getNumberOfIndices()>0) ret.addIndexSet(set); set = getProteinIndexSet(); if (set.getNumberOfIndices()>0) ret.addIndexSet(set); set = getHeavyProteinIndexSet(); if (set.getNumberOfIndices()>0) ret.addIndexSet(set); set = getAlphaCarbonIndexSet(); if (set.getNumberOfIndices()>0) ret.addIndexSet(set); set = getBackboneIndexSet(); if (set.getNumberOfIndices()>0) ret.addIndexSet(set); set = getMainChainIndexSet(); if (set.getNumberOfIndices()>0) ret.addIndexSet(set); set = getMainChainPlusCbIndexSet(); if (set.getNumberOfIndices()>0) ret.addIndexSet(set); set = getMainChainPlusHIndexSet(); if (set.getNumberOfIndices()>0) ret.addIndexSet(set); set = getSideChainIndexSet(); if (set.getNumberOfIndices()>0) ret.addIndexSet(set); set = getSideChainMinusHIndexSet(); if (set.getNumberOfIndices()>0) ret.addIndexSet(set); set = getNonProteinIndexSet(); if (set.getNumberOfIndices()>0) ret.addIndexSet(set); set = getWaterIndexSet(); if (set.getNumberOfIndices()>0) ret.addIndexSet(set); return ret; } /** * Returns the index set of atoms of a given chain ID * @param chainID selected chain ID * @return index set defined by chain ID */ public IndexSet getIndexSetOfChainID(String chainID){ IndexSet ret = new IndexSet(); for (int i = 0; i < getNumberOfResidues(); i++) { Residue aa = getResidue(i); if (aa.getChainID().equals(chainID)) ret = ret.union(aa.getAtomIndices()); } ret.setName("chain_"+chainID); return ret; } // Coordinates /** * Sets the coordinates of atom #i * @param coordinates new atomic coordinates */ public void setAtomCoordinates(int i, Point3D coordinates){ getAtom(i).setCoordinates(coordinates); } /** * Sets the coordinates of atom of given index * @param coordinates new atomic coordinates */ public void setAtomOfIndexCoordinates(int index, Point3D coordinates){ getAtomByIndex(index).setCoordinates(coordinates); } /** * Sets the coordinates of all atoms * @param pointlist list of new atomic coordinates */ public void setAllAtomCoordinates(PointList pointlist){ int numofatoms = getNumberOfAtoms(); for (int i = 0; i < numofatoms; i++) { setAtomCoordinates(i, pointlist.getPoint(i)); } } /** * Returns the coordinates of all atoms * @return list of atomic coordinates */ public PointList getAllAtomCoordinates(){ PointList ret = new PointList(); for (int j = 0; j < getNumberOfResidues(); j++) { Residue res = getResidue(j); int numOfAtoms = res.getNumberOfAtoms(); for (int k = 0; k < numOfAtoms; k++) ret.addPoint(res.getAtom(k).getCoordinates()); } return ret; } // Extracting sequence /** * Returns the amino acid sequence of the structure * @return amino acid sequence */ public Sequence getSequence(){ Sequence ret = new Sequence(); ret.setName("Sequence("+name+")"); for (int i = 0; i < getNumberOfResidues(); i++){ Residue res = getResidue(i); if (res.isAminoAcid()) ret.addPosition(res.getIndex(), res.getResidueType()); } return ret; } // Retrieving different chains /** * Returns all chains in an array of Structure objects * @return array of chains */ public Structure[] getChains(){ ArrayList ids = getChainIDs(); Structure[] ret = new Structure[ids.size()]; for (int i = 0; i < ids.size(); i++) { IndexSet g = getIndexSetOfChainID(ids.get(i)); ret[i] = getSubStructure(g); } return ret; } // Getting substructures /** * Returns the substructure defined by the given index set * @param indices index set of substructure * @return substructure */ public Structure getSubStructure(IndexSet indices){ Structure ret = (Structure)clone(); ret.setName(indices.getName()+"(from:"+name+")"); for (int i = 0; i < ret.getNumberOfResidues(); i++) { Residue res = ret.getResidue(i); for (int j = 0; j < res.getNumberOfAtoms(); j++) { Atom atom = res.getAtom(j); if (!indices.isIndexIn(atom.getIndex())) { res.removeAtom(j); j--; } } if (res.getNumberOfAtoms()==0) { ret.removeResidue(i); i--; } } return ret; } // Converting indices /** * Converts atomic indices into list indices * @param indices set of atomic indices * @return list indices */ public ArrayList convertIndicesToArrayListIndices(IndexSet indices){ ArrayList ret = new ArrayList(); int counter = 0; for (int i = 0; i < getNumberOfResidues(); i++) { Residue res = getResidue(i); for (int j = 0; j < res.getNumberOfAtoms(); j++) { Atom atom = res.getAtom(j); if (indices.isIndexIn(atom.getIndex())) ret.add(counter); counter++; } } return ret; } // Mapping residue indices to atom indices and back /** * Maps atomic indices to residue indices (i.e. returns which residues contain the * given atoms). If an atom is not present in any residue it is mapped to residue index -1 * @param indices set of atomic indices * @return residue indices */ public ArrayList mapAtomIndicesToResidueIndices(IndexSet indices){ ArrayList ret = new ArrayList(); ArrayList atoms = indices.getAsArrayList(); for (int k = 0; k < atoms.size() ; k++){ Atom atom = getAtomByIndex(atoms.get(k)); boolean found = false; for (int i = 0; i < getNumberOfResidues(); i++) { Residue res = getResidue(i); if (res.isAtomIn(atom)) { ret.add(res.getIndex()); found = true; } } if (!found) ret.add(-1); } return ret; } /** * Maps residue indices to atomic indices (i.e. returns which atoms are present in the * given residues). * @param indices ArrayList of residue indices * @return IndexSet of atomic indices */ public IndexSet mapResidueIndicesToAtomIndices(ArrayList indices){ IndexSet ret = new IndexSet(); for (int i = 0; i < indices.size(); i++) { Residue res = getResidueByIndex(indices.get(i)); IndexSet atoms = res.getAtomIndices(); ret = ret.union(atoms); } return ret; } // toString, clone, equals /** * Returns the String representation of structure * * @return String representation */ public String toString(){ return toStringAsGRO(); } /** * Returns the String representation of structure in GRO format * * @return String representation in GRO format */ public String toStringAsGRO(){ String title = ""; if (name.equals("")) title = "NO TITLE"; else title = name; StringBuffer buf = new StringBuffer(title+"\n"); buf.append(makeRecordRight(String.valueOf(getNumberOfAtoms()), 5)+"\n"); for (int i = 0; i < getNumberOfResidues(); i++) { Residue res = getResidue(i); for (int j = 0; j < res.getNumberOfAtoms(); j++) buf.append(makeGROLine(this, i, j)+"\n"); } buf.append(" 0.00000 0.00000 0.00000\n"); return buf.toString(); } /** * Returns the String representation of structure in PDB format * * @return String representation in PDB format */ public String toStringAsPDB(){ String title = ""; if (!name.equals("")) title = name; StringBuffer buf = new StringBuffer("TITLE "+title+"\n"); for (int i = 0; i < getNumberOfResidues(); i++) { Residue res = getResidue(i); for (int j = 0; j < res.getNumberOfAtoms(); j++) buf.append(makePDBLine(this, i, j)+"\n"); } return buf.toString(); } /** * Returns summary information about the structure * * @return summary information */ public String toStringInfo(){ return "Name: "+name+" | ("+getNumberOfResidues()+" residues, "+getNumberOfAtoms()+" atoms)"; } /** * Returns an identical Structure object * * @return clone of the structure */ public Object clone(){ try { Structure ret = (Structure)super.clone(); ret.name = name; ret.residues = new ArrayList(); for (int i = 0; i < residues.size(); i++) ret.residues.add((Residue)residues.get(i).clone()); return ret; } catch (CloneNotSupportedException e) { e.printStackTrace(); return null; } } /** * Returns true if the two structures are identical * @param other the other structure * */ public boolean equals(Object other){ if (other == null) return false; if (other == this) return true; if (this.getClass() != other.getClass()) return false; Structure s = (Structure)other; if (!s.name.equals(name)) return false; if (s.residues.size()!=residues.size()) return false; for (int i = 0; i < residues.size(); i++) { if (!s.getResidue(i).equals(getResidue(i))) return false; } return true; } /** * Returns hash code * */ public int hashCode() { return residues.size()+name.length(); } private static String makeGROLine( Structure s, int resi, int atomi){ Residue res = s.getResidue(resi); Atom atom = res.getAtom(atomi); String resindex = String.valueOf(res.getIndex()); String resname = res.getName().toUpperCase(); String atomindex = String.valueOf(atom.getIndex()); String atomname = atom.getName(); String x = correctCoordinate(String.valueOf(roundIt(atom.getXCoordinate(),3))); String y = correctCoordinate(String.valueOf(roundIt(atom.getYCoordinate(),3))); String z = correctCoordinate(String.valueOf(roundIt(atom.getZCoordinate(),3))); resindex = makeRecordRight(resindex, 5); resname = makeRecordLeft(resname, 5); atomindex = makeRecordRight(atomindex, 5); atomname = makeRecordRight(atomname, 5); x = makeRecordRight(x, 8); y = makeRecordRight(y, 8); z = makeRecordRight(z, 8); return resindex+resname+atomname+atomindex+x+y+z; } private static String makePDBLine( Structure s, int resi, int atomi){ Residue res = s.getResidue(resi); Atom atom = res.getAtom(atomi); String resindex = String.valueOf(res.getIndex()); String resname = res.getName().toUpperCase(); String atomindex = String.valueOf(atom.getIndex()); String atomname = atom.getName(); String chainID = res.getChainID(); String occup = String.valueOf(roundIt(atom.getOccupancy(),2)); String bval = String.valueOf(roundIt(atom.getBvalue(),2)); String x = correctCoordinate(String.valueOf(roundIt(10*atom.getXCoordinate(),3))); String y = correctCoordinate(String.valueOf(roundIt(10*atom.getYCoordinate(),3))); String z = correctCoordinate(String.valueOf(roundIt(10*atom.getZCoordinate(),3))); resindex = makeRecordRight(resindex, 4); resname = makeRecordLeft(resname, 3); atomindex = makeRecordRight(atomindex, 5); String atomnameGood = ""; if (atom.getAtomType().getCode().length()==2) atomnameGood = makeRecordLeft(atomname, 4); else { if (atomname.length()<4) atomnameGood = " "+makeRecordLeft(atomname, 3); else atomnameGood = makeRecordLeft(atomname, 4); } x = makeRecordRight(x, 8); y = makeRecordRight(y, 8); z = makeRecordRight(z, 8); occup = makeRecordRight(correctOccupancy(occup), 6); bval = makeRecordRight(correctOccupancy(bval), 6); return "ATOM "+atomindex+" "+atomnameGood+" "+resname+" "+chainID+resindex+" "+x+y+z+occup+bval+" "+makeRecordRight(atom.getAtomType().toString(), 2); } private static String makeRecordRight( String s, int length){ int spaces = length-s.length(); if (spaces<0) { return s.substring(-spaces); } else { StringBuffer buf = new StringBuffer(); for (int i = 0; i < spaces; i++) buf.append(" "); return buf.toString()+s; } } private static String makeRecordLeft( String s, int length){ int spaces = length-s.length(); if (spaces<0) { return s.substring(-spaces); } else { StringBuffer buf = new StringBuffer(); for (int i = 0; i < spaces; i++) buf.append(" "); return s+buf.toString(); } } private static double roundIt( double d, int digit){ double N = Math.pow(10, digit); long L = (int)Math.round(d * N); double ret = L / N; return ret; } private static String correctCoordinate(String c){ StringBuffer buf = new StringBuffer(c); int n = c.length()-c.indexOf(".")-1; if (n<3) for (int i = 0; i < 3-n; i++) buf.append("0"); if (n>3) buf = new StringBuffer(c.substring(0,c.indexOf(".")+4)); return buf.toString(); } private static String correctOccupancy(String c){ StringBuffer buf = new StringBuffer(c); int n = c.length()-c.indexOf(".")-1; if (n<2) for (int i = 0; i < 2-n; i++) buf.append("0"); if (n>2) buf = new StringBuffer(c.substring(0,c.indexOf(".")+3)); return buf.toString(); } } source/jgromacs/data/Trajectory.java000644 000000264041164306052400135020ustar /** * * Written by Márton Münz and Philip C Biggin * Copyright (c) University of Oxford, United Kingdom * Visit http://sbcb.bioch.ox.ac.uk/jgromacs/ * * This source code file is part of JGromacs v1.0. * * JGromacs v1.0 is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * JGromacs v1.0. is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with JGromacs v1.0. If not, see . * */ package jgromacs.data; import java.util.ArrayList; /** * Objects of this class represent a single trajectory * */ public class Trajectory implements Cloneable { private Structure structure = new Structure(); private ArrayList frames = new ArrayList(); private String name = "Noname"; private double startTime = 0; private double timeStep = 0; // Constructors /** * Constructs a new Trajectory object * * */ public Trajectory() { } /** * Constructs a new Trajectory object of given name * * */ public Trajectory(String name) { super(); this.name = name; } /** * Constructs a new Trajectory object of given structure * * */ public Trajectory(Structure structure){ this.structure = structure; } /** * Constructs a new Trajectory object made from an ensemble of structures * * */ public Trajectory(Structure[] ensemble){ structure = ensemble[0]; for (int i = 0; i < ensemble.length; i++) { Structure s = ensemble[i]; frames.add(s.getAllAtomCoordinates()); } } // Getters and setters /** * Returns frames of the trajectory as an ArrayList object * @return frames as an ArrayList * */ public ArrayList getFrames(){ return frames; } /** * Returns frame #i of the trajectory as a PointList object * @return frame #i as a PointList * */ public PointList getFrameAsPointList(int i){ return frames.get(i); } /** * Returns frame #i of the trajectory as a Structure object * @return frame #i as a Structure * */ public Structure getFrameAsStructure(int i){ Structure ret = (Structure)structure.clone(); ret.setName("Frame:"+i); PointList pointlist = getFrameAsPointList(i); ret.setAllAtomCoordinates(pointlist); return ret; } /** * Returns the number of frames in the trajectory * @return number of frames * */ public int getNumberOfFrames(){ return frames.size(); } /** * Returns the name of trajectory * @return name of trajectory * */ public String getName() { return name; } /** * Sets the name of trajectory * @param name name of trajectory * */ public void setName(String name) { this.name = name; } /** * Returns the start time of trajectory * @return start time of trajectory * */ public double getStartTime() { return startTime; } /** * Sets the start time of trajectory * @param startTime start time of trajectory * */ public void setStartTime(double startTime) { this.startTime = startTime; } /** * Returns the time step of trajectory * @return time step of trajectory * */ public double getTimeStep() { return timeStep; } /** * Sets the time step of trajectory * @param timeStep time step of trajectory * */ public void setTimeStep(double timeStep) { this.timeStep = timeStep; } /** * Sets the structure described by the trajectory * @param structure structure described by the trajectory * */ public void setStructure(Structure structure) { this.structure = structure; } /** * Returns the mean frame of trajectory * @return mean frame * */ public PointList getMeanFrame(){ double counter = 0; PointList ret = new PointList(); int numofpoints = getFrameAsPointList(0).getNumberOfPoints(); for (int i = 0; i < numofpoints; i++) ret.addPoint(new Point3D(0,0,0)); for (int i = 0; i < getNumberOfFrames(); i++) { PointList frame = getFrameAsPointList(i); for (int j = 0; j < numofpoints; j++) ret.setPoint(j,ret.getPoint(j).plus(frame.getPoint(j))); counter++; } for (int j = 0; j < numofpoints; j++) ret.setPoint(j, ret.getPoint(j).multiplyByScalar(1.0/counter)); return ret; } /** * Returns the number of atoms in the trajectory * @return number of atoms * */ public int getNumberOfAtoms(){ return getFirstFrameAsPointList().getNumberOfPoints(); } /** * Returns the number of residues in the trajectory * @return number of residues * */ public int getNumberOfResidues(){ return structure.getNumberOfResidues(); } /** * Returns the initial frame of trajectory as a PointList * @return initial frame * */ public PointList getFirstFrameAsPointList(){ return frames.get(0); } /** * Returns the initial frame of trajectory as a Structure * @return initial frame * */ public Structure getFirstFrameAsStructure(){ return getFrameAsStructure(0); } /** * Returns the last frame of trajectory as a PointList * @return last frame * */ public PointList getLastFrameAsPointList(){ return getFrameAsPointList(getNumberOfFrames()-1); } /** * Returns the last frame of trajectory as a Structure * @return last frame * */ public Structure getLastFrameAsStructure(){ return getFrameAsStructure(getNumberOfFrames()-1); } // Modifications /** * Adds a new frame to the trajectory * @param frame new frame * */ public void addFrame(PointList frame){ frames.add(frame); } /** * Removes frame #i from the trajectory * */ public void removeFrame(int i){ frames.remove(i); } /** * Replaces frame #i with a new frame * @param frame new frame * */ public void setFrame(int i, PointList frame){ frames.set(i, frame); } // Conversion /** * Converts frame index to simulation time * @param frameindex frame index * @return simulation time */ public double convertFrameIndexToTime(int frameindex){ return startTime+frameindex*timeStep; } /** * Converts simulation time to frame index * @param time simulation time * @return frame index */ public int convertTimeToFrameIndex(double time){ return (int) Math.round((time-startTime)/timeStep); } // Getting subtrajectories /** * Returns the subtrajectory between the given start and end frames * @param startframe start frame * @param endframe end frame * @return subtrajectory */ public Trajectory getSubTrajectory(int startframe, int endframe){ Trajectory ret = new Trajectory(structure); ret.setName("Subtrajectory["+startframe+","+endframe+"](from:"+getName()+")"); ret.timeStep = timeStep; ret.startTime = convertFrameIndexToTime(startframe); for (int i = startframe; i < endframe+1; i++) { ret.addFrame((PointList)getFrameAsPointList(i).clone()); } return ret; } /** * Returns the subtrajectory between the given start and end frames using the given sampling frequency * @param startframe start frame * @param endframe end frame * @param frequency sampling frequency * @return subtrajectory */ public Trajectory getSubTrajectory(int startframe, int endframe, int frequency){ Trajectory ret = new Trajectory(structure); ret.setName("Subtrajectory["+startframe+","+endframe+"][freq:"+frequency+"](from:"+getName()+")"); ret.timeStep = timeStep*frequency; ret.startTime = convertFrameIndexToTime(startframe); for (int i = startframe; i < endframe+1; i++) { if ((i-startframe)%frequency==0) ret.addFrame((PointList)getFrameAsPointList(i).clone()); } return ret; } /** * Returns the subtrajectory defined by the given index set * @param indices index set of subtrajectory * @return subtrajectory */ public Trajectory getSubTrajectory(IndexSet indices){ Structure s = structure.getSubStructure(indices); Trajectory ret = new Trajectory(s); ret.setName("Subtrajectory[atoms:"+indices.getName()+"](from:"+getName()+")"); ArrayList listIndices = structure.convertIndicesToArrayListIndices(indices); for (int i = 0; i < getNumberOfFrames(); i++) { PointList frame = getFrameAsPointList(i); ret.addFrame(frame.getSubList(listIndices)); } ret.setStartTime(startTime); ret.setTimeStep(timeStep); return ret; } /** * Returns the subtrajectory defined by the given frame list * @param framelist frame list * @return subtrajectory */ public Trajectory getSubTrajectory(FrameIndexSet framelist){ Trajectory ret = new Trajectory(structure); ret.setName("Subtrajectory[frames:"+framelist.getName()+"](from:"+getName()+")"); ret.timeStep = 0; ret.startTime = 0; for (int i = 0; i < getNumberOfFrames(); i++) { if (framelist.isFrameIn(i)) ret.addFrame((PointList)getFrameAsPointList(i).clone()); } return ret; } // toString, clone, equals /** * Returns the String representation of trajectory * * @return String representation */ public String toString(){ if (getNumberOfFrames()>0) return "Name: "+name+" | Start time: "+startTime+" | Time step: "+timeStep+" | ("+getNumberOfAtoms()+" atoms, "+getNumberOfFrames()+" frames)"; else return "Name: "+name+" | Start time: "+0.0+" | Time step: "+0.0+" | (0 atoms, 0 frames)"; } /** * Returns true if the two trajectories are identical * @param other the other trajectory * */ public boolean equals(Object other){ if (other == null) return false; if (other == this) return true; if (this.getClass() != other.getClass()) return false; Trajectory t = (Trajectory)other; if (!t.name.equals(name)) return false; if (Math.abs(t.startTime-startTime)>0.0000001) return false; if (Math.abs(t.timeStep-timeStep)>0.0000001) return false; if (!t.structure.equals(structure)) return false; if (t.getNumberOfFrames()!=getNumberOfFrames()) return false; for (int i = 0; i < getNumberOfFrames(); i++) { if (!t.getFrameAsPointList(i).equals(getFrameAsPointList(i))) return false; } return true; } /** * Returns hash code * */ public int hashCode() { return frames.size()+name.length()+structure.getNumberOfResidues(); } /** * Returns an identical Trajectory object * * @return clone of the trajectory */ public Object clone(){ try { Trajectory ret = (Trajectory)super.clone(); ret.name = name; ret.startTime = startTime; ret.timeStep = timeStep; ret.structure = (Structure)structure.clone(); ret.frames = new ArrayList(); for (int i = 0; i < getNumberOfFrames(); i++) ret.addFrame((PointList)getFrameAsPointList(i).clone()); return ret; } catch (CloneNotSupportedException e) { e.printStackTrace(); return null; } } } source/jgromacs/db/000755 000000000001165162413600101635ustar source/jgromacs/db/AtomType.java000644 000000435241163670077600126100ustar /** * * Written by Márton Münz and Philip C Biggin * Copyright (c) University of Oxford, United Kingdom * Visit http://sbcb.bioch.ox.ac.uk/jgromacs/ * * This source code file is part of JGromacs v1.0. * * JGromacs v1.0 is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * JGromacs v1.0. is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with JGromacs v1.0. If not, see . * */ package jgromacs.db; /** * Objects of this class represent an atom type * */ public class AtomType implements Cloneable{ private int which = 0; // Constants: the full periodic table final static int Hydrogen = 1; final static int Helium = 2; final static int Lithium = 3; final static int Beryllium = 4; final static int Boron = 5; final static int Carbon = 6; final static int Nitrogen = 7; final static int Oxygen = 8; final static int Fluorine = 9; final static int Neon = 10; final static int Sodium = 11; final static int Magnesium = 12; final static int Aluminum = 13; final static int Silicon = 14; final static int Phosphorus = 15; final static int Sulfur = 16; final static int Chlorine = 17; final static int Argon = 18; final static int Potassium = 19; final static int Calcium = 20; final static int Scandium = 21; final static int Titanium = 22; final static int Vanadium = 23; final static int Chromium = 24; final static int Manganese = 25; final static int Iron = 26; final static int Cobalt = 27; final static int Nickel = 28; final static int Copper = 29; final static int Zinc = 30; final static int Gallium = 31; final static int Germanium = 32; final static int Arsenic = 33; final static int Selenium = 34; final static int Bromine = 35; final static int Krypton = 36; final static int Rubidium = 37; final static int Strontium = 38; final static int Yttrium = 39; final static int Zirconium = 40; final static int Niobium = 41; final static int Molybdenum = 42; final static int Technetium = 43; final static int Ruthenium = 44; final static int Rhodium = 45; final static int Palladium = 46; final static int Silver = 47; final static int Cadmium = 48; final static int Indium = 49; final static int Tin = 50; final static int Antimony = 51; final static int Tellurium = 52; final static int Iodine = 53; final static int Xenon = 54; final static int Cesium = 55; final static int Barium = 56; final static int Lanthanum = 57; final static int Cerium = 58; final static int Praseodymium = 59; final static int Neodymium = 60; final static int Promethium = 61; final static int Samarium = 62; final static int Europium = 63; final static int Gadolinium = 64; final static int Terbium = 65; final static int Dysprosium = 66; final static int Holmium = 67; final static int Erbium = 68; final static int Thulium = 69; final static int Ytterbium = 70; final static int Lutetium = 71; final static int Hafnium = 72; final static int Tantalum = 73; final static int Tungsten = 74; final static int Rhenium = 75; final static int Osmium = 76; final static int Iridium = 77; final static int Platinum = 78; final static int Gold = 79; final static int Mercury = 80; final static int Thallium = 81; final static int Lead = 82; final static int Bismuth = 83; final static int Polonium = 84; final static int Astatine = 85; final static int Radon = 86; final static int Francium = 87; final static int Radium = 88; final static int Actinium = 89; final static int Thorium = 90; final static int Protactinium = 91; final static int Uranium = 92; final static int Neptunium = 93; final static int Plutonium = 94; final static int Americium = 95; final static int Curium = 96; final static int Berkelium = 97; final static int Californium = 98; final static int Einsteinium = 99; final static int Fermium = 100; final static int Mendelevium = 101; final static int Nobelium = 102; final static int Lawrencium = 103; final static int Rutherfordium = 104; final static int Dubnium = 105; final static int Seaborgium = 106; final static int Bohrium = 107; final static int Hassium = 108; final static int Meitnerium = 109; // Constructors /** * Constructs a new AtomType object * * */ public AtomType() { } /** * Constructs a new AtomType object of a given type * @param type atom type * */ public AtomType(int type){ which = type; } /** * Constructs a new AtomType object of given code * @param code atom code * */ public AtomType(String code){ code = code.toUpperCase(); if (code.equals("H")) which = 1; if (code.equals("HE")) which = 2; if (code.equals("LI")) which = 3; if (code.equals("BE")) which = 4; if (code.equals("B")) which = 5; if (code.equals("C")) which = 6; if (code.equals("N")) which = 7; if (code.equals("O")) which = 8; if (code.equals("F")) which = 9; if (code.equals("NE")) which = 10; if (code.equals("NA")) which = 11; if (code.equals("MG")) which = 12; if (code.equals("AL")) which = 13; if (code.equals("SI")) which = 14; if (code.equals("P")) which = 15; if (code.equals("S")) which = 16; if (code.equals("CL")) which = 17; if (code.equals("AR")) which = 18; if (code.equals("K")) which = 19; if (code.equals("CA")) which = 20; if (code.equals("SC")) which = 21; if (code.equals("TI")) which = 22; if (code.equals("V")) which = 23; if (code.equals("CR")) which = 24; if (code.equals("MN")) which = 25; if (code.equals("FE")) which = 26; if (code.equals("CO")) which = 27; if (code.equals("NI")) which = 28; if (code.equals("CU")) which = 29; if (code.equals("ZN")) which = 30; if (code.equals("GA")) which = 31; if (code.equals("GE")) which = 32; if (code.equals("AS")) which = 33; if (code.equals("SE")) which = 34; if (code.equals("BR")) which = 35; if (code.equals("KR")) which = 36; if (code.equals("RB")) which = 37; if (code.equals("SR")) which = 38; if (code.equals("Y")) which = 39; if (code.equals("ZR")) which = 40; if (code.equals("NB")) which = 41; if (code.equals("MO")) which = 42; if (code.equals("TC")) which = 43; if (code.equals("RU")) which = 44; if (code.equals("RH")) which = 45; if (code.equals("PD")) which = 46; if (code.equals("AG")) which = 47; if (code.equals("CD")) which = 48; if (code.equals("IN")) which = 49; if (code.equals("SN")) which = 50; if (code.equals("SB")) which = 51; if (code.equals("TE")) which = 52; if (code.equals("I")) which = 53; if (code.equals("XE")) which = 54; if (code.equals("CS")) which = 55; if (code.equals("BA")) which = 56; if (code.equals("LA")) which = 57; if (code.equals("CE")) which = 58; if (code.equals("PR")) which = 59; if (code.equals("ND")) which = 60; if (code.equals("PM")) which = 61; if (code.equals("SM")) which = 62; if (code.equals("EU")) which = 63; if (code.equals("GD")) which = 64; if (code.equals("TB")) which = 65; if (code.equals("DY")) which = 66; if (code.equals("HO")) which = 67; if (code.equals("ER")) which = 68; if (code.equals("TM")) which = 69; if (code.equals("YB")) which = 70; if (code.equals("LU")) which = 71; if (code.equals("HF")) which = 72; if (code.equals("TA")) which = 73; if (code.equals("W")) which = 74; if (code.equals("RE")) which = 75; if (code.equals("OS")) which = 76; if (code.equals("IR")) which = 77; if (code.equals("PT")) which = 78; if (code.equals("AU")) which = 79; if (code.equals("HG")) which = 80; if (code.equals("TL")) which = 81; if (code.equals("PB")) which = 82; if (code.equals("BI")) which = 83; if (code.equals("PO")) which = 84; if (code.equals("AT")) which = 85; if (code.equals("RN")) which = 86; if (code.equals("FR")) which = 87; if (code.equals("RA")) which = 88; if (code.equals("AC")) which = 89; if (code.equals("TH")) which = 90; if (code.equals("PA")) which = 91; if (code.equals("U")) which = 92; if (code.equals("NP")) which = 93; if (code.equals("PU")) which = 94; if (code.equals("AM")) which = 95; if (code.equals("CM")) which = 96; if (code.equals("BK")) which = 97; if (code.equals("CF")) which = 98; if (code.equals("ES")) which = 99; if (code.equals("FM")) which = 100; if (code.equals("MD")) which = 101; if (code.equals("NO")) which = 102; if (code.equals("LR")) which = 103; if (code.equals("RF")) which = 104; if (code.equals("DB")) which = 105; if (code.equals("SG")) which = 106; if (code.equals("BH")) which = 107; if (code.equals("HS")) which = 108; if (code.equals("MT")) which = 109; } // Getters /** * Returns the code of atom type * @return atom code * */ public String getCode(){ if (which==1) return "H"; if (which==2) return "He"; if (which==3) return "Li"; if (which==4) return "Be"; if (which==5) return "B"; if (which==6) return "C"; if (which==7) return "N"; if (which==8) return "O"; if (which==9) return "F"; if (which==10) return "Ne"; if (which==11) return "Na"; if (which==12) return "Mg"; if (which==13) return "Al"; if (which==14) return "Si"; if (which==15) return "P"; if (which==16) return "S"; if (which==17) return "Cl"; if (which==18) return "Ar"; if (which==19) return "K"; if (which==20) return "Ca"; if (which==21) return "Sc"; if (which==22) return "Ti"; if (which==23) return "V"; if (which==24) return "Cr"; if (which==25) return "Mn"; if (which==26) return "Fe"; if (which==27) return "Co"; if (which==28) return "Ni"; if (which==29) return "Cu"; if (which==30) return "Zn"; if (which==31) return "Ga"; if (which==32) return "Ge"; if (which==33) return "As"; if (which==34) return "Se"; if (which==35) return "Br"; if (which==36) return "Kr"; if (which==37) return "Rb"; if (which==38) return "Sr"; if (which==39) return "Y"; if (which==40) return "Zr"; if (which==41) return "Nb"; if (which==42) return "Mo"; if (which==43) return "Tc"; if (which==44) return "Ru"; if (which==45) return "Rh"; if (which==46) return "Pd"; if (which==47) return "Ag"; if (which==48) return "Cd"; if (which==49) return "In"; if (which==50) return "Sn"; if (which==51) return "Sb"; if (which==52) return "Te"; if (which==53) return "I"; if (which==54) return "Xe"; if (which==55) return "Cs"; if (which==56) return "Ba"; if (which==57) return "La"; if (which==58) return "Ce"; if (which==59) return "Pr"; if (which==60) return "Nd"; if (which==61) return "Pm"; if (which==62) return "Sm"; if (which==63) return "Eu"; if (which==64) return "Gd"; if (which==65) return "Tb"; if (which==66) return "Dy"; if (which==67) return "Ho"; if (which==68) return "Er"; if (which==69) return "Tm"; if (which==70) return "Yb"; if (which==71) return "Lu"; if (which==72) return "Hf"; if (which==73) return "Ta"; if (which==74) return "W"; if (which==75) return "Re"; if (which==76) return "Os"; if (which==77) return "Ir"; if (which==78) return "Pt"; if (which==79) return "Au"; if (which==80) return "Hg"; if (which==81) return "Tl"; if (which==82) return "Pb"; if (which==83) return "Bi"; if (which==84) return "Po"; if (which==85) return "At"; if (which==86) return "Rn"; if (which==87) return "Fr"; if (which==88) return "Ra"; if (which==89) return "Ac"; if (which==90) return "Th"; if (which==91) return "Pa"; if (which==92) return "U"; if (which==93) return "Np"; if (which==94) return "Pu"; if (which==85) return "At"; if (which==86) return "Rn"; if (which==87) return "Fr"; if (which==88) return "Ra"; if (which==89) return "Ac"; if (which==90) return "Th"; if (which==91) return "Pa"; if (which==92) return "U"; if (which==93) return "Np"; if (which==94) return "Pu"; if (which==95) return "Am"; if (which==96) return "Cm"; if (which==97) return "Bk"; if (which==98) return "Cf"; if (which==99) return "Es"; if (which==100) return "Fm"; if (which==101) return "Md"; if (which==102) return "No"; if (which==103) return "Lr"; if (which==104) return "Rf"; if (which==105) return "Db"; if (which==106) return "Sg"; if (which==107) return "Bh"; if (which==108) return "Hs"; if (which==109) return "Mt"; return ""; } /** * Returns the full name of atom type * @return atom name * */ public String getFullName(){ if (which==1) return "Hydrogen"; if (which==2) return "Helium"; if (which==3) return "Lithium"; if (which==4) return "Beryllium"; if (which==5) return "Boron"; if (which==6) return "Carbon"; if (which==7) return "Nitrogen"; if (which==8) return "Oxygen"; if (which==9) return "Fluorine"; if (which==10) return "Neon"; if (which==11) return "Sodium"; if (which==12) return "Magnesium"; if (which==13) return "Aluminum"; if (which==14) return "Silicon"; if (which==15) return "Phosphorus"; if (which==16) return "Sulfur"; if (which==17) return "Chlorine"; if (which==18) return "Argon"; if (which==19) return "Potassium"; if (which==20) return "Calcium"; if (which==21) return "Scandium"; if (which==22) return "Titanium"; if (which==23) return "Vanadium"; if (which==24) return "Chromium"; if (which==25) return "Manganese"; if (which==26) return "Iron"; if (which==27) return "Cobalt"; if (which==28) return "Nickel"; if (which==29) return "Copper"; if (which==30) return "Zinc"; if (which==31) return "Gallium"; if (which==32) return "Germanium"; if (which==33) return "Arsenic"; if (which==34) return "Selenium"; if (which==35) return "Bromine"; if (which==36) return "Krypton"; if (which==37) return "Rubidium"; if (which==38) return "Strontium"; if (which==39) return "Yttrium"; if (which==40) return "Zirconium"; if (which==41) return "Niobium"; if (which==42) return "Molybdenum"; if (which==43) return "Technetium"; if (which==44) return "Ruthenium"; if (which==45) return "Rhodium"; if (which==46) return "Palladium"; if (which==47) return "Silver"; if (which==48) return "Cadmium"; if (which==49) return "Indium"; if (which==50) return "Tin"; if (which==51) return "Antimony"; if (which==52) return "Tellurium"; if (which==53) return "Iodine"; if (which==54) return "Xenon"; if (which==55) return "Cesium"; if (which==56) return "Barium"; if (which==57) return "Lanthanum"; if (which==58) return "Cerium"; if (which==59) return "Praseodymium"; if (which==60) return "Neodymium"; if (which==61) return "Promethium"; if (which==62) return "Samarium"; if (which==63) return "Europium"; if (which==64) return "Gadolinium"; if (which==65) return "Terbium"; if (which==66) return "Dysprosium"; if (which==67) return "Holmium"; if (which==68) return "Erbium"; if (which==69) return "Thulium"; if (which==70) return "Ytterbium"; if (which==71) return "Lutetium"; if (which==72) return "Hafnium"; if (which==73) return "Tantalum"; if (which==74) return "Tungsten"; if (which==75) return "Rhenium"; if (which==76) return "Osmium"; if (which==77) return "Iridium"; if (which==78) return "Platinum"; if (which==79) return "Gold"; if (which==80) return "Mercury"; if (which==81) return "Thallium"; if (which==82) return "Lead"; if (which==83) return "Bismuth"; if (which==84) return "Polonium"; if (which==85) return "Astatine"; if (which==86) return "Radon"; if (which==87) return "Francium"; if (which==88) return "Radium"; if (which==89) return "Actinium"; if (which==90) return "Thorium"; if (which==91) return "Protactinium"; if (which==92) return "Uranium"; if (which==93) return "Neptunium"; if (which==94) return "Plutonium"; if (which==95) return "Americium"; if (which==96) return "Curium"; if (which==97) return "Berkelium"; if (which==98) return "Californium"; if (which==99) return "Einsteinium"; if (which==100) return "Fermium"; if (which==101) return "Mendelevium"; if (which==102) return "Nobelium"; if (which==103) return "Lawrencium"; if (which==104) return "Rutherfordium"; if (which==105) return "Dubnium"; if (which==106) return "Seaborgium"; if (which==107) return "Bohrium"; if (which==108) return "Hassium"; if (which==109) return "Meitnerium"; return ""; } // toString, clone, equals /** * Returns the String representation of atom type * * @return String representation */ public String toString(){ return getCode(); } /** * Returns an identical AtomType object * * @return clone of the atom type */ public Object clone(){ try { AtomType ret = (AtomType)super.clone(); ret.which = which; return ret; } catch (CloneNotSupportedException e) { e.printStackTrace(); return null; } } /** * Returns true if the two atom types are identical * @param other the other atom type * */ public boolean equals(Object other){ if (other == null) return false; if (other == this) return true; if (this.getClass() != other.getClass()) return false; AtomType type = (AtomType)other; if (type.which==which) return true; else return false; } /** * Returns hash code * */ public int hashCode() { return which; } } source/jgromacs/db/package-info.java000644 000000001431153530242600133440ustar /** * jgromacs.db contains two classes defining atom and residue types */ package jgromacs.db;source/jgromacs/db/ResidueType.java000644 000000175171164336122400133000ustar /** * * Written by Márton Münz and Philip C Biggin * Copyright (c) University of Oxford, United Kingdom * Visit http://sbcb.bioch.ox.ac.uk/jgromacs/ * * This source code file is part of JGromacs v1.0. * * JGromacs v1.0 is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * JGromacs v1.0. is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with JGromacs v1.0. If not, see . * */ package jgromacs.db; /** * Objects of this class represent a residue type * */ public class ResidueType implements Cloneable { private int which = 0; // Constants: amino acids final static int Alanine = 1; final static int Arginine = 2; final static int Asparagine = 3; final static int AsparticAcid = 4; final static int Cysteine = 5; final static int GlutamicAcid = 6; final static int Glutamine = 7; final static int Glycine = 8; final static int Histidine = 9; final static int Isoleucine = 10; final static int Leucine = 11; final static int Lysine = 12; final static int Methionine = 13; final static int Phenylalanine = 14; final static int Proline = 15; final static int Serine = 16; final static int Threonine = 17; final static int Tryptophan = 18; final static int Tyrosine = 19; final static int Valine = 20; final static int Water = 21; final static int Other = 22; final static int Unknown = 23; // Constructors /** * Constructs a new ResidueType object * * */ public ResidueType() { // TODO Auto-generated constructor stub } /** * Constructs a new ResidueType object of a given type * @param type residue type * */ public ResidueType(int type){ which = type; } /** * Constructs a new ResidueType object of given code * @param code residue code * */ public ResidueType(String code){ code = code.toUpperCase(); which = 22; if (code.equals("A")||code.startsWith("ALA")) which = 1; if (code.equals("R")||code.startsWith("ARG")) which = 2; if (code.equals("N")||code.startsWith("ASN")) which = 3; if (code.equals("D")||code.startsWith("ASP")) which = 4; if (code.equals("C")||code.startsWith("CYS")) which = 5; if (code.equals("E")||code.startsWith("GLU")) which = 6; if (code.equals("Q")||code.startsWith("GLN")) which = 7; if (code.equals("G")||code.startsWith("GLY")) which = 8; if (code.equals("H")||code.startsWith("HIS")) which = 9; if (code.equals("I")||code.startsWith("ILE")) which = 10; if (code.equals("L")||code.startsWith("LEU")) which = 11; if (code.equals("K")||code.startsWith("LYS")) which = 12; if (code.equals("M")||code.startsWith("MET")) which = 13; if (code.equals("F")||code.startsWith("PHE")) which = 14; if (code.equals("P")||code.startsWith("PRO")) which = 15; if (code.equals("S")||code.startsWith("SER")) which = 16; if (code.equals("T")||code.startsWith("THR")) which = 17; if (code.equals("W")||code.startsWith("TRP")) which = 18; if (code.equals("Y")||code.startsWith("TYR")) which = 19; if (code.equals("V")||code.startsWith("VAL")) which = 20; if (code.equals("Sol")||code.startsWith("SOL")||code.startsWith("HOH")) which = 21; if (code.equals("X")||code.startsWith("XXX")) which = 23; } // Getters /** * Returns 1 letter code of residue type * @return residue code * */ public String get1LetterCode(){ if (which==1) return "A"; if (which==2) return "R"; if (which==3) return "N"; if (which==4) return "D"; if (which==5) return "C"; if (which==6) return "E"; if (which==7) return "Q"; if (which==8) return "G"; if (which==9) return "H"; if (which==10) return "I"; if (which==11) return "L"; if (which==12) return "K"; if (which==13) return "M"; if (which==14) return "F"; if (which==15) return "P"; if (which==16) return "S"; if (which==17) return "T"; if (which==18) return "W"; if (which==19) return "Y"; if (which==20) return "V"; if (which==21) return "~"; if (which==22) return "?"; if (which==23) return "X"; return ""; } /** * Returns 3 letter code of residue type * @return residue code * */ public String get3LetterCode(){ if (which==1) return "Ala"; if (which==2) return "Arg"; if (which==3) return "Asn"; if (which==4) return "Asp"; if (which==5) return "Cys"; if (which==6) return "Glu"; if (which==7) return "Gln"; if (which==8) return "Gly"; if (which==9) return "His"; if (which==10) return "Ile"; if (which==11) return "Leu"; if (which==12) return "Lys"; if (which==13) return "Met"; if (which==14) return "Phe"; if (which==15) return "Pro"; if (which==16) return "Ser"; if (which==17) return "Thr"; if (which==18) return "Trp"; if (which==19) return "Tyr"; if (which==20) return "Val"; if (which==21) return "Sol"; if (which==22) return "Oth"; if (which==23) return "Xxx"; return ""; } /** * Returns full name of residue type * @return residue name * */ public String getFullName(){ if (which==1) return "Alanine"; if (which==2) return "Arginine"; if (which==3) return "Asparagine"; if (which==4) return "AsparticAcid"; if (which==5) return "Cysteine"; if (which==6) return "GlutamicAcid"; if (which==7) return "Glutamine"; if (which==8) return "Glycine"; if (which==9) return "Histidine"; if (which==10) return "Isoleucine"; if (which==11) return "Leucine"; if (which==12) return "Lysine"; if (which==13) return "Methionine"; if (which==14) return "Phenylalanine"; if (which==15) return "Proline"; if (which==16) return "Serine"; if (which==17) return "Threonine"; if (which==18) return "Tryptophan"; if (which==19) return "Tyrosine"; if (which==20) return "Valine"; if (which==21) return "Water"; if (which==22) return "Other"; if (which==23) return "Unknown"; return ""; } // is? /** * Returns true if it is an amino acid (not water or else) * * */ public boolean isAminoAcid(){ if (which == 0) return false; if (which<21) return true; else return false; } /** * Returns true if it is water (not amino acid or else) * * */ public boolean isWater(){ if (which == 21) return true; else return false; } /** * Returns true if it is not an amino acid nor water * * */ public boolean isOther(){ if (which == 22) return true; else return false; } // toString, clone, equals /** * Returns the String representation of residue type * * @return String representation */ public String toString(){ return get3LetterCode(); } /** * Returns an identical ResidueType object * * @return clone of the residue type */ public Object clone(){ try { ResidueType ret = (ResidueType)super.clone(); ret.which = which; return ret; } catch (CloneNotSupportedException e) { e.printStackTrace(); return null; } } /** * Returns true if the two residue types are identical * @param other the other residue type * */ public boolean equals(Object other){ if (other == null) return false; if (other == this) return true; if (this.getClass() != other.getClass()) return false; ResidueType type = (ResidueType)other; if (type.which==which) return true; else return false; } /** * Returns hash code * */ public int hashCode() { return which; } } source/jgromacs/io/000755 000000000001165162413600102055ustar source/jgromacs/io/IOData.java000644 000000625341165004477000121620ustar /** * * Written by Márton Münz and Philip C Biggin * Copyright (c) University of Oxford, United Kingdom * Visit http://sbcb.bioch.ox.ac.uk/jgromacs/ * * This source code file is part of JGromacs v1.0. * * JGromacs v1.0 is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * JGromacs v1.0. is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with JGromacs v1.0. If not, see . * */ package jgromacs.io; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import jgromacs.data.Alignment; import jgromacs.data.Atom; import jgromacs.data.IndexSet; import jgromacs.data.IndexSetList; import jgromacs.data.Point3D; import jgromacs.data.PointList; import jgromacs.data.Residue; import jgromacs.data.Sequence; import jgromacs.data.Structure; import jgromacs.data.Trajectory; import jgromacs.db.AtomType; import jgromacs.db.ResidueType; /** * This class contains static methods for IO of data objects * */ public class IOData { // IO Structures /** * Reads structure from the given GRO file * @param filename Input file name * @return structure as a Structure object * @throws IOException */ public static Structure readStructureFromGRO(String filename) throws IOException{ Structure ret = new Structure(); ArrayList lines = readFromFileToVector(filename); ret.setName(lines.get(0)); lines.remove(0); lines.remove(0); String line; int currentResidue = -1; Residue res = new Residue(); for (int i= 0; i < lines.size()-1; i++) { line = (String)lines.get(i); Integer resindex = Integer.valueOf(line.substring(0,5).trim()); String resname = line.substring(5,10).trim(); String atomname = line.substring(10,15).trim(); Integer atomindex = Integer.valueOf(line.substring(15,20).trim()); Double x = Double.valueOf(line.substring(20,28).trim()); Double y = Double.valueOf(line.substring(28,36).trim()); Double z = Double.valueOf(line.substring(36,44).trim()); if (resindex!=currentResidue) { if (i>0) ret.addResidue(res); res = new Residue(); res.setName(resname); res.setIndex(resindex); res.setResidueType(new ResidueType(resname)); currentResidue = resindex; } Atom atom = new Atom(); atom.setName(atomname); if (res.isAminoAcid()) atom.setAtomType(new AtomType(atomname.substring(0, 1))); else atom.setAtomType(new AtomType(atomname)); atom.setIndex(atomindex); atom.setCoordinates(new Point3D(x, y, z)); res.addAtom(atom); } ret.addResidue(res); return ret; } /** * Reads structure from the given PDB file * @param filename Input file name * @return structure as a Structure object * @throws IOException */ public static Structure readStructureFromPDB(String filename) throws IOException{ Structure ret = new Structure(); ret.setName(filename); ArrayList lines = readFromFileToVector(filename); int currentResidue = -1; Residue res = new Residue(); boolean ok = true; boolean titleok = false; for (int i= 0; i < lines.size(); i++) { String line = (String)lines.get(i); if (isTitleLine(line)&&!titleok) { ret.setName(line.substring(10)); titleok = true; } if (isModelEndLine(line)) ok = false; if (ok&&isAtomLine(line)) { Integer resindex = Integer.valueOf(line.substring(22,26).trim()); String resname = line.substring(17,20).trim(); String chainID = line.substring(21,22).trim(); if (resindex!=currentResidue) { if (currentResidue!=-1) { ret.addResidue(res); } res = new Residue(); res.setChainID(chainID); res.setName(resname); res.setIndex(resindex); res.setResidueType(new ResidueType(resname)); currentResidue = resindex; } String atomname = line.substring(12,16).trim(); String atomtype = ""; if (line.length()>=78) atomtype = line.substring(76,78).trim(); if (atomtype.equals("")){ if (res.isAminoAcid()) atomtype = atomname.substring(0, 1); else atomtype = atomname; } Integer atomindex = Integer.valueOf(line.substring(6,11).trim()); Double x = Double.valueOf(line.substring(30,38).trim())/10; Double y = Double.valueOf(line.substring(38,46).trim())/10; Double z = Double.valueOf(line.substring(46,54).trim())/10; double occupancy = Double.valueOf(line.substring(54,60).trim()); double bvalue = Double.valueOf(line.substring(60,66).trim()); Atom atom = new Atom(); atom.setName(atomname); atom.setAtomType(new AtomType(atomtype)); atom.setIndex(atomindex); atom.setCoordinates(new Point3D(x, y, z)); atom.setOccupancy(occupancy); atom.setBvalue(bvalue); res.addAtom(atom); } } ret.addResidue(res); return ret; } /** * Reads the given model from the given PDB file * @param filename Input file name * @param model model to be read * @return structure as a Structure object * @throws IOException */ public static Structure readStructureFromPDB(String filename, int model) throws IOException{ if (model>howManyModelsInPDB(filename)) return null; Structure ret = new Structure(); ret.setName(filename+"(Model_"+model+")"); ArrayList lines = readFromFileToVector(filename); int currentResidue = -1; Residue res = new Residue(); boolean ok = true; int modelcounter = 1; for (int i= 0; i < lines.size(); i++) { String line = (String)lines.get(i); if (isModelEndLine(line)) modelcounter++; if (modelcounter==model) ok = true; else ok = false; if (ok&isAtomLine(line)) { Integer resindex = Integer.valueOf(line.substring(22,26).trim()); String resname = line.substring(17,20).trim(); String chainID = line.substring(21,22).trim(); if (resindex!=currentResidue) { if (currentResidue!=-1) { ret.addResidue(res); } res = new Residue(); res.setChainID(chainID); res.setName(resname); res.setIndex(resindex); res.setResidueType(new ResidueType(resname)); currentResidue = resindex; } String atomname = line.substring(12,16).trim(); String atomtype = ""; if (line.length()>=78) atomtype = line.substring(76,78).trim(); if (atomtype.equals("")){ if (res.isAminoAcid()) atomtype = atomname.substring(0, 1); else atomtype = atomname; } Integer atomindex = Integer.valueOf(line.substring(6,11).trim()); Double x = Double.valueOf(line.substring(30,38).trim())/10; Double y = Double.valueOf(line.substring(38,46).trim())/10; Double z = Double.valueOf(line.substring(46,54).trim())/10; double occupancy = Double.valueOf(line.substring(54,60).trim()); double bvalue = Double.valueOf(line.substring(60,66).trim()); Atom atom = new Atom(); atom.setName(atomname); atom.setAtomType(new AtomType(atomtype)); atom.setIndex(atomindex); atom.setCoordinates(new Point3D(x, y, z)); atom.setOccupancy(occupancy); atom.setBvalue(bvalue); res.addAtom(atom); } } ret.addResidue(res); return ret; } /** * Returns the number of models in the given PDB file * @param filename Input file name * @return number of models * @throws IOException */ public static int howManyModelsInPDB( String filename) throws IOException{ int ret = 0; boolean something = false; ArrayList lines = readFromFileToVector(filename); for (int i= 0; i < lines.size(); i++) { String line = (String)lines.get(i); if (isModelStartLine(line)) { ret++; } if (isAtomLine(line)) { something = true; } } if ((ret==0)&something) ret = 1; return ret; } /** * Reads an ensemble of structures from the given PDB file * @param filename Input file name * @return ensemble of structures as a Structure[] object * @throws IOException */ public static Structure[] readStructuresFromPDB(String filename) throws IOException{ int howmany = howManyModelsInPDB(filename); if (howmany>1){ Structure[] ret = new Structure[howmany]; ArrayList lines = readFromFileToVector(filename); Structure s = new Structure(); int currentResidue = -1; Residue res = new Residue(); boolean started = false; int q = 0; for (int i= 0; i < lines.size(); i++) { String line = (String)lines.get(i); if (isModelStartLine(line)){ s = new Structure(); currentResidue = -1; res = new Residue(); q++; if (!started) { q = 0; } started = true; } if (isModelEndLine(line)){ s.addResidue(res); s.setName(filename+"(Model_"+(q+1)+")"); ret[q] = s; } if (isAtomLine(line)) { Integer resindex = Integer.valueOf(line.substring(22,26).trim()); String resname = line.substring(17,20).trim(); String chainID = line.substring(21,22).trim(); if (resindex!=currentResidue) { if (currentResidue!=-1) { s.addResidue(res); } res = new Residue(); res.setChainID(chainID); res.setName(resname); res.setIndex(resindex); res.setResidueType(new ResidueType(resname)); currentResidue = resindex; } String atomname = line.substring(12,16).trim(); String atomtype = ""; if (line.length()>=78) atomtype = line.substring(76,78).trim(); if (atomtype.equals("")){ if (res.isAminoAcid()) atomtype = atomname.substring(0, 1); else atomtype = atomname; } Integer atomindex = Integer.valueOf(line.substring(6,11).trim()); Double x = Double.valueOf(line.substring(30,38).trim())/10; Double y = Double.valueOf(line.substring(38,46).trim())/10; Double z = Double.valueOf(line.substring(46,54).trim())/10; double occupancy = Double.valueOf(line.substring(54,60).trim()); double bvalue = Double.valueOf(line.substring(60,66).trim()); Atom atom = new Atom(); atom.setName(atomname); atom.setAtomType(new AtomType(atomtype)); atom.setIndex(atomindex); atom.setCoordinates(new Point3D(x, y, z)); atom.setOccupancy(occupancy); atom.setBvalue(bvalue); res.addAtom(atom); } } return ret; } else { Structure[] ret = new Structure[1]; ret[0] = readStructureFromPDB(filename); return ret; } } /** * Reads an ensemble of structures from PDB files in the given directory * @param path path of directory * @return ensemble of structures as a Structure[] object * @throws IOException */ public static Structure[] readStructuresFromPDBsInDirectory(String path) throws IOException{ File dir = new File(path); String[] children = dir.list(); int numofPDBs = 0; for (int i = 0; i < children.length; i++) { String child = children[i]; if (child.endsWith(".pdb")||child.endsWith(".PDB")) numofPDBs++; } Structure[] ret = new Structure[numofPDBs]; int counter = 0; for (int i = 0; i < children.length; i++) { String child = children[i]; if (child.endsWith(".pdb")||child.endsWith(".PDB")){ Structure s = IOData.readStructureFromPDB(path+"//"+child); ret[counter] = s; counter++; } } return ret; } /** * Writes a structure to the given GRO file * @param filename Output file name * @param structure Structure object to be written out * @throws IOException */ public static void writeStructureToGRO(String filename, Structure structure) throws IOException{ writeStringToFile(filename, structure.toStringAsGRO()); } /** * Writes a structure to the given PDB file * @param filename Output file name * @param structure Structure object to be written out * @throws IOException */ public static void writeStructureToPDB(String filename, Structure structure) throws IOException{ writeStringToFile(filename, structure.toStringAsPDB()); } // IO Trajectories /** * Reads a trajectory from the given XTC or TRR file * @param structure reference structure * @param filename Input file name * @return trajectory as a Trajectory object * @throws IOException */ public static Trajectory readTrajectory(Structure structure, String filename) throws IOException{ Trajectory ret = new Trajectory(structure); ret.setName(filename); int counter=0; int counterFrame=0; double firsttime = 0; double secondtime = 0; ArrayList rows = new ArrayList(); Runtime rt = Runtime.getRuntime(); Process pr = rt.exec("gmxdump -f "+filename); BufferedReader input = new BufferedReader(new InputStreamReader(pr.getInputStream())); String line=null; while((line=input.readLine()) != null) { if ((line.indexOf("time")>0)&(counterFrame==0)) firsttime = extractTime(line); if ((line.indexOf("time")>0)&(counterFrame==1)) secondtime = extractTime(line); if ((line.indexOf("frame")>0)&(counter>0)) { PointList pointlist = extractPointList(rows); ret.addFrame(pointlist); counterFrame++; rows = new ArrayList(); } rows.add(line); counter++; } PointList pointlist = extractPointList(rows); ret.addFrame(pointlist); input.close(); ret.setStartTime(firsttime); ret.setTimeStep(secondtime-firsttime); ret.setName(filename.substring(0,filename.indexOf("."))); return ret; } /** * Reads a trajectory from the given dumped XTC or TRR file * @param structure reference structure * @param filename Input file name * @return trajectory as a Trajectory object * @throws IOException */ public static Trajectory readDumpedTrajectory( Structure structure, String filename) throws IOException{ Trajectory ret = new Trajectory(structure); ret.setName(filename); File file = new File(filename); ArrayList rows = new ArrayList(); double firsttime = 0; double secondtime = 0; BufferedReader input = new BufferedReader(new FileReader(file)); String line = null; int counter=0; int counterFrame=0; while (( line = input.readLine()) != null) { if ((line.indexOf("time")>0)&(counterFrame==0)) firsttime = extractTime(line); if ((line.indexOf("time")>0)&(counterFrame==1)) secondtime = extractTime(line); if ((line.indexOf("frame")>0)&(counter>0)) { PointList pointlist = extractPointList(rows); ret.addFrame(pointlist); counterFrame++; rows = new ArrayList(); } rows.add(line); counter++; } PointList pointlist = extractPointList(rows); ret.addFrame(pointlist); ret.setStartTime(firsttime); ret.setTimeStep(secondtime-firsttime); ret.setName(filename); input.close(); return ret; } private static double extractTime(String line){ String str = line.substring(line.indexOf("time=")); str = str.substring(0, str.indexOf(" ")); str = str.substring(str.indexOf("=")+1); return Double.valueOf(str); } // IO Sequences and Alignments /** * Reads a sequence from the given FASTA file * @param filename Input file name * @return sequence as a Sequence object * @throws IOException */ public static Sequence readSequenceFromFASTA(final String filename) throws IOException{ Sequence ret = new Sequence(); Boolean ok = false; ArrayList rows = readFromFileToVector(filename); for (int i = 0; i < rows.size(); i++) { String row = (String)rows.get(i); if (row.indexOf(">")>=0) { row = row.substring(row.indexOf(">")+1); if (!ok) { ret.setName(row); ok = true; } else { return ret; } } else { ret.addPositionsFromString(row); } } return ret; } /** * Reads an alignment from the given FASTA file * @param filename Input file name * @return alignment as an Alignment object * @throws IOException */ public static Alignment readAlignmentFromFASTA( String filename) throws IOException{ ArrayListrows = readFromFileToVector(filename); Alignment ret = new Alignment(); Boolean ok = false; Sequence seq = new Sequence(); for (int i = 0; i < rows.size(); i++) { String row = (String)rows.get(i); if (row.indexOf(">")>=0) { row = row.substring(row.indexOf(">")+1); if (ok) { Sequence sc = (Sequence)seq.clone(); ret.addSequence(sc); seq = new Sequence(row); } else { seq = new Sequence(row); ok = true; } } else { seq.addPositionsFromString(row); } } ret.addSequence(seq); return ret; } /** * Writes a sequence to the given FASTA file * @param filename Output file name * @param sequence Sequence object to be written out * @throws IOException * */ public static void writeSequenceToFASTA(String filename, Sequence sequence) throws IOException{ writeStringToFile(filename, sequence.toString()); } /** * Writes an alignment to the given FASTA file * @param filename Output file name * @param alignment Alignment object to be written out * @throws IOException * */ public static void writeAlignmentToFASTA( String filename, Alignment alignment) throws IOException{ writeStringToFile(filename, alignment.toString()); } // IO IndexSets and IndexSetLists /** * Reads an index set from the given NDX file * @param filename Input file name * @return index set as an IndexSet object * @throws IOException */ public static IndexSet readIndexSetFromNDX( String filename) throws IOException{ IndexSet ret; ArrayList rows = readFromFileToVector(filename); for (int i = 0; i < rows.size(); i++) { if (((String)rows.get(i)).equals("")) { rows.remove(i); i--; } } String row = (String)rows.get(0); row = row.substring(row.indexOf("[")+1, row.indexOf("]")); row = row.trim(); ret = new IndexSet(row); for (int i = 1; i < rows.size(); i++) { row = (String)rows.get(i); if (row.indexOf("[")>=0) { return ret; } ArrayList values = extractValues(row); for (int j = 0; j < values.size(); j++){ String number = (String)values.get(j); if (!number.equals("")) { ret.addIndex(Integer.valueOf(number)); } } } return ret; } /** * Reads an index set list from the given NDX file * @param filename Input file name * @return index set list as an IndexSetList object * @throws IOException */ public static IndexSetList readIndexSetListFromNDX( String filename) throws IOException{ IndexSetList ret = new IndexSetList(); ArrayList rows = readFromFileToVector(filename); String row = ""; IndexSet set = new IndexSet(); for (int i = 0; i < rows.size(); i++) { row = (String)rows.get(i); if (row.indexOf("[")>=0) { if (i>0) { ret.addIndexSet(set); } row = row.substring(row.indexOf("[")+1, row.indexOf("]")); row = row.trim(); set = new IndexSet(row); } else { ArrayList values = extractValues(row); for (int j = 0; j < values.size(); j++){ String number = (String)values.get(j); if (!number.equals("")) { set.addIndex(Integer.valueOf(number)); } } } } ret.addIndexSet(set); return ret; } /** * Writes an index set to the given NDX file * @param filename Output file name * @param set IndexSet object to be written out * @throws IOException * */ public static void writeIndexSetToNDX(String filename, IndexSet set) throws IOException{ writeStringToFile(filename, set.toString()); } /** * Writes an index set list to the given NDX file * @param filename Output file name * @param indexsetlist IndexSetList object to be written out * @throws IOException * */ public static void writeIndexSetListToNDX( String filename, IndexSetList indexsetlist) throws IOException{ writeStringToFile(filename, indexsetlist.toString()); } // Running Gromacs commands from the Java code /** * Executes Gromacs commands from within the Java code and reads * the listed output files back into JGromacs objects. (Note that * the method can be used to execute not only Gromacs commands.) * The commands are run in the Unix shell (sh), so for example * shell pipes (>,>>,<,|) can also be used in the command line. * The first element of the returned array is the standard output * and next elements are the JGromacs objects read in. * @param command Gromacs command to be executed * @param filenames array of output file names to be read in * @return array of JGromacs objects read from the files * @throws IOException * */ public static Object[] runGromacsCommand(String command, String[] filenames) throws IOException{ Object[] ret = new Object[filenames.length+1]; String[] cmd = {"sh", "-c", command}; StringBuffer buf = new StringBuffer(); String line; Process p = Runtime.getRuntime().exec(cmd); BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream())); while ((line = input.readLine()) != null) buf.append(line+"\n"); input.close(); ret[0] = buf.toString(); for (int i = 0; i < filenames.length; i++) ret[i+1] = readFromFile(filenames[i]); return ret; } // Reading files automatically identifying their type /** * Reads a JGromacs object (Structure, IndexSetList, Trajectory or Sequence) from a file * automatically identifying the type of the file * @param filename Input file name with correct extension * @return JGromacs object * @throws IOException * */ public static Object readFromFile(String filename) throws IOException{ if (isTrajectoryFile(filename)) return readTrajectory(new Structure(), filename); if (isGROFile(filename)) return readStructureFromGRO(filename); if (isPDBFile(filename)) return readStructureFromPDB(filename); if (isNDXFile(filename)) return readIndexSetListFromNDX(filename); if (isFASTAFile(filename)) return readSequenceFromFASTA(filename); return null; } // Private methods helping the public methods private static boolean isTrajectoryFile(String fn){ return fn.toUpperCase().endsWith("XTC")|fn.toUpperCase().endsWith("TRR"); } private static boolean isGROFile(String fn){ return fn.toUpperCase().endsWith("GRO"); } private static boolean isPDBFile(String fn){ return fn.toUpperCase().endsWith("PDB"); } private static boolean isNDXFile(String fn){ return fn.toUpperCase().endsWith("NDX"); } private static boolean isFASTAFile(String fn){ return fn.toUpperCase().endsWith("FASTA"); } private static boolean isModelStartLine( String row){ return row.startsWith("MODEL"); } private static boolean isModelEndLine( String row){ return row.startsWith("ENDMDL"); } private static boolean isAtomLine( String row){ return row.startsWith("ATOM")|row.startsWith("HETATM"); } private static boolean isTitleLine(String row){ return row.startsWith("TITLE"); } private static ArrayList readFromFileToVector(String filename) throws IOException{ ArrayList ret = new ArrayList(); File file = new File(filename); BufferedReader input = new BufferedReader(new FileReader(file)); String line = null; while (( line = input.readLine()) != null) ret.add(line); input.close(); return ret; } private static ArrayList extractValues(String s){ s=s.replaceAll(" ", " "); s=s.replaceAll(" ", " "); s=s.replaceAll(" ", " "); s=s.replaceAll(" ", " "); s=s.replaceAll(" ", " "); s=s.replaceAll(" ", " "); s=s.trim(); ArrayList elements = new ArrayList(); while(s.indexOf(" ")>0){ String element = s.substring(0,s.indexOf(" ")); s = s.substring(s.indexOf(" ")+1,s.length()); elements.add(element); } elements.add(s); return elements; } private static PointList extractPointList(ArrayList rows){ PointList ret = new PointList(); String row = ""; Point3D point; for (int i = 0; i < rows.size(); i++) { row = (String)rows.get(i); if (row.indexOf(" x[")>0) { point = extractPoint(row); ret.addPoint(point); } } return ret; } private static Point3D extractPoint(String s){ String xstr = s.substring(s.indexOf("{")+1, s.indexOf(",")); s = s.substring(s.indexOf(",")+1,s.length()); String ystr = s.substring(0, s.indexOf(",")); s = s.substring(s.indexOf(",")+1,s.length()); String zstr = s.substring(0, s.indexOf("}")); return new Point3D(Double.valueOf(xstr),Double.valueOf(ystr),Double.valueOf(zstr)); } private static void writeStringToFile(String filename, String str) throws IOException{ File file = new File(filename); BufferedWriter output = new BufferedWriter(new FileWriter(file)); output.write(str); output.close(); } } source/jgromacs/io/IOMath.java000644 000000111751164062154600121760ustar /** * * Written by Márton Münz and Philip C Biggin * Copyright (c) University of Oxford, United Kingdom * Visit http://sbcb.bioch.ox.ac.uk/jgromacs/ * * This source code file is part of JGromacs v1.0. * * JGromacs v1.0 is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * JGromacs v1.0. is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with JGromacs v1.0. If not, see . * */ package jgromacs.io; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import jama.Matrix; /** * This class contains static methods for IO of ArrayList and Matrix objects * */ public class IOMath { // Input /** * Reads ArrayList from the given file * @param filename file name * @return file content as an ArrayList * @throws IOException */ public static ArrayList readArrayListFromFile(String filename) throws IOException{ ArrayList rows = readFromFileToVector(filename); ArrayList ret = new ArrayList(); for (int i = 0; i < rows.size(); i++) { String row = (String)rows.get(i); ret.add(Double.valueOf(row)); } return ret; } /** * Reads Matrix from the given file * @param filename file name * @return file content as a Matrix * @throws IOException */ public static Matrix readMatrixFromFile(String filename) throws IOException{ ArrayList rows = readFromFileToVector(filename); String firstrow = (String)rows.get(0); int dim = extractValues(firstrow).size(); Matrix ret = new Matrix(rows.size(),dim); for (int i = 0; i < rows.size(); i++) { String row = (String)rows.get(i); ArrayList elements = extractValues(row); for (int j = 0; j < elements.size(); j++) { ret.set(i, j, Double.valueOf((String)elements.get(j))); } } return ret; } // Output /** * Writes a scalar to the given file * @param scalar the scalar value * @param filename file name * @throws IOException */ public static void writeScalarToFile(double scalar, String filename) throws IOException{ File file = new File(filename); BufferedWriter output = new BufferedWriter(new FileWriter(file)); output.write(String.valueOf(scalar)); output.close(); } /** * Writes an ArrayList to the given file * @param list the ArrayList object * @param filename file name * @throws IOException */ public static void writeArrayListToFile(ArrayList list, String filename) throws IOException{ File file = new File(filename); BufferedWriter output = new BufferedWriter(new FileWriter(file)); for (int i = 0; i < list.size(); i++) { if (i>0) output.newLine(); output.write(list.get(i).toString()); } output.close(); } /** * Writes a Matrix to the given file * @param M the Matrix object * @param filename file name * @throws IOException */ public static void writeMatrixToFile(Matrix M, String filename) throws IOException{ File file = new File(filename); BufferedWriter output = new BufferedWriter(new FileWriter(file)); for (int i = 0; i < M.getRowDimension(); i++) { if (i>0) output.newLine(); for (int j = 0; j < M.getColumnDimension(); j++) { output.write(M.get(i, j)+" "); } } output.close(); } // Private methods private static ArrayList readFromFileToVector(String filename) throws IOException{ ArrayList ret = new ArrayList(); File file = new File(filename); BufferedReader input = new BufferedReader(new FileReader(file)); String line = null; while (( line = input.readLine()) != null) ret.add(line); input.close(); return ret; } private static ArrayList extractValues(String s){ s=s.replaceAll(" ", " "); s=s.replaceAll(" ", " "); s=s.replaceAll(" ", " "); s=s.replaceAll(" ", " "); s=s.replaceAll(" ", " "); s=s.replaceAll(" ", " "); s=s.trim(); ArrayList elements = new ArrayList(); while(s.indexOf(" ")>0){ String element = s.substring(0,s.indexOf(" ")); s = s.substring(s.indexOf(" ")+1,s.length()); elements.add(element); } elements.add(s); return elements; } } source/jgromacs/io/package-info.java000644 000000001611157566103200133730ustar /** * jgromacs.io provides parsers for reading and methods for writing GROMACS files */ package jgromacs.io;source/jgromacs/ui/000755 000000000001165162413600102135ustar source/jgromacs/ui/Application.java000644 000000475701164063315400133340ustar /** * * Written by Márton Münz and Philip C Biggin * Copyright (c) University of Oxford, United Kingdom * Visit http://sbcb.bioch.ox.ac.uk/jgromacs/ * * This source code file is part of JGromacs v1.0. * * JGromacs v1.0 is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * JGromacs v1.0. is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with JGromacs v1.0. If not, see . * */ package jgromacs.ui; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import jgromacs.data.IndexSetList; /** * Parent class of JGromacs applications. * You can extend this class to write JGromacs applications. * (See TemplateApplication.java !) * */ public abstract class Application { private static final int INPUT = 1; private static final int OUTPUT = 2; private static final int SETTING = 3; private String start_time = ""; private String end_time = ""; private String applicationName; private String author; private String description; private String version; private boolean writeLogFile = false; private String logFileName = "logfile.log"; /** * XML configuration file name * */ protected String XMLFileName = "template.xml"; private ArrayList flags = new ArrayList(); private ArrayList arguments = new ArrayList(); private boolean canRunWithoutArguments = false; // Inner class: Argument private class Argument { public int type = 1; public String description = ""; public boolean optional = false; public boolean given = false; public String value = ""; public Argument(int type, String description, boolean optional, String value) { super(); this.type = type; this.description = description; this.optional = optional; this.value = value; } } // End of inner class: Argument /** * Constructor * */ public Application(){ } /** * Don't override this method! * */ protected void run(String[] args){ readXML(); printWelcomeMessage(); if ((args.length>0)||(canRunWithoutArguments)) { if (askForHelp(args)) printHelpMessage(); else { analyzeArguments(args); start_time = getDateTime(); if (writeLogFile) writeStartInfoToLogFile(args); if (checkArguments()) runCore(); else { System.out.println("Fatal error: a compulsory argument is missing!"); } end_time = getDateTime(); printFinishedMessage(); writeEndInfoToLogFile(); } } } private void analyzeArguments(String[] args){ String flag = ""; for (int i = 0; i < args.length; i++) { if (i 0) { Element el = (Element)list.item(0); ret = el.getFirstChild().getNodeValue(); } return ret; } private String getDateTime(){ DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); Date date = new Date(); return dateFormat.format(date); } private boolean askForHelp(String[] args){ if (args.length==1){ if (args[0].equals("-h")) return true; else return false; } else return false; } private void printWelcomeMessage(){ System.out.println(); System.out.println(alignTextToCenter(";-) J G r o m a c s (-;",40)); System.out.println(); System.out.println(alignTextToCenter("a Java API for analysing protein motions",40)); System.out.println(); System.out.println(alignTextToCenter(";-) VERSION 1.0.1 (-;",40)); System.out.println(); System.out.println(); System.out.println(alignTextToCenter("Written by Marton Munz and Philip C Biggin",40)); System.out.println(alignTextToCenter("Copyright (c) University of Oxford, United Kingdom",40)); System.out.println(alignTextToCenter("visit http://sbcb.bioch.ox.ac.uk/jgromacs/",40)); System.out.println(); System.out.println(alignTextToCenter("This program is free software; you can redistribute it and/or",40)); System.out.println(alignTextToCenter("modify it under the terms of the GNU General Public License",40)); System.out.println(alignTextToCenter("as published by the Free Software Foundation; either version 3",40)); System.out.println(alignTextToCenter("of the License, or (at your option) any later version.",40)); System.out.println(); System.out.println(alignTextToCenter(";-) "+applicationName+" (-;",40)); System.out.println(alignTextToCenter("Version: "+version,40)); System.out.println(alignTextToCenter("Written by "+author,40)); System.out.println(); } private String alignTextToCenter(String text, int center){ int n = center-text.length()/2; StringBuffer buf = new StringBuffer(); for (int i = 0; i < n; i++) buf.append(" "); return buf.toString()+text; } private void printFinishedMessage(){ System.out.println(); System.out.println("---------------------------------------------------------------------------"); System.out.println(applicationName+" has successfully finished."); System.out.println("It has been running from "+start_time+" to "+end_time); System.out.println("---------------------------------------------------------------------------"); System.out.println(); } private void printHelpMessage(){ System.out.println("DESCRIPTION"); System.out.println("-----------"); System.out.println(description); System.out.println(); ArrayList inputFlags = new ArrayList(); ArrayList inputDescriptions = new ArrayList(); ArrayList inputIsOptional = new ArrayList(); ArrayList inputDefaults = new ArrayList(); ArrayList outputFlags = new ArrayList(); ArrayList outputDescriptions = new ArrayList(); ArrayList outputIsOptional = new ArrayList(); ArrayList outputDefaults = new ArrayList(); ArrayList settingFlags = new ArrayList(); ArrayList settingDescriptions = new ArrayList(); ArrayList settingIsOptional = new ArrayList(); ArrayList settingDefaults = new ArrayList(); String flag = ""; for (int i = 0; i < flags.size(); i++) { flag = flags.get(i); Argument arg = arguments.get(i); if (arg.type==INPUT){ inputFlags.add(flag); inputDescriptions.add(arg.description); inputDefaults.add(arg.value); inputIsOptional.add(arg.optional); } if (arg.type==OUTPUT){ outputFlags.add(flag); outputDescriptions.add(arg.description); outputDefaults.add(arg.value); outputIsOptional.add(arg.optional); } if (arg.type==SETTING){ settingFlags.add(flag); settingDescriptions.add(arg.description); settingDefaults.add(arg.value); settingIsOptional.add(arg.optional); } } if (inputFlags.size()>0) { System.out.println(" Inputs:"); System.out.println(); ArrayList flags = new ArrayList(); ArrayList descriptions = new ArrayList(); ArrayList optionals = new ArrayList(); ArrayList defs = new ArrayList(); int maxflag = 4; int maxdescription = 11; int maxoptional = 4; int maxdefs = 12; flags.add("Flag"); defs.add("DefaultValue"); optionals.add("Opt."); descriptions.add("Description"); for (int i = 0; i < inputFlags.size(); i++) { flags.add("-"+(String)inputFlags.get(i)); if (((String)inputFlags.get(i)).length()>maxflag) maxflag=((String)inputFlags.get(i)).length(); descriptions.add((String)inputDescriptions.get(i)); if (((String)inputDescriptions.get(i)).length()>maxdescription) maxdescription=((String)inputDescriptions.get(i)).length(); if ((Boolean)inputIsOptional.get(i)) optionals.add("Yes"); else optionals.add("No"); defs.add((String)inputDefaults.get(i)); if (((String)inputDefaults.get(i)).length()>maxdefs) maxdefs=((String)inputDefaults.get(i)).length(); } String format = " %1$-"+(maxflag+1)+"s %2$-"+(maxdefs+1)+"s %3$-"+(maxoptional+1)+"s %4$-"+(maxdescription+1)+"s\n"; System.out.format(format, flags.get(0),defs.get(0),optionals.get(0),descriptions.get(0)); System.out.print(" "); for (int i = 0; i < (maxflag+maxdescription+maxoptional+maxdefs+10); i++) System.out.print("-"); System.out.println(); for (int i = 1; i < flags.size(); i++) System.out.format(format, flags.get(i),defs.get(i),optionals.get(i),descriptions.get(i)); } if (outputFlags.size()>0) { System.out.println(); System.out.println(" Outputs:"); System.out.println(); ArrayList flags = new ArrayList(); ArrayList descriptions = new ArrayList(); ArrayList optionals = new ArrayList(); ArrayList defs = new ArrayList(); int maxflag = 4; int maxdescription = 11; int maxoptional = 4; int maxdefs = 12; flags.add("Flag"); defs.add("DefaultValue"); optionals.add("Opt."); descriptions.add("Description"); for (int i = 0; i < outputFlags.size(); i++) { flags.add("-"+(String)outputFlags.get(i)); if (((String)outputFlags.get(i)).length()>maxflag) maxflag=((String)outputFlags.get(i)).length(); descriptions.add((String)outputDescriptions.get(i)); if (((String)outputDescriptions.get(i)).length()>maxdescription) maxdescription=((String)outputDescriptions.get(i)).length(); if ((Boolean)outputIsOptional.get(i)) optionals.add("Yes"); else optionals.add("No"); defs.add((String)outputDefaults.get(i)); if (((String)outputDefaults.get(i)).length()>maxdefs) maxdefs=((String)outputDefaults.get(i)).length(); } String format = " %1$-"+(maxflag+1)+"s %2$-"+(maxdefs+1)+"s %3$-"+(maxoptional+1)+"s %4$-"+(maxdescription+1)+"s\n"; System.out.format(format, flags.get(0),defs.get(0),optionals.get(0),descriptions.get(0)); System.out.print(" "); for (int i = 0; i < (maxflag+maxdescription+maxoptional+maxdefs+10); i++) System.out.print("-"); System.out.println(); for (int i = 1; i < flags.size(); i++) System.out.format(format, flags.get(i),defs.get(i),optionals.get(i),descriptions.get(i)); } if (settingFlags.size()>0) { System.out.println(); System.out.println(" Settings:"); System.out.println(); ArrayList flags = new ArrayList(); ArrayList descriptions = new ArrayList(); ArrayList optionals = new ArrayList(); ArrayList defs = new ArrayList(); int maxflag = 4; int maxdescription = 11; int maxoptional = 4; int maxdefs = 12; flags.add("Flag"); defs.add("DefaultValue"); optionals.add("Opt."); descriptions.add("Description"); for (int i = 0; i < settingFlags.size(); i++) { flags.add("-"+(String)settingFlags.get(i)); if (((String)settingFlags.get(i)).length()>maxflag) maxflag=((String)settingFlags.get(i)).length(); descriptions.add((String)settingDescriptions.get(i)); if (((String)settingDescriptions.get(i)).length()>maxdescription) maxdescription=((String)settingDescriptions.get(i)).length(); if ((Boolean)settingIsOptional.get(i)) optionals.add("Yes"); else optionals.add("No"); defs.add((String)settingDefaults.get(i)); if (((String)settingDefaults.get(i)).length()>maxdefs) maxdefs=((String)settingDefaults.get(i)).length(); } String format = " %1$-"+(maxflag+1)+"s %2$-"+(maxdefs+1)+"s %3$-"+(maxoptional+1)+"s %4$-"+(maxdescription+1)+"s\n"; System.out.format(format, flags.get(0),defs.get(0),optionals.get(0),descriptions.get(0)); System.out.print(" "); for (int i = 0; i < (maxflag+maxdescription+maxoptional+maxdefs+10); i++) System.out.print("-"); System.out.println(); for (int i = 1; i < flags.size(); i++) System.out.format(format, flags.get(i),defs.get(i),optionals.get(i),descriptions.get(i)); } System.out.println(); } private boolean checkArguments(){ for (int i = 0; i < flags.size(); i++) { if ((!arguments.get(i).optional)&(!arguments.get(i).given)) return false; } return true; } /** * You can override this method to include your own code. * This is the entry point of your program. * */ protected abstract void runCore(); /** * Returns true if the attribute defined by the given flag was called by the user * @param flag attribute flag * */ protected boolean isArgumentGiven(String flag){ Argument arg = getArgumentByFlag(flag); return arg.given; } /** * Returns the value defined by the given attribute flag * @param flag attribute flag * @return value * */ protected String getArgumentValue(String flag){ Argument arg = getArgumentByFlag(flag); return arg.value; } /** * Asks the user which index set is to be selected from the index set list * @param list index set list to select from * @param question question to be asked * @return list index of selected index set */ protected int askIndexSetFromUser(IndexSetList list, String question){ System.out.println(" "+question); System.out.println(); for (int i = 0; i < list.getNumberOfIndexSets(); i++) System.out.println(" "+i+": "+list.getIndexSet(i).getName()+" ("+list.getIndexSet(i).getNumberOfIndices()+" atoms)"); System.out.println(); System.out.print(" Your selection: "); try { InputStreamReader isr = new InputStreamReader(System.in); BufferedReader br = new BufferedReader(isr); String nstring = br.readLine(); int n = Integer.valueOf(nstring); if ((n>=0) && (n. * */ package jgromacs.ui; /** * Template JGromacs application * */ public class TemplateApplication extends Application{ public TemplateApplication(){ super(); // Your XML configuration file: XMLFileName = "template.xml"; } public void runCore() { // Put your code here... // Use runCore() as you normally use the main() method! // It is the entry point of your program. // Accessing attributes is simple... // You can access the value corresponding to a given flag: String c_value = getArgumentValue("c"); System.out.println("Value assigned to flag -c was "+c_value); // You can ask if a flag was given in the attributes: boolean is_c_given = isArgumentGiven("c"); if (is_c_given) System.out.println("Flag -c was given in the attributes"); else System.out.println("Flag -c was NOT given in the attributes"); } public static void main(String[] args) { // Don't modify! TemplateApplication app = new TemplateApplication(); app.run(args); } } source/licence.txt000644 000001045131153321664400101400ustar GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . source/template.xml000644 000000013521144714247600103340ustar My Application Detailed description of my application Albert Einstein 1.0.1. c Coordinate (GRO) File whatever.gro o Alignment (FASTA) File whatever.fasta b begin frame 0